@cortexkit/opencode-openai-auth 1.0.0 → 1.0.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.
@@ -1,221 +0,0 @@
1
- import{Ab as t7,Bb as e7,Cb as eN,Db as XL,Eb as T1,Fb as JL,La as nG,Ma as sG,Na as Y6,Oa as z7,Pa as f8,Qa as zz,Ra as O7,Sa as _8,Ta as f0,Ua as J2,Va as aG,Wa as lX,Ya as XY,_a as kH,ab as m8,bb as cN,eb as lN,ib as jV,jb as dN,kb as iN,lb as nN,qb as SX,rb as IX,sb as sN,tb as aN,wb as oN,xb as rN,yb as tN}from"./index-eqh53k8v.js";import{Kb as DQ,Lb as O6,Mb as FQ,Nb as V5,Ob as g0,Pb as Q2,Qb as PQ,Rb as gZ}from"./index-jyr8y8k4.js";import{Tb as NH,Ub as LH,Vb as DH,Wb as vV,Xb as uN,Yb as l7}from"./index-rv08jmd4.js";import{dc as M2,ec as s7,gc as Z0,hc as EB,jc as hJ,kc as fJ,lc as n0,nc as jH}from"./index-bmd7x5aq.js";import{pc as FH,rc as pN}from"./index-766sfrh5.js";import{uc as KY}from"./index-b3q3j39x.js";import{createHash as jI,randomUUID as qI}from"node:crypto";import{mkdirSync as NI,readFileSync as LI,renameSync as DI,statSync as FI,writeFileSync as PI}from"node:fs";import BG from"node:os";import{join as OI}from"node:path";function oG(X,J,$){let Y=J.rateLimitMarks?.get(X);if(Y!==void 0&&$<Y)return{id:X,reason:"rate-limited",until:Y};let G=J.refreshBackoff?.get(X);if(G!==void 0&&$<G)return{id:X,reason:"refresh-backoff",until:G};return}function NL(X,J,$,Y){if(J.limits.length===0)return{id:X,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let Q of $)if(!J.limits.some((z)=>z.label===Q))return{id:X,stage:1,gate:3,reason:"unknown-window",window:{scope:J.scope,label:Q},pullRequested:!0};let G=J.limits.filter(aG);for(let Q of G)if(lX(Q,Y)===void 0)return{id:X,stage:1,gate:4,reason:"unknown-reset",window:{scope:Q.scope,label:Q.label},pullRequested:!0};for(let Q of G){let z=lX(Q,Y);if(z!==void 0&&typeof Q.resetsAt==="string")return{id:X,stage:1,gate:5,reason:"exhausted",window:{scope:Q.scope,label:Q.label},resetsAt:Q.resetsAt,resetAtMs:z}}return}function m9(X){let J=X.scope??nG,$=X.requiredLabels??sG,Y=[],G=[],Q=[];for(let j of X.rows){let q=oG(j.id,X,X.now);if(q){Y.push(q);continue}if(j.kind==="api-key"){Q.push({id:j.id,kind:j.kind});continue}let K=f0(j.quota,J),L=NL(j.id,K,$,X.now);if(L){G.push(L);continue}Q.push({id:j.id,kind:j.kind,projection:K})}let z=new Map(Q.flatMap((j)=>{let q=J2(j.projection,X.now);return q?[[j.id,q]]:[]})),Z=z.size>0&&z.size===Q.length,W=[];for(let j of Q){let q=z.get(j.id);if(q===void 0)W.push(j);else if(Z)W.push({...j,lastPath:!0});else G.push({id:j.id,stage:2,reason:"budget-spent",...q})}let B=new Map(X.rows.map((j,q)=>[j.id,q])),H=(j,q)=>(B.get(j.id)??0)-(B.get(q.id)??0);G.sort(H);let U=G.filter((j)=>("pullRequested"in j)).map((j)=>j.id);for(let j of U)X.requestPull?.(j);return{admitted:W,refused:G,excluded:Y,pulls:U}}var $2="main";function dX(X){switch(X){case"sticky-balanced":return{mode:"sticky-balanced",placement:"roster"};case"main-first":return{mode:"ordered",placement:"main-first"};case"fallback-first":return{mode:"ordered",placement:"fallback-first"};default:return{mode:"ordered",placement:"roster"}}}function I1(X,J,$=$2){if(J==="roster"||!X.includes($))return[...X];let Y=X.filter((G)=>G!==$);return J==="main-first"?[$,...Y]:[...Y,$]}function iX(X){let J=m9(X),$=new Set(J.admitted.map((G)=>G.id));return{order:I1(X.rows.map((G)=>G.id),X.placement??"roster",X.formerMainId).filter((G)=>$.has(G)&&X.killswitch?.get(G)!==!1),admission:J}}function nX(X,J,$){let Y=J.at(-1);if(Y!==void 0){if(Y.status===void 0||!$.includes(Y.status))return}let G=new Set(J.map((Q)=>Q.id));return X.find((Q)=>!G.has(Q))}function sX(X,J,$){if(!J.has(X.accountId))return!1;return!(typeof X.wireIdentity==="string"&&typeof $==="string"&&X.wireIdentity!==$)}function LL(X,J,$){let Y=new Map;for(let[G,Q]of X){if(G===$)continue;if(Q.quotaCheckedAt!==J.get(Q.accountId))continue;Y.set(Q.accountId,(Y.get(Q.accountId)??0)+(Q.inputBytes??0))}return Y}var rX=900000,tG=0.016666666666666666,aX=0.000001;function Y2(X,J){for(let $ of[X?.checkedAt,J])if(typeof $==="number"&&Number.isFinite($))return $;return}function eG(X){if(X===401||X===403)return"permanent";if(X===void 0||X===0||!Number.isFinite(X)||X>=500&&X<=599||X===429)return"transient";return"healthy"}function XQ(X){return X.limits.filter((J)=>J.kind==="reading").sort((J,$)=>{let Y=J.windowMinutes!==void 0,G=$.windowMinutes!==void 0;if(Y!==G)return Y?-1:1;if(Y&&G)return($.windowMinutes??0)-(J.windowMinutes??0);return 0})}function tX(X){let J=(X.classifyStatus??eG)(X.status);if(J==="permanent")return{action:"migrate",reason:"permanent"};if(!X.quota)return{action:"retain",reason:"unknown"};let $=Y2(X.quota,X.quotaCheckedAt);if($===void 0||!Number.isFinite($)||X.now-$>rX)return{action:"retain",reason:"stale"};if(X.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let G of XQ(X.quota)){let Q=G.remainingPercent;if(typeof Q==="number"&&Number.isFinite(Q)&&Q<=0)return{action:"migrate",reason:"exhausted",window:{scope:G.scope,label:G.label},...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}}}let Y=J2(X.quota,X.now);if(Y)return{action:"migrate",reason:"exhausted",resetsAt:Y.resetsAt};return{action:"retain",reason:J}}function oX(X,J,$){let Y=Math.max(0,X.remainingPercent-J);if(Y<=0)return 0;if(!X.resetsAt)return Y;let G=Date.parse(X.resetsAt);if(!Number.isFinite(G)||G<=$)return Y;let Q=Math.max((G-$)/3600000,tG);return Y/Q}function rG(X,J){if(X<J)return-1;if(X>J)return 1;return 0}function DL(X,J){if(!X.quota)return;let $=Y2(X.quota,X.quotaCheckedAt);if($===void 0||J-$>rX)return;let Y=XQ(X.quota).map((z)=>oX({remainingPercent:z.remainingPercent??Number.NaN,...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}},X.reservePercent[z.label]??0,J)),G=X.quota.budget;if(G&&typeof G.remainingPercent==="number"&&Number.isFinite(G.remainingPercent))Y.push(oX({remainingPercent:G.remainingPercent,...G.resetsAt===void 0?{}:{resetsAt:G.resetsAt}},0,J));let Q=Y.length>0?Math.min(...Y):0;return Q>0?{candidate:X,quotaCheckedAt:$,weight:Q}:void 0}function JQ(X){let J=X.candidates.filter((G)=>G.killswitchPasses!==!1);if(X.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(J.length===0)return;let $=J.map((G)=>DL(G,X.now)).filter((G)=>G!==void 0);if($.length>0){$.sort((Q,z)=>{let Z=((X.pendingBytes.get(Q.candidate.accountId)??0)+X.requestBytes)/Math.max(Q.weight,aX),W=((X.pendingBytes.get(z.candidate.accountId)??0)+X.requestBytes)/Math.max(z.weight,aX);return Z-W||Q.candidate.configuredOrder-z.candidate.configuredOrder||rG(Q.candidate.accountId,z.candidate.accountId)});let G=$[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}X.onEmptyWeightedSet?.();let Y=[...J].sort((G,Q)=>{let z=(G.resetCreditsApplicable??0)>0?1:0;return((Q.resetCreditsApplicable??0)>0?1:0)-z||G.configuredOrder-Q.configuredOrder||rG(G.accountId,Q.accountId)})[0];if(!Y)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Y.accountId,quotaCheckedAt:Y2(Y.quota,Y.quotaCheckedAt),source:"mode-fallback"}}function eX(X){let J=m9(X),$=new Map(J.admitted.map((K)=>[K.id,K])),Y=new Map(J.refused.map((K)=>[K.id,K])),G=new Set(J.excluded.map((K)=>K.id)),Q=new Set(X.rows.map((K)=>K.id)),z=X.pin!==void 0&&sX(X.pin,Q,X.identities?.get(X.pin.accountId));if(z&&X.pin){let K=$.get(X.pin.accountId);if(K&&X.killswitch?.get(K.id)!==!1)return{outcome:"dispatch",accountId:K.id,source:"pin",...K.projection?.checkedAt===void 0?{}:{quotaCheckedAt:K.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:J}}let Z=X.pin?Y.get(X.pin.accountId):void 0,W=z&&X.pin!==void 0&&X.refusedPinPolicy==="move-on-confirmed-exhaustion"&&(X.killswitch?.get(X.pin.accountId)===!1||Z?.reason==="exhausted"||Z?.reason==="budget-spent"),B=(K)=>{return(typeof X.rowReservePercent==="function"?X.rowReservePercent(K):X.rowReservePercent?.get(K.id))??X.reservePercent??{}},H=X.scope,U=X.rows.map((K,L)=>({row:K,configuredOrder:L})).filter(({row:K})=>!G.has(K.id)).map(({row:K,configuredOrder:L})=>{let F=X.killswitch?.get(K.id),O=X.resetCreditsApplicable?.get(K.id);return{accountId:K.id,quota:K.kind==="api-key"?void 0:$.get(K.id)?.projection??f0(K.quota,H),reservePercent:B(K),configuredOrder:L,...O===void 0?{}:{resetCreditsApplicable:O},...F===void 0?{}:{killswitchPasses:F}}}),j=[],q=z?{action:"retain"}:X.pin?{action:"clear"}:{action:"none"};while(U.length>0){let K=JQ({candidates:U,pendingBytes:X.pendingBytes??new Map,requestBytes:X.requestBytes,now:X.now,...X.onEmptyWeightedSet?{onEmptyWeightedSet:X.onEmptyWeightedSet}:{}});if(!K)break;let L=Y.get(K.accountId);if(L){j.push(L),U=U.filter((O)=>O.accountId!==K.accountId);continue}let F=X.identities?.get(K.accountId);return{outcome:"dispatch",accountId:K.accountId,source:K.source,...K.quotaCheckedAt===void 0?{}:{quotaCheckedAt:K.quotaCheckedAt},pin:z&&!W?{action:"retain"}:{action:"assign",pin:{accountId:K.accountId,inputBytes:X.requestBytes,...F===void 0?{}:{wireIdentity:F},...K.quotaCheckedAt===void 0?{}:{quotaCheckedAt:K.quotaCheckedAt}}},refusedSelections:j,admission:J}}return{outcome:"no-admissible-account",pin:q,refusedSelections:j,admission:J}}class K0 extends Error{operation;rowId;phase;retryable;kind;committed;constructor(X){super(X.message??`${X.operation} failed (${X.kind}, ${X.phase})`,X.cause===void 0?void 0:{cause:X.cause});this.name="PoolOperationError",this.operation=X.operation,this.rowId=X.rowId,this.phase=X.phase,this.retryable=X.retryable,this.kind=X.kind,this.committed=X.committed}}class G2 extends Error{operation;constructor(X){super(`${X} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=X}}var b1="identity-contradicted: ",X5="duplicate-identity";function K9(X,J,$){let Y=X.rosterRow(J);if(!Y)return;Y.enabled=!1;let G=X.entry(J)??{credentialEpoch:1,needsFirstReading:!0},Q=typeof G.disabledReason==="string"&&G.disabledReason.startsWith("identity-contradicted: ");X.setEntry(J,{...G,disabledReason:Q?G.disabledReason:$})}function b4(X,J){let $=X.rosterRow(J);if(!$)return;$.enabled=!0;let Y=X.entry(J);if(Y&&"disabledReason"in Y){let G={...Y};delete G.disabledReason,X.setEntry(J,G)}}function k1(X,J){let $=X.rows().filter((G)=>G.invalid===void 0&&!G.staged&&G.type==="oauth"&&G.enabled&&G.identity===J),Y=[];for(let G of $.slice(1))K9(X,G.id,"duplicate-identity"),Y.push(G.id);return Y}function u9(X,J,$){let Y=X.rosterRow(J);if(!Y)return[];return Y.accountId=$,k1(X,$)}import{readFile as yL}from"node:fs/promises";import{setTimeout as hL}from"node:timers/promises";import{AsyncLocalStorage as FL}from"node:async_hooks";var $Q=new FL;function W6(X){if($Q.getStore()!==void 0)throw new G2(X)}function O8(X,J){return $Q.run(X,async()=>await J())}async function YQ(X,J,$,Y,G){if(!J)return;try{await O8(X,()=>J($,Y))}catch(Q){G?.warn("store failure hook threw; the original failure stands",{operation:X,rowId:$,error:Q instanceof Error?Q.message:String(Q)})}}var J5=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function PL(X,J,$){let Y=(z)=>{try{let Z=$.onLockEvent?.({type:z,name:X.name,path:X.path});if(Z&&(typeof Z==="object"||typeof Z==="function")&&"then"in Z&&typeof Z.then==="function")Promise.resolve(Z).catch(()=>{})}catch{}},G={...J,...OL(X)},Q=performance.now();for(;;){let z=await g0({name:X.name,path:X.path,ttlMs:G.ttlMs,now:$.now,renew:G.renew,onContended:()=>Y("contended"),...G.renewIntervalMs!==void 0?{renewIntervalMs:G.renewIntervalMs}:{},...$.onLockStep?{onStep:(B)=>$.onLockStep?.({name:X.name,path:X.path},B)}:{}});if(z){Y("acquired");let B={name:X.name,path:X.path,assertOwned:()=>z.assertOwned(),release:async()=>{await z.release(),Y("released")}};try{await B.assertOwned()}catch(H){throw await B.release(),H}return B}let Z=G.timeoutMs-(performance.now()-Q);if(Z<=0)throw new Q2({target:X.path,name:X.name,timeoutMs:G.timeoutMs});let W=Math.floor(Math.random()*(G.retryMs+1));await new Promise((B)=>setTimeout(B,Math.min(G.retryMs+W,Z)))}}function OL(X){let J={};if(X.ttlMs!==void 0)J.ttlMs=X.ttlMs;if(X.timeoutMs!==void 0)J.timeoutMs=X.timeoutMs;if(X.retryMs!==void 0)J.retryMs=X.retryMs;if(X.renew!==void 0)J.renew=X.renew;if(X.renewIntervalMs!==void 0)J.renewIntervalMs=X.renewIntervalMs;return J}class j9{defaults;env;held=[];constructor(X,J){this.defaults=X,this.env=J}async acquire(X){let J=await PL(X,this.defaults,this.env);return this.held.push(J),await this.assertAll(),J}async assertAll(){for(let X of this.held)await X.assertOwned()}async releaseTo(X){while(this.held.length>X)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}function p9(X,J,$){if($!==void 0)throw new K0({operation:X,rowId:J,kind:"row-staged",phase:X==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${J} is reserved for roster publication`})}import{createHash as k4}from"node:crypto";var E0="commonAuthPool",q9=1,X8="rows",z2="retiredEpochs",x4=1,$5=300000,_0=E0;function ML(X){let J=JSON.parse(JSON.stringify(X)),$=(Y)=>{if(Array.isArray(Y))return`[${Y.map($).join(",")}]`;if(y(Y))return`{${Object.keys(Y).sort().map((G)=>`${JSON.stringify(G)}:${$(Y[G])}`).join(",")}}`;return JSON.stringify(Y)};return $(J)}function c9(X){return k4("sha256").update(ML(X)).digest("hex")}function GQ(X){if(!y(X)||Object.keys(X).length!==1||typeof X.reservation!=="string"||!X.reservation)return;return{reservation:X.reservation}}function _L(X){if(!y(X)||typeof X.reservation!=="string"||!X.reservation||typeof X.disabledReason!=="string")return;if(Object.keys(X).some((J)=>!["reservation","label","disabledReason","providerState"].includes(J)))return;if("label"in X&&typeof X.label!=="string")return;if("providerState"in X&&(typeof X.providerState!=="string"||!/^[a-f0-9]{64}$/.test(X.providerState)))return;return X}var P6="commonAuthProviderState";function y(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}var AL=new Set(["__proto__","constructor","prototype"]);function x1(X){if(typeof X!=="string"||X.length===0)return"id must be non-empty";if(X.trim()!==X)return"id must not carry surrounding whitespace";if(AL.has(X))return"id is a reserved object key";return}function Y5(X){let J=typeof X==="string"?X.trim():"";if(!J)return!1;try{let $=new URL(J);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}function QQ(X){return X.type==="oauth"?`oauth\x00${X.refresh}`:`api\x00${X.apiKey}`}function J8(X){return k4("sha256").update(QQ(X)).digest("hex")}function M8(X){return k4("sha256").update(`credential-stamp\x00${QQ(X)}`).digest("hex")}function n8(X){let J=X.type==="oauth"?["oauth",typeof X.access==="string"?X.access:null,X.refresh,typeof X.expires==="number"&&Number.isFinite(X.expires)?X.expires:null]:["api",X.apiKey,X.baseURL.trim(),X.authHeader??"authorization-bearer"];return k4("sha256").update(`credential-dispatch\x00${JSON.stringify(J)}`).digest("hex")}function G5(X,J,$,Y={}){return{credentialEpoch:J,digest:M8(X),dispatch:n8(X),binding:{...$},...Y.replace?{replace:!0}:{},...Y.providerState!==void 0?{providerState:Y.providerState}:{}}}function w1(X,J){let $=X?.credentialBound?X.credentialBound(J):J;return k4("sha256").update(`provider-state\x00${JSON.stringify($??null)}`).digest("hex")}function w4(X,J,$,Y){if(!J||$===void 0)return;if(!y(X)||!Object.hasOwn(X,P6))return;let G=S6(X[_0]);if(!G||G.providerState===void 0||G.digest!==M8(J)||G.credentialEpoch!==$||G.binding?.identity!==Y)return;return G.providerState}function $6(X){return Number.isSafeInteger(X)&&X>=1}function S6(X){if(!y(X))return;let J=X.credentialEpoch;if(!$6(J))return;if(typeof X.digest!=="string")return;if("dispatch"in X&&typeof X.dispatch!=="string")return;if("replace"in X&&X.replace!==!0)return;if("providerState"in X&&typeof X.providerState!=="string")return;let $="staged"in X?_L(X.staged):void 0;if("staged"in X&&!$)return;let Y={...$?{staged:$}:{},...typeof X.dispatch==="string"?{dispatch:X.dispatch}:{},...X.replace===!0?{replace:!0}:{},...typeof X.providerState==="string"?{providerState:X.providerState}:{}};if(!("binding"in X))return"dispatch"in X||"replace"in X||"providerState"in X||"staged"in X?void 0:{credentialEpoch:J,digest:X.digest};let G=X.binding;if(!y(G))return;if("identity"in G&&(typeof G.identity!=="string"||!G.identity))return;if("baseURL"in G&&!Y5(G.baseURL))return;if("authHeader"in G&&G.authHeader!=="authorization-bearer"&&G.authHeader!=="x-api-key")return;return{credentialEpoch:J,digest:X.digest,...Y,binding:{...typeof G.identity==="string"?{identity:G.identity}:{},...typeof G.baseURL==="string"?{baseURL:G.baseURL.trim()}:{},...G.authHeader==="authorization-bearer"||G.authHeader==="x-api-key"?{authHeader:G.authHeader}:{}}}}function TL(X,J,$){if(X.identity!==$)return!1;if(X.baseURL!==void 0&&(J.type!=="api"||J.baseURL!==X.baseURL))return!1;if(X.authHeader!==void 0&&(J.type!=="api"||J.authHeader!==X.authHeader))return!1;return!0}function RL(X,J,$,Y){if(!X)return"none";if(!y(Y)||!Object.hasOwn(Y,_0))return"missing";let G=S6(Y[_0]);if(!G)return"malformed";if(G.digest!==M8(X))return"mismatched";if(G.dispatch===void 0)return"legacy";if(G.credentialEpoch!==J)return"mismatched";if(!G.binding||!TL(G.binding,X,$))return"mismatched";if(G.dispatch!==n8(X))return"mismatched";return"bound"}function zQ(X){if(!X.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in X)return{status:"error",reason:"config file is not valid JSON"};let J=X.value;if(!y(J))return{status:"error",reason:"config root is not an object"};if("accounts"in J&&!Array.isArray(J.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(E0 in J))return Array.isArray(J.accounts)?{status:"pending-migration",config:J}:{status:"ready",exists:!0,config:J};let $=J[E0];if(!y($))return{status:"error",reason:`${E0} is not an object`};let Y=$.schemaVersion;if(typeof Y!=="number"||!Number.isInteger(Y)||Y<1)return{status:"error",reason:`${E0}.schemaVersion is invalid`};if(Y>q9)return{status:"error",reason:`${E0}.schemaVersion ${Y} is newer than ${q9}`};if(X8 in $&&!y($[X8]))return{status:"error",reason:`${E0}.${X8} is not an object`};return{status:"ready",exists:!0,config:J}}function ZQ(X){if(!X.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in X)return{status:"error",reason:"state file is not valid JSON"};if(!y(X.value))return{status:"error",reason:"state root is not an object"};if("accounts"in X.value&&!y(X.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:X.value}}function v1(X){return Array.isArray(X.accounts)?X.accounts:[]}function WQ(X){let J=X[E0];if(!y(J))return{};let $=J[X8];return y($)?$:{}}function CL(X){return y(X.accounts)?X.accounts:{}}function EL(X){if(!y(X))return"not an object";let J=x1(X.id);if(J)return J;if(X.type==="api")return Y5(X.baseURL)?void 0:"invalid baseURL";if(X.type==="oauth")return;return"unknown type"}function SL(X,J){if(!y(X))return;let $=X.credentialEpoch;if(!$6($))return;if("needsFirstReading"in X&&typeof X.needsFirstReading!=="boolean")return;if("disabledReason"in X&&typeof X.disabledReason!=="string")return;if("quota"in X&&!J.validate(X.quota))return;if("staged"in X&&!GQ(X.staged))return;return{credentialEpoch:$,needsFirstReading:X.needsFirstReading===!0,...typeof X.disabledReason==="string"?{disabledReason:X.disabledReason}:{},..."quota"in X?{quota:X.quota}:{}}}function IL(X,J){if(!y(J))return;if(X.type==="api"){let Y=typeof J.apiKey==="string"?J.apiKey.trim():"";if(!Y)return;return{type:"api",apiKey:Y,baseURL:String(X.baseURL).trim(),authHeader:X.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if(X.corrupt===!0)return;let $=J.refresh;if(typeof $!=="string"||!$.trim())return;return{type:"oauth",refresh:$,...typeof J.access==="string"?{access:J.access}:{},...typeof J.expires==="number"?{expires:J.expires}:{},...typeof J.lastRefreshedAt==="number"?{lastRefreshedAt:J.lastRefreshedAt}:{}}}function Z2(X,J){return v1(X).find(($)=>y($)&&$.id===J)}function BQ(X){if(!y(X[E0]))X[E0]={};return X[E0]}function Q5(X){let J=BQ(X);if(!y(J[X8]))J[X8]={};return J[X8]}function N9(X,J){let $=WQ(X),Y=Object.hasOwn($,J)?$[J]:void 0;return y(Y)?Y:void 0}function W2(X,J,$){Object.defineProperty(Q5(X),J,{value:$,enumerable:!0,writable:!0,configurable:!0})}function HQ(X,J){let $=X[E0];if(!y($))return;let Y=$[z2];if(!y(Y)||!Object.hasOwn(Y,J))return;let G=Y[J];return $6(G)?G:void 0}function VQ(X,J){let $=N9(X,J)?.credentialEpoch;return $6($)?$:void 0}function B2(X,J){return Math.max(HQ(X,J)??0,VQ(X,J)??0)+1}function UQ(X,J){let $=[...J];if($.length===0)return;let Y=BQ(X),G=y(Y[z2])?Y[z2]:{},Q={},z=(Z,W)=>Object.defineProperty(Q,Z,{value:W,enumerable:!0,writable:!0,configurable:!0});for(let[Z,W]of Object.entries(G))if($6(W))z(Z,W);for(let Z of $)z(Z,Math.max(HQ(X,Z)??0,VQ(X,Z)??1));Y[z2]=Q}function L9(X,J,$,Y){let G=WQ(X),Q=CL(J),z=new Set,Z=[];for(let W of v1(X)){let B=EL(W),H=y(W)&&typeof W.id==="string"?W.id:void 0,U=H===void 0?void 0:G[H],j=y(U)&&Object.hasOwn(U,"staged"),q=j?GQ(U.staged):void 0;if(B||!y(W)||H===void 0||z.has(H)){if(H!==void 0&&!z.has(H))z.add(H);if(H!==void 0)Z.push({id:H,type:y(W)&&W.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(G,H),candidate:!1,invalid:"roster",stamp:"none",...q?{staged:q}:{}});continue}z.add(H);let K=W.type==="api"?"api":"oauth",L=Object.hasOwn(G,H),F=L?SL(G[H],$):void 0,O=IL(W,Q[H]),_=W.enabled!==!1,C=F?F.credentialEpoch:L?void 0:1,N=typeof W.accountId==="string"&&W.accountId?W.accountId:void 0,P={id:H,type:K,enabled:_,needsFirstReading:F?F.needsFirstReading:K==="oauth",hasEntry:L,candidate:!1,...typeof W.label==="string"?{label:W.label}:{},...typeof W.addedAt==="number"?{addedAt:W.addedAt}:{},...N!==void 0?{identity:N}:{},...O?{credential:O,fingerprint:J8(O)}:{},...F?{credentialEpoch:F.credentialEpoch}:{},...q?{staged:q}:{},...F?.disabledReason!==void 0?{disabledReason:F.disabledReason}:{},...F&&"quota"in F?{quota:F.quota}:{},...bL(Q[H],O,C,N,Y),stamp:RL(O,C,N,Q[H])};if(L&&!F)P.invalid="entry";else P.candidate=_&&O!==void 0&&!j;Z.push(P)}return Z}function bL(X,J,$,Y,G){if(!y(X)||!Object.hasOwn(X,P6))return{};let Q=w4(X,J,$,Y);if(Q===void 0)return{providerStateDropped:"uncovered"};let z=X[P6];if(!G?.validate(z))return{providerStateDropped:"invalid"};if(w1(G,z)!==Q)return{providerStateDropped:"uncovered"};return{providerState:z}}function x0(X){return X.identity??X.id}function v4(X,J){if(X===void 0||X>J+$5)return J;return Math.max(J,X+1)}function z5(X,J){return v4(X,J)>J+$5}function y1(X){let{id:J,credential:$,identity:Y,label:G,addedAt:Q}=X;return{id:J,...G!==void 0?{label:G}:{},type:$.type,addedAt:Q,...Y!==void 0?{accountId:Y}:{},...$.type==="api"?{baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"}:{}}}function KQ(X,J){if(X.type==="api")return{apiKey:X.apiKey};return{...X.access!==void 0?{access:X.access}:{},refresh:X.refresh,...X.expires!==void 0?{expires:X.expires}:{},...J!==void 0?{lastRefreshedAt:J}:{}}}function jQ(X,J){if(X.type==="api")return{...X,baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"};return{...X,...J!==void 0?{lastRefreshedAt:J}:{}}}function qQ(X,J={}){if(!y(X))return"credential must be an object";if(X.type==="oauth"){if(typeof X.refresh!=="string"||!X.refresh.trim())return"oauth credential needs a refresh token";return}if(X.type==="api"){if(typeof X.apiKey!=="string"||!X.apiKey.trim())return"api credential needs an api key";if(X.apiKey.trim()!==X.apiKey)return"api key must not carry surrounding whitespace";if(!(J.baseURLOptional&&X.baseURL===void 0)&&!Y5(X.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var H2="transition",NQ="transitionMark";function kL(X){if(!y(X))return;let J=X[H2];if(!y(J))return;if(typeof J.mark!=="string"||J.mark.length===0)return;if(J.enabled===!0)return{mark:J.mark,enabled:!0};if(J.enabled===!1&&typeof J.reason==="string")return{mark:J.mark,enabled:!1,reason:J.reason};return}function y4(X,J,$){if($.enabled)b4(X,J);else K9(X,J,$.reason??"");if(!X.rosterRow(J))return;let Y=X.entry(J)??{credentialEpoch:1,needsFirstReading:!0};if(X.setEntry(J,{...Y,[NQ]:$.mark}),!$.enabled)return;let G=X.rows().find((Q)=>Q.id===J);if(G?.type==="oauth"&&G.identity!==void 0)k1(X,G.identity)}function xL(X,J){if(X.type!=="api")return X;return{...X,...J.baseURL!==void 0?{baseURL:J.baseURL}:{},...J.authHeader!==void 0?{authHeader:J.authHeader}:{}}}function wL(X){if(!X.binding)return!1;return X.replace===!0||X.dispatch===void 0}function vL(X,J,$,Y={}){let G=y(J.accounts)?J.accounts:{},Q=new Map;for(let z of L9(X,J,$)){if(z.invalid||z.staged||!z.credential)continue;let Z=Object.hasOwn(G,z.id)?G[z.id]:void 0;if(!y(Z))continue;let W=S6(Z[_0]);if(!W?.binding)continue;if(W.digest!==M8(z.credential))continue;let B=z.credentialEpoch??1;if(W.credentialEpoch>B){if(!wL(W))continue;if(Y.requireCredentialStamps){if(W.dispatch===void 0)continue;if(W.dispatch!==n8(xL(z.credential,W.binding)))continue}Q.set(z.id,{kind:"replace",stamp:{...W,binding:W.binding}})}else if(W.credentialEpoch===B&&W.dispatch!==void 0&&W.dispatch===n8(z.credential)&&W.binding.identity!==void 0&&z.identity===void 0)Q.set(z.id,{kind:"identity",identity:W.binding.identity});else if(W.credentialEpoch===B&&W.binding.identity===z.identity){if(Y.requireCredentialStamps&&W.dispatch!==n8(z.credential))continue;let H=kL(Z[_0]);if(H&&N9(X,z.id)?.[NQ]!==H.mark)Q.set(z.id,{kind:"transition",transition:H})}}return Q}function Z5(X,J,$,Y){let Q={...X.entry(J)??{},credentialEpoch:$,needsFirstReading:!0};if(delete Q.quota,Y.identity!==void 0&&typeof Q.disabledReason==="string"&&Q.disabledReason.startsWith(b1))delete Q.disabledReason;X.setEntry(J,Q);let z=X.rosterRow(J);if(!z)return;if(Y.identity!==void 0)z.accountId=Y.identity;else delete z.accountId;if(Y.baseURL!==void 0)z.baseURL=Y.baseURL;if(Y.authHeader!==void 0)z.authHeader=Y.authHeader}function W5(X,J,$,Y={}){let G=vL(X,J,$,Y);if(G.size===0)return{config:X,torn:[]};let Q=structuredClone(X),z={rows:()=>L9(Q,J,$),rosterRow:(Z)=>Z2(Q,Z),entry:(Z)=>N9(Q,Z),setEntry:(Z,W)=>W2(Q,Z,W)};for(let[Z,W]of G)if(W.kind==="replace")Z5(z,Z,W.stamp.credentialEpoch,W.stamp.binding);for(let[Z,W]of G)if(W.kind==="identity")u9(z,Z,W.identity);else if(W.kind==="transition")y4(z,Z,W.transition);else if(W.stamp.binding.identity!==void 0)k1(z,W.stamp.binding.identity);return{config:Q,torn:[...G.keys()]}}function B5(X,J,$,Y={}){let{config:G,torn:Q}=W5(X,J,$,Y),z=L9(G,J,$,Y.providerState);for(let Z of z){if(Q.includes(Z.id))Z.torn=!0,Z.candidate=!1;if(Y.requireCredentialStamps&&Z.stamp!=="bound")Z.unbound=!0,Z.candidate=!1}return z}async function H5(X){try{return await yL(X,"utf8")}catch(J){if(J.code==="ENOENT")return;throw J}}function LQ(X){if(X===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse(X)}}catch(J){return{exists:!0,parseError:J}}}async function M6(X){for(let J=0;J<3;J++){let $=await H5(X.configPath),Y=await H5(X.statePath),G=await H5(X.configPath);if($!==G){if(J<2)await hL(2+Math.floor(Math.random()*4));continue}let Q=zQ(LQ($));if(Q.status==="error")return{status:"error",file:"config",reason:Q.reason};let z=ZQ(LQ(Y));if(z.status==="error")return{status:"error",file:"state",reason:z.reason};if(Q.status==="pending-migration")return{status:"pending-migration",config:Q.config};return{status:"ready",configExists:Q.exists,stateExists:z.exists,config:Q.config,state:z.state,rows:B5(Q.config,z.state,X.codec,{requireCredentialStamps:X.requireCredentialStamps===!0,...X.providerState?{providerState:X.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function $8(X,J,$,Y="before-first-write"){if(X.status==="error"&&X.kind==="snapshot-contended")return new K0({operation:J,...$!==void 0?{rowId:$}:{},phase:Y,kind:"snapshot-contended",retryable:!0,message:X.reason});return new K0({operation:J,...$!==void 0?{rowId:$}:{},phase:Y,retryable:!1,kind:X.status==="pending-migration"?"pending-migration":"load-error",message:X.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${X.file} file cannot be loaded: ${X.reason}`})}class OQ{ctx;snapshot;locks;progress;info;config;state;constructor(X,J,$,Y,G){this.ctx=X,this.snapshot=J,this.locks=$,this.progress=Y,this.info=G,this.config=structuredClone(J.config),this.state=structuredClone(J.state)}rows(){return B5(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row(X){return this.rows().find((J)=>J.id===X)}reservation(X){if(this.rosterRow(X)){let $=this.entry(X);return $&&Object.hasOwn($,"staged")?$.staged:void 0}let J=this.stateAccount(X)?.[_0];return y(J)&&Object.hasOwn(J,"staged")?J.staged:void 0}assertNotStaged(X){p9(this.info.operation,X,this.reservation(X))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow(X){return this.roster(),Z2(this.config,X)}dropRosterRows(X){let J=this.roster(),$=J.filter((Y)=>!(y(Y)&&Y.id===X));return this.config.accounts=$,J.length-$.length}entries(){return Q5(this.config)}entry(X){return this.entries(),N9(this.config,X)}setEntry(X,J){W2(this.config,X,J)}async completeTorn(){let{config:X,torn:J}=W5(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if(J.length===0)return;this.config=X,await this.commitConfig({counted:!1})}stateAccount(X){let J=y(this.state.accounts)?this.state.accounts:{},$=Object.hasOwn(J,X)?J[X]:void 0;return y($)?$:void 0}dropStateAccount(X){if(y(this.state.accounts)&&Object.hasOwn(this.state.accounts,X))delete this.state.accounts[X]}setStateAccount(X,J){if(!y(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,X,{value:J,enumerable:!0,writable:!0,configurable:!0})}async commitConfig(X={}){let J=this.roster(),$=new Set;for(let W of J)if(y(W)&&typeof W.id==="string")$.add(W.id);let Y=new Set;for(let W of v1(this.snapshot.config))if(y(W)&&typeof W.id==="string"&&!$.has(W.id))Y.add(W.id);for(let W of Object.keys(this.entries()))if(!$.has(W))Y.add(W);UQ(this.config,Y);let G=this.entries(),Q={};for(let[W,B]of Object.entries(G))if($.has(W))Object.defineProperty(Q,W,{value:B,enumerable:!0,writable:!0,configurable:!0});let z=this.config[E0],Z={...this.config,version:x4,accounts:J,[E0]:{...z,schemaVersion:q9,[X8]:Q}};await this.write(this.ctx.configPath,Z,"config",X.counted??!0,X.durable??!1,()=>{if(X.publicationDecision)this.markPublicationDecision();for(let W of Y)this.ctx.removedIds.add(W);this.config=Z}),this.config=Z}async commitState(X,J={}){let $={...this.state,version:x4,accounts:y(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,$,"state",!0,J.durable??!1),this.state=$,X)this.progress.committed=X}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await V5(this.ctx.statePath)}catch(X){throw new K0({operation:this.info.operation,rowId:this.info.rowId,phase:"before-first-write",kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:X})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await V5(this.ctx.configPath)}async write(X,J,$,Y=!0,G=!1,Q){await FQ(X,J,{durable:G,beforeRename:async()=>{await this.ctx.onStep?.(`before-${$}-write`,this.info),await this.locks.assertAll()}},()=>{if(Y)this.progress.writes++;Q?.()}),await this.ctx.onStep?.(`after-${$}-write`,this.info)}}async function MQ(X,J){let $=new j9(X.lockDefaults,X.lockEnv),Y={writes:0};try{for(let Z of X.storeLocks)await $.acquire(Z);let G=await M6(X);if(G.status==="error")throw $8(G,"initialize",void 0);if(G.status==="ready")return"already-ready";let Q={};for(let[Z,W]of Object.entries(G.config))if(!J.includes(Z))Q[Z]=W;Q.version=x4,Q[E0]={schemaVersion:q9,[X8]:{}};let z={operation:"initialize",rowId:void 0};return await O6(X.configPath,Q,{beforeRename:async()=>{await X.onStep?.("before-config-write",z),await $.assertAll()}}),Y.writes++,await X.onStep?.("after-config-write",z),"initialized"}catch(G){throw h1(G,"initialize",void 0,Y)}finally{await $.releaseAll()}}async function a0(X,J,$,Y,G,Q={}){let z=J.held.length;try{for(let B of X.storeLocks)await J.acquire(B);let Z=await M6(X);if(Z.status!=="ready")throw $8(Z,Y.operation,Y.rowId,$.writes>0?"after-first-write":"before-first-write");let W=new OQ(X,Z,J,$,Y);if(Y.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(Y.operation))W.assertNotStaged(Y.rowId);if(Q.completeTorn??!0)await W.completeTorn();return await G(W)}finally{await J.releaseTo(z)}}function h1(X,J,$,Y){let G=J==="pull"?"pull":Y.writes>0?"after-first-write":"before-first-write",Q=G==="after-first-write"?Y.committed:void 0;if(J==="publishRoster"&&Y.publicationDecided)return new K0({operation:J,...$!==void 0?{rowId:$}:{},phase:G,kind:"publication-incomplete",retryable:!0,message:"The publication may already be decided. Replay the same plan or check publication(operationId).",cause:X});if(J==="publishRoster"&&X instanceof DQ)return new K0({operation:J,...$!==void 0?{rowId:$}:{},phase:G,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:X});if(X instanceof K0){if(X.phase===G&&X.rowId===$&&X.operation===J&&X.committed===Q)return X;return new K0({operation:J,...$!==void 0?{rowId:$}:{},phase:X.kind==="after-persist-hook"?X.phase:G,retryable:X.retryable,kind:X.kind,...X.committed??Q?{committed:X.committed??Q}:{},message:X.message,...X.cause!==void 0?{cause:X.cause}:{}})}let z={operation:J,...$!==void 0?{rowId:$}:{},phase:G,...Q?{committed:Q}:{},cause:X};if(X instanceof PQ)return new K0({...z,retryable:!0,kind:"lock-ownership",message:G==="after-first-write"?`${J} lost a lease after its first write; the intermediate stays on disk`:`${J} lost a lease before writing; nothing was written`});if(X instanceof Q2)return new K0({...z,retryable:!0,kind:"lock-contention",message:X.message});return new K0({...z,retryable:!1,kind:"unexpected",message:X instanceof Error?X.message:String(X)})}async function B6(X,J,$,Y,G){let Q=new j9(X.lockDefaults,X.lockEnv),z={writes:0};try{return await G(Q,z)}catch(Z){let W=h1(Z,J,$,z);if(W.kind!=="after-persist-hook")await YQ(J,Y,$,W,X.logger);throw W}finally{await Q.releaseAll()}}function h6(X,J){return{...X.rowLockOptions,name:`row-${encodeURIComponent(x0(J))}`,path:X.ctx.statePath}}async function s8(X,J,$){let Y=await M6(X.ctx);if(Y.status!=="ready")throw $8(Y,J,$);let G=Y.rows.find((B)=>B.id===$),Q=N9(Y.config,$),z=Y.state.accounts,Z=y(z)&&Object.hasOwn(z,$)?z[$]:void 0,W=y(Z)?Z[_0]:void 0;if(G&&!["enable","disable"].includes(J)&&Q&&Object.hasOwn(Q,"staged"))p9(J,$,Q.staged);if(!G&&y(W)&&Object.hasOwn(W,"staged"))p9(J,$,W.staged);if(!G)throw Y8(J,$);return{result:Y,row:G}}function Y8(X,J){return new K0({operation:X,rowId:J,phase:X==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${J} in the pool`})}function _6(X,J){if(J.unbound)throw x(X,J.id,"unbound-credential",`row ${J.id}'s credential is not the one this store stamped for it (stamp ${J.stamp}); replace it with fresh material`)}function x(X,J,$,Y,G=!1){return new K0({operation:X,rowId:J,phase:X==="pull"?"pull":"before-first-write",retryable:G,kind:$,message:Y})}async function V2(X,J,$,Y){let{ctx:G}=X,Q=new j9(G.lockDefaults,G.lockEnv),z={writes:0};try{if(!$6($?.credentialEpoch))throw x("pull",J,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await a0(G,Q,z,{operation:"pull",rowId:J},async(Z)=>{Z.assertNotStaged(J);let W=Z.row(J);if(!W)throw Y8("pull",J);if(W.invalid)throw x("pull",J,"invalid-row",`row ${J} is invalid`);if(!W.credential)throw x("pull",J,"no-credential",`row ${J} holds no credential`);_6("pull",W);let B=Z.entry(J);if(W.torn||!B||B.credentialEpoch!==$.credentialEpoch||W.identity!==$.identity)throw new K0({operation:"pull",rowId:J,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${J} was issued for a credential the row no longer holds`});let H=G.codec.merge(B.quota,Y);if(!G.codec.validate(H))throw x("pull",J,"invalid-quota","the quota codec rejected the merged map");Z.setEntry(J,{...B,quota:H,needsFirstReading:!1}),await Z.commitConfig()},{completeTorn:!1})}catch(Z){throw h1(Z,"pull",J,z)}finally{await Q.releaseAll()}}function a8(X,J,$,Y,G="the provider state"){if(!X)throw x(J,$,"invalid-input","the store was opened without a provider-state codec");let Q;try{let z=JSON.stringify(Y);Q=z===void 0?void 0:JSON.parse(z)}catch{Q=void 0}if(Q===void 0)throw x(J,$,"invalid-provider-state",`${G} cannot be stored as JSON`);if(!X.validate(Q))throw x(J,$,"invalid-provider-state",`the provider-state codec rejected ${G}`);return Q}function h4(X,J,$,Y,G){if(Y===void 0||!X?.merge)return{kind:"set",value:G};return{kind:"set",value:a8(X,J,$,X.merge(structuredClone(Y),structuredClone(G)),"the merged provider state")}}function _Q(X,J,$,Y,G){let Q=X?.onReplace,z=Q?Q(J.providerState===void 0?void 0:structuredClone(J.providerState),{id:J.id,credentialEpoch:$,...J.identity!==void 0?{previousIdentity:J.identity}:{},...Y!==void 0?{identity:Y}:{},...G!==void 0?{incoming:structuredClone(G)}:{}}):G;if(z===void 0)return{kind:"clear"};if(!Q)return{kind:"set",value:z};return{kind:"set",value:a8(X,"replace",J.id,z,"the provider state onReplace returned")}}function AQ(X,J,$,Y,G){if(J.kind==="set")return w1(X,J.value);if(J.kind==="clear")return;return w4($,Y?.credential,G,Y?.identity)}async function TQ(X,J,$,Y,G={}){W6("updateProviderState");let{ctx:Q}=X,z="updateProviderState";return B6(Q,z,J,G.onFailure,async(Z,W)=>{let B=Q.providerState;if(!B)throw x(z,J,"invalid-input","the store was opened without a provider-state codec");if(typeof Y!=="function")throw x(z,J,"invalid-input","a mutator is required");let H=y($)?$.credentialEpoch:void 0;if(!$6(H))throw x(z,J,"invalid-input","the credential epoch the provider state was read at is required");let{row:U}=await s8(X,z,J);await Z.acquire(h6(X,U));for(let j of G.extraLocks??[])await Z.acquire(j);return a0(Q,Z,W,{operation:z,rowId:J},async(j)=>{let q=j.row(J);if(!q)throw Y8(z,J);if(x0(q)!==x0(U))throw x(z,J,"row-key-changed",`row ${J}'s wire identity changed while its lock was being taken`,!0);if(q.invalid)throw x(z,J,"invalid-row",`row ${J} failed validation`);if(!q.credential)throw x(z,J,"no-credential",`row ${J} holds no credential`);if(_6(z,q),(q.credentialEpoch??1)!==H||q.identity!==$.identity)throw x(z,J,"attribution",`the provider state for ${J} was read for a credential or account the row no longer holds`,!0);let L=await U5(j,B,z,q,Y);if(L.kind!=="changed")return{id:J,outcome:"unchanged",...L.kind==="unchanged"&&L.value!==void 0?{providerState:L.value}:{}};return j.setStateAccount(J,L.account),await j.commitState(),L.value===void 0?{id:J,outcome:"cleared"}:{id:J,outcome:"updated",providerState:L.value}})})}var RQ=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function U5(X,J,$,Y,G,Q=!1){let{id:z,credential:Z}=Y;if(!Z)throw x($,z,"no-credential",`row ${z} holds no credential`);let W=Y.credentialEpoch??1,B=X.stateAccount(z),H=B?.[_0],U=S6(H);if(!y(H)||!U?.binding||U.digest!==M8(Z)||U.credentialEpoch!==W||U.binding.identity!==Y.identity)throw x($,z,"unbound-credential",`row ${z}'s credential carries no stamp of this store to bind a provider state to (stamp ${Y.stamp}); rotate or replace it first`);let j=Y.providerState===void 0?void 0:structuredClone(Y.providerState),q=await O8($,()=>G(j,Y));if(Q&&q===RQ)return{kind:"declined"};let K=q===void 0?void 0:a8(J,$,z,q,"the provider state the mutator returned"),L=B!==void 0&&Object.hasOwn(B,P6);if(K===void 0?!L:Y.providerState!==void 0&&JSON.stringify(Y.providerState)===JSON.stringify(K))return{kind:"unchanged",...K!==void 0?{value:K}:{}};let F={...B};if(K===void 0){delete F[P6];let O={...H};delete O.providerState,F[_0]=O}else{F[P6]=K;let O=w1(J,K);if(U.providerState!==O)F[_0]={...H,providerState:O}}return{kind:"changed",...K!==void 0?{value:K}:{},account:F}}import{randomUUID as CQ}from"node:crypto";async function q2(X,J,$){if(!$)return;let Y=X.rows().map((Q)=>{let{id:z,type:Z,label:W,enabled:B,disabledReason:H,identity:U,credentialEpoch:j,stamp:q,staged:K,torn:L,invalid:F}=Q;return{id:z,type:Z,label:W,enabled:B,disabledReason:H,identity:U,credentialEpoch:j,stamp:q,staged:K,torn:L,invalid:F}}),G=await O8(X.info.operation,()=>$({id:J,row:Y.find((Q)=>Q.id===J),rows:Y,config:structuredClone(X.snapshot.config)}));if(G!==void 0)throw x(X.info.operation,J,"row-protected",G)}var fL=["access","refresh","expires","lastRefreshedAt","apiKey"];function gL(X){return{baseURL:String(X.baseURL).trim(),authHeader:X.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function mL(X,J,$){if($.type!=="api")return $;let Y=X.rosterRow(J);if(!y(Y)){if($.baseURL===void 0)throw x(X.info.operation,J,"invalid-input","api credential needs a valid baseURL");return{...$,baseURL:$.baseURL}}let G=X.row(J)?.credential,Q=G?.type==="api"?{baseURL:G.baseURL.trim(),authHeader:G.authHeader??"authorization-bearer"}:gL(Y),z=$.baseURL?.trim()??Q.baseURL,Z=$.authHeader??Q.authHeader;if(z!==Q.baseURL||Z!==Q.authHeader)throw x(X.info.operation,J,"endpoint-mismatch",`row ${J} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...$,baseURL:z,authHeader:Z}}function EQ(X,J,$,Y){let G=X.rosterRow(J),Q=X.row(J),z=Y??(Q?Q.identity:y(G)&&typeof G.accountId==="string"&&G.accountId?G.accountId:void 0);return{...z!==void 0?{identity:z}:{},...$.type==="api"?{baseURL:$.baseURL,authHeader:$.authHeader??"authorization-bearer"}:{}}}function U2(X,J,$,Y,G={}){let Q=mL(J,$,Y),z=J.stateAccount($),Z=G.providerState??{kind:"keep"},W=J.row($)?.credentialEpoch??J.entry($)?.credentialEpoch,B=typeof W==="number"?W:1,H=AQ(X.ctx.providerState,Z,z,z&&Object.hasOwn(z,P6)?J.row($):void 0,B),U=typeof z?.lastRefreshedAt==="number"?z.lastRefreshedAt:void 0,j=Q.type==="oauth"?G.stamp??v4(U,X.ctx.now()):void 0,q={...z??{}};for(let F of fL)delete q[F];if(G.clearErrors)delete q.lastRefreshError,delete q.lastQuotaRefreshError,delete q.quota;if(Z.kind==="clear")delete q[P6];else if(Z.kind==="set")q[P6]=Z.value;let K=jQ(Q,j),L={...q,...KQ(Q,j),[_0]:{...G.staged?{staged:G.staged}:{},...G.transition!==void 0?{[H2]:G.transition}:{},...G5(K,B,G.binding??EQ(J,$,K,G.identity),{replace:G.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:K,account:L}}async function K2(X,J,$){return X.setStateAccount(J,$.account),await X.commitState($.stored),$.stored}async function N2(X,J,$,Y,G={}){return K2(J,$,U2(X,J,$,Y,G))}async function uL(X,J,$){if(!J.credential||J.stamp!=="bound")return;let Y=X.stateAccount(J.id),G=w4(Y,J.credential,J.credentialEpoch??1,J.identity);X.setStateAccount(J.id,{...Y??{},[_0]:G5(J.credential,J.credentialEpoch??1,EQ(X,J.id,J.credential,$),G!==void 0?{providerState:G}:{})}),await X.commitState()}function j5(X,J,$){let Y=X==="add"?x1(J):void 0;if(Y)throw x(X,J,"invalid-input",Y);let G=qQ($,{baseURLOptional:X==="rotate"});if(G)throw x(X,J,"invalid-input",G)}function L2(X,J,$,Y){if(!$)throw Y8(X,J);if($.invalid)throw x(X,J,"invalid-row",`row ${J} failed validation`);if(Y&&Y.type!==$.type)throw x(X,J,"type-mismatch",`row ${J} holds a ${$.type} credential`);return $}function g1(X,J,$){if($!==void 0&&!$6(y($)?$.credentialEpoch:void 0))throw x(X,J,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function D2(X,J,$,Y){if(!$)throw Y8(X,J);if($.invalid)throw x(X,J,"invalid-row",`row ${J} failed validation`);if(($.credentialEpoch??1)!==Y.credentialEpoch||$.identity!==Y.identity)throw x(X,J,"attribution",`the ${X} of ${J} was issued for a credential or account the row no longer holds`,!0)}function j2(X,J){return x(X,J,"identity-mismatch",`row ${J} is recorded for another account; a credential of a different account is a replacement`)}function f4(X,J){return x(X,J,"row-key-changed",`row ${J}'s wire identity changed while its lock was being taken`,!0)}function pL(X,J,$,Y){let{id:G,credential:Q,identity:z}=$;if(!X.ctx.requireCredentialStamps||J.rosterRow(G)||!f1(J.state,G))return;let Z=()=>{throw x("add",G,"unbound-credential",`orphan ${G} cannot be bound to this add's material; remove it explicitly before adding different material`)},W=J.stateAccount(G),B=S6(W?.[_0]);if(!B?.binding||B.dispatch===void 0||B.replace)return Z();if(Q.type==="api"&&(B.binding.baseURL===void 0||B.binding.authHeader===void 0))return Z();let H=Q.type==="api"?{...Q,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}:Q,[U]=L9({accounts:[y1({id:G,credential:H,identity:B.binding.identity,addedAt:0})],[E0]:{rows:{[G]:{credentialEpoch:B2(J.config,G)}}}},J.state,X.ctx.codec,X.ctx.providerState);if(!U?.credential||U.invalid||U.stamp!=="bound")return Z();if(z!==void 0&&z!==U.identity)return Z();if(M8(Q)!==B.digest)return Z();if(Q.type==="api"){if(Q.baseURL.trim()!==B.binding.baseURL)return Z();if((Q.authHeader??"authorization-bearer")!==B.binding.authHeader)return Z()}else if(n8(Q)!==B.dispatch)return Z();if(B.providerState!==void 0&&U.providerState===void 0)return Z();if(Y!==void 0&&w1(X.ctx.providerState,Y)!==B.providerState)return Z();return U}function cL(X,J,$,Y){let{id:G,credential:Q,identity:z,label:Z}=$,W=J.rosterRow(G),B=()=>{throw x("add",G,W?"id-exists":"unbound-credential",`row ${G} does not match this staged add`)},H=J.stateAccount(G),U=S6(H?.[_0]),j=U?.staged;if(!U?.binding||!j||U.replace||U.dispatch===void 0)return B();if(W&&(W.type!==Q.type||W.label!==Z||W.accountId!==z))return B();if(j.reservation!==$.stage?.reservation||j.label!==Z||j.disabledReason!==$.disabled?.reason||U.binding.identity!==z)return B();let q=Y===void 0?void 0:c9(Y),K=H?.[P6],L=K===void 0?void 0:c9(K);if(j.providerState!==q||j.providerState!==L)return B();if(M8(Q)!==U.digest||n8(Q)!==U.dispatch)return B();let F=W?J.config:{accounts:[{...y1({id:G,credential:Q.type==="api"?{...Q,baseURL:U.binding.baseURL??"",authHeader:U.binding.authHeader}:Q,identity:U.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[E0]:{rows:{[G]:{credentialEpoch:U.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},O=L9(F,J.state,X.ctx.codec,X.ctx.providerState).find((_)=>_.id===G);if(!O?.credential||O.invalid||O.stamp!=="bound"||O.type!==Q.type||O.enabled||O.label!==j.label||O.identity!==U.binding.identity||O.disabledReason!==j.disabledReason||O.staged?.reservation!==j.reservation)return B();if(W)return{id:G,outcome:"exists",credential:O.credential,credentialEpoch:U.credentialEpoch};if(B2(J.config,G)!==U.credentialEpoch)return B();return J.roster().push({...y1({id:G,credential:Q,identity:z,label:Z,addedAt:X.ctx.now()}),enabled:!1}),J.setEntry(G,{credentialEpoch:U.credentialEpoch,needsFirstReading:Q.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),J.commitConfig().then(()=>({id:G,outcome:"completed",credential:O.credential,credentialEpoch:U.credentialEpoch}))}async function SQ(X,J,$={}){W6("add");let{ctx:Y}=X,{id:G,credential:Q,identity:z,label:Z}=J,W=J.stage!==void 0||J.disabled!==void 0,B=await B6(Y,"add",G,$.onFailure,async(H,U)=>{j5("add",G,Q);let j=$.onExisting??"rotate";if(J.stage!==void 0&&j==="rotate")throw x("add",G,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||J.stage!==void 0&&(Z!==void 0&&typeof Z!=="string"||z!==void 0&&(typeof z!=="string"||!z))||J.disabled!==void 0&&(!y(J.disabled)||typeof J.disabled.reason!=="string")||J.stage!==void 0&&(!y(J.stage)||typeof J.stage.reservation!=="string"||!J.stage.reservation||!J.disabled)||j==="stage-duplicate"&&(!J.disabled||!J.stage))throw x("add",G,"invalid-input","staging requires a reservation and a disabled reason");let q=J.providerState===void 0?void 0:a8(Y.providerState,"add",G,J.providerState);if(await H.acquire(h6(X,{id:G,identity:z})),Q.type==="oauth")await H.acquire($.providerLock??X.providerLock);for(let K of $.extraLocks??[])await H.acquire(K);return a0(Y,H,U,{operation:"add",rowId:G},async(K)=>{await q2(K,G,$.protect);let L=y(K.state.accounts)?K.state.accounts:{},F=Object.entries(L).find(([X0,w])=>{if(X0===G||K.rosterRow(X0)||!y(w))return!1;let J0=w[_0];if(!y(J0)||!Object.hasOwn(J0,"staged"))return!1;return Q.type==="oauth"?w.refresh===Q.refresh:typeof w.apiKey==="string"&&w.apiKey.trim()===Q.apiKey.trim()});if(F)throw x("add",F[0],"row-staged",`orphan ${F[0]} reserves this secret until its staged add is replayed or removed`);if(Y.removedIds.has(G))throw x("add",G,"id-removed",`id ${G} was removed from the roster in this process and is not reused`);if(J.stage&&j!=="rotate"&&(K.rosterRow(G)||f1(K.state,G)))return cL(X,K,J,q);if(j==="rotate"){K.assertNotStaged(G);let X0=K.rows().find((w)=>w.fingerprint===J8(Q));if(X0)K.assertNotStaged(X0.id)}if(j==="refuse"){let X0=K.rows().find((L0)=>L0.fingerprint===J8(Q)||L0.id===G&&L0.credential),w=y(K.state.accounts)?K.state.accounts:{},J0=Object.entries(w).find(([,L0])=>{if(!y(L0))return!1;if(Q.type==="oauth")return L0.refresh===Q.refresh;return typeof L0.apiKey==="string"&&L0.apiKey.trim()===Q.apiKey.trim()})?.[0],G0=X0?.id??J0??G;if(X0||J0!==void 0||f1(K.state,G))throw x("add",G0,"credential-exists",`row ${G0} already holds this secret or id`)}if(j==="stage-duplicate"&&(K.rosterRow(G)||f1(K.state,G)))throw x("add",G,"id-exists",`row ${G} already exists`);let O=pL(X,K,J,q),_=K.rows(),C=J8(Q),N=j==="rotate"&&!O&&_.find((X0)=>X0.invalid===void 0&&X0.fingerprint===C);if(N){if(K.assertNotStaged(N.id),_6("add",N),z!==void 0&&N.identity!==void 0&&z!==N.identity)throw j2("add",N.id);let X0=U2(X,K,N.id,Q,{...q!==void 0?{providerState:h4(Y.providerState,"add",N.id,N.providerState,q)}:{}});await K.completeTorn(),K.assertNotStaged(N.id);let w=await K2(K,N.id,X0);return{id:N.id,outcome:"rotated",credential:w,credentialEpoch:N.credentialEpoch??1}}let P=_.find((X0)=>X0.id===G);if(P){if(P.invalid)throw x("add",G,"invalid-row",`row ${G} is invalid`);if(P.credential)throw x("add",G,"id-exists",`row ${G} already holds a credential`);if(_6("add",P),P.type!==Q.type)throw x("add",G,"type-mismatch",`row ${G} is a ${P.type} row`);if(z!==void 0&&P.identity!==void 0&&z!==P.identity)throw j2("add",G);if(!P.hasEntry)K.setEntry(G,{credentialEpoch:1,needsFirstReading:Q.type==="oauth"});let X0=U2(X,K,G,Q,{clearErrors:!0,...q!==void 0?{providerState:{kind:"set",value:q}}:{}});await K.completeTorn();let w=await K2(K,G,X0);if(!P.hasEntry)await K.commitConfig();return{id:G,outcome:"completed",credential:w,credentialEpoch:P.credentialEpoch??1}}let A=B2(K.config,G);if(!$6(A))throw x("add",G,"id-removed",`id ${G} has held every credential epoch and is not reused; add the credential under another id`);let T=O?.identity??z;K.roster().push(y1({id:G,credential:Q,...T!==void 0?{identity:T}:{},...Z!==void 0?{label:Z}:{},addedAt:Y.now()})),K.setEntry(G,{credentialEpoch:A,needsFirstReading:Q.type==="oauth",...J.stage?{staged:{reservation:J.stage.reservation}}:{}});let b="added";if(J.disabled)K9(K,G,J.disabled.reason),b="added-disabled";if(!J.disabled&&T!==void 0&&Q.type==="oauth"){if(_.find((w)=>w.invalid===void 0&&w.type==="oauth"&&w.enabled&&w.identity===T))K9(K,G,X5),b="added-disabled"}if(O?.credential)return await K.commitConfig(),{id:G,outcome:b,credential:O.credential,credentialEpoch:O.credentialEpoch??A};K.dropStateAccount(G);let p=U2(X,K,G,Q,{...J.stage&&J.disabled?{staged:{reservation:J.stage.reservation,disabledReason:J.disabled.reason,...Z!==void 0?{label:Z}:{},...q!==void 0?{providerState:c9(q)}:{}}}:{},...q!==void 0?{providerState:{kind:"set",value:q}}:{}});if(j==="rotate")await K.completeTorn();let i=await K2(K,G,p);return await K.commitConfig(),{id:G,outcome:b,credential:i,credentialEpoch:A}},{completeTorn:!1})});if(!W&&Q.type==="oauth"&&(B.outcome==="added"||B.outcome==="completed"))X.firePull(B.id,"add");return B}async function IQ(X,J,$,Y={},G={}){W6("replace");let{ctx:Q}=X,z=await B6(Q,"replace",J,G.onFailure,async(Z,W)=>{j5("replace",J,$),g1("replace",J,G.attribution);let B=Y.providerState===void 0?void 0:a8(Q.providerState,"replace",J,Y.providerState),{row:H}=await s8(X,"replace",J);if(await Z.acquire(h6(X,H)),$.type==="oauth")await Z.acquire(G.providerLock??X.providerLock);for(let U of G.extraLocks??[])await Z.acquire(U);return a0(Q,Z,W,{operation:"replace",rowId:J},async(U)=>{if(G.attribution!==void 0)D2("replace",J,U.row(J),G.attribution),await U.completeTorn();let j=L2("replace",J,U.row(J),$);if(x0(j)!==x0(H))throw f4("replace",J);let q=U.entry(J)?.credentialEpoch,K=(typeof q==="number"?q:1)+1;if(!$6(K))throw x("replace",J,"invalid-row",`row ${J}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let L=_Q(Q.providerState,j,K,Y.identity,B),F={...Y.identity!==void 0?{identity:Y.identity}:{},...$.type==="api"?{baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"}:{}};if(Z5(U,J,K,F),Y.identity!==void 0)k1(U,Y.identity);let O=await N2(X,U,J,$,{clearErrors:!0,binding:F,providerState:L});return await U.commitConfig(),{id:J,credential:O,credentialEpoch:K}},{completeTorn:G.attribution===void 0})});if($.type==="oauth")X.firePull(J,"replace");return z}async function bQ(X,J,$,Y={},G={}){W6("rotate");let{ctx:Q}=X;return B6(Q,"rotate",J,G.onFailure,async(z,Z)=>{j5("rotate",J,$),g1("rotate",J,G.attribution);let W=Y.providerState===void 0?void 0:a8(Q.providerState,"rotate",J,Y.providerState),{row:B}=await s8(X,"rotate",J);if(await z.acquire(h6(X,B)),Y.identity!==void 0&&$.type==="oauth")await z.acquire(G.providerLock??X.providerLock);for(let H of G.extraLocks??[])await z.acquire(H);return a0(Q,z,Z,{operation:"rotate",rowId:J},async(H)=>{if(G.attribution!==void 0)D2("rotate",J,H.row(J),G.attribution),await H.completeTorn();let U=L2("rotate",J,H.row(J),$);if(x0(U)!==x0(B))throw f4("rotate",J);if(_6("rotate",U),Y.identity!==void 0&&U.identity!==void 0&&Y.identity!==U.identity)throw j2("rotate",J);let j=Y.identity!==void 0&&U.identity===void 0?Y.identity:void 0,q=await N2(X,H,J,$,{identity:j,...W!==void 0?{providerState:h4(Q.providerState,"rotate",J,U.providerState,W)}:{}}),K=!1;if(!U.hasEntry)H.setEntry(J,{credentialEpoch:1,needsFirstReading:U.type==="oauth"}),K=!0;if(Y.identity!==void 0&&U.identity!==Y.identity)u9(H,J,Y.identity),K=!0;if(K)await H.commitConfig();return{id:J,credential:q}},{completeTorn:G.attribution===void 0})})}async function kQ(X,J,$,Y,G){W6(J);let{ctx:Q}=X,z=Q.providerState,Z=G.attribution,W=G.providerState;return B6(Q,J,$,G.onFailure,async(B,H)=>{if(g1(J,$,Z),W!==void 0){if(typeof W!=="function")throw x(J,$,"invalid-input","the provider-state mutator must be a function");if(Z===void 0)throw x(J,$,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!z)throw x(J,$,"invalid-input","the store was opened without a provider-state codec")}let{row:U}=await s8(X,J,$);await B.acquire(h6(X,U));for(let j of G.extraLocks??[])await B.acquire(j);return a0(Q,B,H,{operation:J,rowId:$},async(j)=>{await q2(j,$,G.protect),j.assertNotStaged($);let q=j.row($),K=Y.enabled?L2("enable",$,q):q;if(!K||!j.rosterRow($))throw Y8(J,$);if(x0(K)!==x0(U))throw f4(J,$);if(Z!==void 0)D2(J,$,K,Z);if(Y.enabled&&K.disabledReason?.startsWith(b1))throw x("enable",$,"identity-contradicted",`row ${$} needs an identity-validated credential replacement before it can be enabled`);let L=!Y.enabled||!K.enabled||K.disabledReason!==void 0;if(Y.enabled&&L&&K.type==="oauth"){let N=K.identity===void 0?void 0:j.rows().find((P)=>P.id!==$&&P.invalid===void 0&&P.type==="oauth"&&P.enabled&&P.identity===K.identity);if(N)throw x("enable",$,"duplicate-identity",`row ${N.id} is enabled with the same identity as row ${$}`)}if(W===void 0||z===void 0){if(await j.completeTorn(),!L)return{id:$};if(Y.enabled)b4(j,$);else K9(j,$,Y.reason);return await j.commitConfig(),{id:$}}if(!K.credential)throw x(J,$,"no-credential",`row ${$} holds no credential`);_6(J,K);let F=await U5(j,z,J,K,W,!0);if(F.kind==="declined")return{id:$,declined:!0};await j.completeTorn();let O={id:$,providerStateOutcome:F.kind==="unchanged"?"unchanged":F.value===void 0?"cleared":"updated",...F.value!==void 0?{providerState:F.value}:{}};if(F.kind==="unchanged"){if(L){if(Y.enabled)b4(j,$);else K9(j,$,Y.reason);await j.commitConfig()}return O}if(!L)return j.setStateAccount($,F.account),await j.commitState(),O;let _=Y.enabled?{mark:CQ(),enabled:!0}:{mark:CQ(),enabled:!1,reason:Y.reason},C=F.account[_0];return j.setStateAccount($,{...F.account,[_0]:{...C,[H2]:_}}),await j.commitState(),y4(j,$,_),await j.commitConfig(),O},{completeTorn:!1})})}function xQ(X,J,$,Y={}){return kQ(X,"disable",J,{enabled:!1,reason:$},Y)}function wQ(X,J,$={}){return kQ(X,"enable",J,{enabled:!0},$)}async function vQ(X,J,$={}){W6("remove");let{ctx:Y}=X;return B6(Y,"remove",J,$.onFailure,async(G,Q)=>{if(typeof J!=="string"||J.length===0)throw x("remove",J,"invalid-input","id must be non-empty");let z=$.attribution;if(g1("remove",J,z),$.staged!==void 0&&(!y($.staged)||typeof $.staged.reservation!=="string"||!$.staged.reservation))throw x("remove",J,"invalid-input","a staged removal needs a reservation");let Z=await M6(Y);if(Z.status!=="ready")throw $8(Z,"remove",J);let W=Z.rows.find((H)=>H.id===J);if(!W&&!f1(Z.state,J))throw Y8("remove",J);let B=x0(W??{id:J});await G.acquire(h6(X,W??{id:J}));for(let H of $.extraLocks??[])await G.acquire(H);return a0(Y,G,Q,{operation:"remove",rowId:J},async(H)=>{let U=H.reservation(J);if(U!==void 0){if(!y(U)||!$.staged||U.reservation!==$.staged.reservation)throw x("remove",J,"row-staged",`row ${J} is reserved for roster publication`)}else if($.staged)throw x("remove",J,"attribution",`row ${J} is no longer reserved`);let j=H.row(J),q=f1(H.state,J);if(!j&&!q)throw Y8("remove",J);if(x0(j??{id:J})!==B)throw f4("remove",J);if(z!==void 0)if(j)F2(J,j,z);else lL(X,H,J,z);let K=$.protect;if(K){let L={row:j,config:H.snapshot.config,state:H.snapshot.state},F=await O8("remove",()=>K(J,L));if(F!==void 0)throw x("remove",J,"row-protected",F)}if(j){if(z===void 0)await H.completeTorn();H.dropRosterRows(J),await H.commitConfig()}if(q)H.dropStateAccount(J),await H.commitState();return{id:J,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function F2(X,J,$,Y="remove"){if(D2(Y,X,J,$),J.torn)throw x(Y,X,"attribution",`row ${X} is between the writes of another operation; retry once it completes`,!0);if(J.stamp!=="bound")throw x(Y,X,"unbound-credential",`row ${X}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function lL(X,J,$,Y){let G=()=>x("remove",$,"unbound-credential",`orphan ${$} has no credential stamp this store can bind, so the removal cannot be attributed to it`),Q=J.stateAccount($),z=S6(Q?.[_0]);if(!Q||!z?.binding||z.dispatch===void 0||z.replace)throw G();let Z;if(typeof Q.apiKey==="string"){if(z.binding.baseURL===void 0||z.binding.authHeader===void 0)throw G();Z={type:"api",apiKey:Q.apiKey,baseURL:z.binding.baseURL,authHeader:z.binding.authHeader}}else if(typeof Q.refresh==="string")Z={type:"oauth",refresh:Q.refresh};else throw G();let[W]=L9({accounts:[y1({id:$,credential:Z,identity:z.binding.identity,addedAt:0})],[E0]:{rows:{[$]:{credentialEpoch:z.credentialEpoch}}}},J.state,X.ctx.codec,X.ctx.providerState);if(!W?.credential||W.invalid||W.stamp!=="bound")throw G();if(z.credentialEpoch!==Y.credentialEpoch||z.binding.identity!==Y.identity)throw x("remove",$,"attribution",`orphan ${$} was written for a credential or account other than the one this removal was decided for`,!0)}function f1(X,J){let $=X.accounts;return y($)&&Object.hasOwn($,J)}function K5(X){return y(X)&&typeof X.id==="string"?X.id:void 0}function dL(X,J){if(!Array.isArray(J))return"ids must be an array of roster ids";let $=new Set;for(let Q of X){let z=K5(Q);if(z!==void 0)$.add(z)}let Y=new Set;for(let Q of J){if(typeof Q!=="string")return"ids must be an array of roster ids";if(Y.has(Q))return`id ${Q} appears more than once`;if(!$.has(Q))return`id ${Q} is not in the roster`;Y.add(Q)}let G=[...$].filter((Q)=>!Y.has(Q));if(G.length>0)return`the order leaves out roster id(s) ${G.join(", ")}`;return}function iL(X,J){let $=new Map;for(let Q of X){let z=K5(Q);if(z===void 0)continue;let Z=$.get(z);if(Z)Z.push(Q);else $.set(z,[Q])}let Y=J.flatMap((Q)=>$.get(Q)??[]),G=0;return X.map((Q)=>K5(Q)===void 0?Q:Y[G++])}async function yQ(X,J,$={}){W6("reorder");let{ctx:Y}=X,G=$.onFailure;return B6(Y,"reorder",void 0,G&&((Q,z)=>G(z)),async(Q,z)=>{for(let Z of $.extraLocks??[])await Q.acquire(Z);return a0(Y,Q,z,{operation:"reorder",rowId:void 0},async(Z)=>{let W=Z.roster(),B=dL(W,J);if(B)throw new K0({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:B});let H=[...J],U=iL(W,H);if(U.every((j,q)=>j===W[q]))return{ids:H,outcome:"unchanged"};return Z.config.accounts=U,await Z.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function hQ(X,J,$,Y,G={}){return W6("recordIdentity"),B6(X.ctx,"recordIdentity",J,G.onFailure,async(Q,z)=>{if(typeof $!=="string"||$.length===0)throw x("recordIdentity",J,"invalid-input","identity must be non-empty");let Z=y(Y)?Y.credentialEpoch:void 0;if(!$6(Z))throw x("recordIdentity",J,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:W}=await s8(X,"recordIdentity",J);await Q.acquire(h6(X,W)),await Q.acquire(G.providerLock??X.providerLock);for(let B of G.extraLocks??[])await Q.acquire(B);return a0(X.ctx,Q,z,{operation:"recordIdentity",rowId:J},async(B)=>{let H=L2("recordIdentity",J,B.row(J));if(x0(H)!==x0(W))throw f4("recordIdentity",J);if(_6("recordIdentity",H),(H.credentialEpoch??1)!==Z)throw x("recordIdentity",J,"attribution",`the identity for ${J} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==$)throw j2("recordIdentity",J);if(H.identity===void 0)await uL(B,H,$);let U=u9(B,J,$);return await B.commitConfig(),{id:J,disabled:U}})})}function gQ(X){let J=X[E0];return y(J)&&y(J.publications)?J.publications:{}}function mQ(X,J){let $=gQ(X);if(!Object.hasOwn($,J))return;let Y=$[J];if(!y(Y)||Y.operationId!==J||typeof Y.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(Y.planDigest)||!["committed","cleaned"].includes(String(Y.phase))||!Array.isArray(Y.removed)||!Array.isArray(Y.finalized)||Y.removed.some((G)=>!y(G)||typeof G.id!=="string"||!$6(G.credentialEpoch))||Y.finalized.some((G)=>!y(G)||typeof G.id!=="string"||!$6(G.credentialEpoch)||typeof G.reservation!=="string"||!G.reservation||typeof G.enabled!=="boolean"))throw x("publishRoster",J,"invalid-input","the stored publication receipt is malformed");return structuredClone(Y)}async function uQ(X,J){let $=await M6(X.ctx);if($.status!=="ready")throw $8($,"publishRoster",J);return mQ($.config,J)}function nL(X,J){let $=()=>{throw x("publishRoster",J?.operationId??"","invalid-input","the publication plan is invalid")};if(!y(J)||typeof J.operationId!=="string"||!J.operationId||!Array.isArray(J.remove)||!Array.isArray(J.finalize)||!Array.isArray(J.order))$();let Y=new Set;for(let G of[...J.remove,...J.finalize]){if(!y(G)||typeof G.id!=="string"||x1(G.id)||Y.has(G.id)||!G.attribution)$();if(Y.add(G.id),g1("publishRoster",G.id,G.attribution),G.attribution.identity!==void 0&&(typeof G.attribution.identity!=="string"||!G.attribution.identity))$()}for(let G of J.remove)if(X.ctx.requireRemovedFingerprint&&!G.fingerprint||G.fingerprint!==void 0&&typeof G.fingerprint!=="string")$();for(let G of J.finalize)if(typeof G.reservation!=="string"||!G.reservation||typeof G.enabled!=="boolean"||(G.enabled?G.disabledReason!==void 0:typeof G.disabledReason!=="string"))$();if(J.order.some((G)=>typeof G!=="string"||x1(G))||new Set(J.order).size!==J.order.length)$()}function pQ(X,J){X.entries();let $=X.config[E0],Y={...gQ(X.config)};Object.defineProperty(Y,J.operationId,{value:J,enumerable:!0,writable:!0,configurable:!0}),$.publications=Y,delete $.publicationOrder}function sL(X,J,$){let Y=new Set;for(let z of v1(X.config)){if(!y(z)||typeof z.id!=="string")continue;if(Y.has(z.id))throw x("publishRoster",J.operationId,"invalid-input","publication needs a roster of unique named rows");Y.add(z.id)}let G=new Set(J.remove.map((z)=>z.id)),Q=$.filter((z)=>z.invalid!=="roster"&&!G.has(z.id));if(Q.length!==J.order.length||J.order.some((z)=>!Q.some((Z)=>Z.id===z))||Q.some((z)=>!J.order.includes(z.id)))throw x("publishRoster",J.operationId,"invalid-input","order must name exactly the surviving roster");return Q}async function fQ(X,J){await X.assertAll();for(let Y of J.removed)if(S6(X.stateAccount(Y.id)?.[_0])?.credentialEpoch===Y.credentialEpoch&&!X.rosterRow(Y.id))X.dropStateAccount(Y.id);for(let Y of J.finalized){let G=X.stateAccount(Y.id),Q=S6(G?.[_0]);if(G&&Q?.credentialEpoch===Y.credentialEpoch&&Q.staged?.reservation===Y.reservation){let z={...G[_0]};delete z.staged,X.setStateAccount(Y.id,{...G,[_0]:z})}}await X.commitState(void 0,{durable:!0});let $={...J,phase:"cleaned"};return pQ(X,$),await X.commitConfig({durable:!0}),$}async function cQ(X,J,$={}){return W6("publishRoster"),B6(X.ctx,"publishRoster",J?.operationId??"",$.onFailure,async(Y,G)=>{if(!y(J)||typeof J.operationId!=="string"||!J.operationId)throw x("publishRoster",J?.operationId??"","invalid-input","the publication needs an operation id");J=structuredClone(J);let Q=c9(J),z=[...Array.isArray(J.remove)?J.remove:[],...Array.isArray(J.finalize)?J.finalize:[]].filter((Z)=>y(Z)&&typeof Z.id==="string");for(let Z=0;;Z++){let W=await M6(X.ctx);if(W.status!=="ready")throw $8(W,"publishRoster",J.operationId);let B=new Map(z.map(({id:U})=>[U,x0(W.rows.find((j)=>j.id===U)??{id:U})]));for(let U of[...new Set(B.values())].sort())await Y.acquire(h6(X,{id:U}));await Y.acquire($.providerLock??X.providerLock);for(let U of $.extraLocks??[])await Y.acquire(U);let H=await a0(X.ctx,Y,G,{operation:"publishRoster",rowId:J.operationId},async(U)=>{let j=U.rows();if(z.some(({id:P})=>x0(j.find((A)=>A.id===P)??{id:P})!==B.get(P)))return;let q=mQ(U.config,J.operationId);if(q){if(q.planDigest!==Q)throw x("publishRoster",J.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(q.phase==="cleaned")return{outcome:"already-cleaned",receipt:q};return U.markPublicationDecision(),await U.syncConfig(),{outcome:"cleaned",receipt:await fQ(U,q)}}nL(X,J);let K=sL(U,J,j),L=[];for(let P of J.remove){U.assertNotStaged(P.id);let A=j.find((T)=>T.id===P.id);if(!A)throw x("publishRoster",P.id,"attribution","the removed row no longer exists");if(F2(P.id,A,P.attribution,"publishRoster"),!A.credential||P.fingerprint!==void 0&&J8(A.credential)!==P.fingerprint)throw x("publishRoster",P.id,"attribution","the removed secret no longer matches");L.push(A)}let F=[];for(let P of J.finalize){let A=j.find((w)=>w.id===P.id),T=S6(U.stateAccount(P.id)?.[_0]);if(!A||A.staged?.reservation!==P.reservation||T?.staged?.reservation!==P.reservation||A.enabled)throw x("publishRoster",P.id,"row-staged","the finalized row is not disabled under this reservation");let b=U.stateAccount(P.id),p=U.rosterRow(P.id),i=b?.[P6],X0=i===void 0?void 0:c9(i);if(!T?.staged||T.staged.label!==p?.label||T.staged.disabledReason!==A.disabledReason||T.staged.providerState!==X0)throw x("publishRoster",P.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");F2(P.id,A,P.attribution,"publishRoster"),F.push(A)}let O=K.find((P)=>P.torn);if(O)throw x("publishRoster",J.operationId,"attribution",`Row ${O.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let _=new Set;for(let P of K){if(!(J.finalize.find((T)=>T.id===P.id)?.enabled??P.enabled)||P.type!=="oauth"||P.identity===void 0)continue;if(_.has(P.identity))throw x("publishRoster",P.id,"invalid-input","the final enabled roster repeats a known identity");_.add(P.identity)}for(let P of K)if(P.identity!==void 0&&P.fingerprint!==void 0&&K.some((A)=>A.id!==P.id&&A.identity!==void 0&&A.identity!==P.identity&&A.fingerprint===P.fingerprint))throw x("publishRoster",P.id,"attribution","the resulting pool gives the same secret different known identities");for(let P of F)if(P.identity!==void 0&&L.some((A)=>A.identity!==void 0&&A.identity!==P.identity&&A.fingerprint===P.fingerprint))throw x("publishRoster",P.id,"attribution","the staged secret belonged to a different known identity");await q2(U,J.operationId,$.protect);let C={operationId:J.operationId,planDigest:Q,phase:"committed",removed:L.map((P)=>({id:P.id,credentialEpoch:P.credentialEpoch??1})),finalized:J.finalize.map((P,A)=>({id:P.id,credentialEpoch:F[A]?.credentialEpoch??1,reservation:P.reservation,enabled:P.enabled}))};for(let P of J.remove)U.dropRosterRows(P.id);for(let P of J.finalize){let A=U.rosterRow(P.id);A.enabled=P.enabled;let T={...U.entry(P.id)};if(delete T.staged,P.enabled)delete T.disabledReason;else T.disabledReason=P.disabledReason;U.setEntry(P.id,T)}let N=U.roster().filter((P)=>!y(P)||typeof P.id!=="string"||j.find((A)=>A.id===P.id)?.invalid==="roster");return U.config.accounts=[...J.order.map((P)=>U.rosterRow(P)),...N],pQ(U,C),await U.syncState(),await U.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await fQ(U,C)}},{completeTorn:!1});if(H)return H;if(await Y.releaseAll(),Z>=1)throw x("publishRoster",J.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class q5{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor(X,J,$,Y,G){this.rt=X,this.hook=J,this.onFailure=$,this.firedAtLoad=Y,this.logger=G}fire(X,J){if(!this.hook)return;if(J==="load"){if(this.firedAtLoad.has(X))return;this.firedAtLoad.add(X)}let $=this.run(X,J);this.inflight.add($),$.finally(()=>this.inflight.delete($))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run(X,J){let $=this.rt(),{ctx:Y}=$,G=new j9(Y.lockDefaults,Y.lockEnv),Q={writes:0};try{let z=await a0(Y,G,Q,{operation:"pull",rowId:X},async(W)=>{if(W.reservation(X)!==void 0)return;await W.completeTorn();let B=W.row(X);if(B?.unbound&&B.enabled&&B.type==="oauth"&&B.credential&&!B.invalid)_6("pull",B);if(!B?.candidate||B.type!=="oauth")return;if(!B.hasEntry)W.setEntry(X,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let H=W.row(X);if(!H?.credential||H.credentialEpoch===void 0)return;return{id:X,credential:H.credential,credentialEpoch:H.credentialEpoch,...H.identity!==void 0?{identity:H.identity}:{},reason:J}},{completeTorn:!1});if(await G.releaseAll(),!z){this.firedAtLoad.delete(X);return}await Y.hold?.("pull-before-request",X);let Z;try{Z=await this.hook?.(z)}catch(W){throw new K0({operation:"pull",rowId:X,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await V2($,X,{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},Z)}catch(z){this.firedAtLoad.delete(X);let Z=h1(z,"pull",X,Q);if(this.onFailure)try{await this.onFailure(X,Z)}catch(W){this.logger?.warn("pull failure hook threw",{rowId:X,error:W instanceof Error?W.message:String(W)})}else this.logger?.warn("quota pull failed",{rowId:X,kind:Z.kind})}finally{await G.releaseAll()}}}import{randomUUID as aL}from"node:crypto";function N5(X,J){if(p9("refresh",X,J?.staged),!J)throw x("refresh",X,"unknown-row",`no row ${X} in the pool`);if(J.invalid)throw x("refresh",X,"invalid-row",`row ${X} is invalid`);if(J.type!=="oauth"||J.credential?.type!=="oauth")throw x("refresh",X,"no-credential",`row ${X} holds no OAuth credential`);if(!J.enabled)throw x("refresh",X,"row-disabled",`row ${X} is disabled`);return J}function lQ(X){return x("refresh",X,"refresh-stamp-ahead",`row ${X}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function dQ(X,J,$,Y={}){W6("refresh");let{ctx:G}=X;return B6(G,"refresh",J,Y.onFailure,async(Q,z)=>{let{row:Z}=await s8(X,"refresh",J);N5(J,Z);let W=await Y.refuse?.(Z);if(W!==void 0)return{status:"refused",rowId:J,reason:W};let B=x0(Z),H;for(let K=0;;K++){await Q.acquire(h6(X,{id:J,identity:B===J?void 0:B})),await Q.acquire(Y.providerLock??X.providerLock);for(let O of Y.extraLocks??[])await Q.acquire(O);let F=await a0(G,Q,{writes:0},{operation:"refresh",rowId:J},async(O)=>{let _=N5(J,O.row(J));if(_6("refresh",_),!_.hasEntry)O.setEntry(J,{credentialEpoch:1,needsFirstReading:!0}),await O.commitConfig(),_=N5(J,O.row(J));if(x0(_)!==B)return{keyNow:x0(_)};let C=await Y.refuse?.(_);if(C!==void 0)return{refused:C};return{row:_,credential:_.credential,credentialEpoch:_.credentialEpoch,identity:_.identity}});if("refused"in F)return{status:"refused",rowId:J,reason:F.refused};if("keyNow"in F){if(await Q.releaseAll(),K>=1)throw x("refresh",J,"row-key-changed",`row ${J}'s wire identity changed twice while its lock was held`,!0);B=F.keyNow;continue}H=F;break}if(z5(H.credential.lastRefreshedAt,G.now()))throw lQ(J);await G.hold?.("refresh-before-provider",J),await Q.assertAll();let U;try{U=await $(H.credential,H.row)}catch(K){throw new K0({operation:"refresh",rowId:J,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:K})}if(typeof U?.refresh!=="string"||!U.refresh.trim())throw x("refresh",J,"provider","the provider returned no refresh token",!0);let j=U.providerState===void 0?void 0:a8(G.providerState,"refresh",J,U.providerState,"the provider state the provider returned"),q=await a0(G,Q,z,{operation:"refresh",rowId:J},async(K)=>{let L=K.row(J),F=K.entry(J);if(!L||L.invalid||!F||F.credentialEpoch!==H.credentialEpoch||L.identity!==H.identity)throw new K0({operation:"refresh",rowId:J,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${J} changed credential while its refresh was in flight; the rotation is discarded`});_6("refresh",L);let O=await Y.refuse?.(L);if(O!==void 0)return{refused:O};let _=G.now(),C=L.credential?.type==="oauth"?L.credential.lastRefreshedAt:void 0;if(z5(C,_))throw lQ(J);let N={type:"oauth",access:U.access,refresh:U.refresh,expires:U.expires},P=L.identity!==void 0&&U.identity!==void 0&&L.identity!==U.identity?{expectedIdentity:L.identity,returnedIdentity:U.identity}:void 0,A=P?{mark:aL(),enabled:!1,reason:`${b1}${JSON.stringify(P)}`}:void 0,T=L.identity===void 0&&U.identity?U.identity:void 0,b=await N2(X,K,J,N,{stamp:v4(C,_),transition:A,identity:T,...j!==void 0?{providerState:h4(G.providerState,"refresh",J,L.providerState,j)}:{}});if(A!==void 0)y4(K,J,A),await K.commitConfig();let p=L.identity;if(T!==void 0)u9(K,J,T),p=T,await K.commitConfig();return{stored:b,identity:p,contradiction:P,refused:void 0}});if(q.refused!==void 0)return{status:"refused",rowId:J,reason:q.refused};if(q.contradiction!==void 0)return{status:"identity-contradicted",rowId:J,...q.contradiction,credential:q.stored};if(Y.onPersisted)try{let K=Y.onPersisted;await O8("refresh",()=>K(J,q.stored))}catch(K){throw new K0({operation:"refresh",rowId:J,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:q.stored,message:"the after-persist hook threw; the rotation stays committed",cause:K})}return{status:"rotated",rowId:J,credential:q.stored,...q.identity!==void 0?{identity:q.identity}:{}}})}import{isDeepStrictEqual as oL}from"node:util";var O2=Object.freeze(["version","accounts",E0]);function L5(X){let J={};for(let[$,Y]of Object.entries(X))if(!O2.includes($))P2(J,$,Y);return J}function P2(X,J,$){Object.defineProperty(X,J,{value:$,enumerable:!0,writable:!0,configurable:!0})}function rL(X,J){let $={};for(let[Y,G]of Object.entries(X))if(O2.includes(Y))P2($,Y,G);else if(Object.hasOwn(J,Y))P2($,Y,J[Y]);for(let[Y,G]of Object.entries(J))if(!Object.hasOwn(X,Y))P2($,Y,G);return $}function iQ(X){return new K0({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:X})}async function nQ(X){let J=await M6(X.ctx);if(J.status==="error")return J;return{status:J.status,settings:L5(J.config)}}async function sQ(X,J,$={}){W6("updateSettings");let{ctx:Y}=X,G=$.onFailure;return B6(Y,"updateSettings",void 0,G&&((Q,z)=>G(z)),async(Q,z)=>{for(let W of $.extraLocks??[])await Q.acquire(W);let Z=Q.held.length;try{for(let F of Y.storeLocks)await Q.acquire(F);let W=await M6(Y);if(W.status!=="ready")throw $8(W,"updateSettings",void 0);let B=L5(W.config),H=structuredClone(B),U=await O8("updateSettings",()=>J(H)),j=U===void 0?H:U;if(!y(j))throw iQ("the settings mutator must produce an object");let q=O2.filter((F)=>Object.hasOwn(j,F));if(q.length>0)throw iQ(`settings cannot set the pool-owned key(s) ${q.join(", ")}`);if(oL(j,B))return{settings:B,outcome:"unchanged"};let K=rL(W.config,j),L={operation:"updateSettings",rowId:void 0};return await O6(Y.configPath,K,{beforeRename:async()=>{await Y.onStep?.("before-config-write",L),await Q.assertAll()}}),z.writes++,await Y.onStep?.("after-config-write",L),{settings:L5(K),outcome:"updated"}}finally{await Q.releaseTo(Z)}})}var aQ=new Map;function tL(X){let J=aQ.get(X);if(!J)J={removedIds:new Set,firedAtLoad:new Set},aQ.set(X,J);return J}function oQ(X){if(X.status==="ready")return{status:"ready",schemaVersion:q9,rows:X.rows};if(X.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(X.config.accounts)?X.config.accounts:[]};return X}function G8(X){let J=tL(X.configPath),$={...J5,...X.lockOptions},Y={provider:X.provider,configPath:X.configPath,statePath:X.statePath,codec:X.quota,...X.providerState?{providerState:X.providerState}:{},now:X.now??Date.now,storeLocks:X.storeLocks??[{name:"save",path:X.configPath},{name:"save",path:X.statePath}],lockDefaults:$,lockEnv:{now:X.now??Date.now,...X.onLockEvent?{onLockEvent:X.onLockEvent}:{},...X.onLockStep?{onLockStep:X.onLockStep}:{}},removedIds:J.removedIds,requireCredentialStamps:X.requireCredentialStamps===!0,requireRemovedFingerprint:X.requireRemovedFingerprint===!0,...X.logger?{logger:X.logger}:{},...X.onStep?{onStep:X.onStep}:{},...X.hold?{hold:X.hold}:{}},G=new q5(()=>Q,X.pull,X.onPullFailure,J.firedAtLoad,X.logger),Q={ctx:Y,providerLock:X.providerLock??{name:`provider-${encodeURIComponent(X.provider)}`,path:X.statePath},rowLockOptions:X.rowLockOptions??{},firePull:(z,Z)=>G.fire(z,Z)};return{async load(){let z=await M6(Y);if(z.status==="ready"){for(let Z of z.rows)if((Z.candidate||Z.torn&&Z.enabled)&&Z.type==="oauth"&&Z.needsFirstReading)G.fire(Z.id,"load")}return oQ(z)},async read(){return oQ(await M6(Y))},async initialize(z={}){return{status:await MQ(Y,z.dropKeys??[])}},add:(z,Z)=>SQ(Q,z,Z),publishRoster:(z,Z)=>cQ(Q,z,Z),publication:(z)=>uQ(Q,z),replace:(z,Z,W,B)=>IQ(Q,z,Z,W,B),rotate:(z,Z,W,B)=>bQ(Q,z,Z,W,B),updateProviderState:(z,Z,W,B)=>TQ(Q,z,Z,W,B),disable:(z,Z,W)=>xQ(Q,z,Z,W),enable:(z,Z)=>wQ(Q,z,Z),remove:(z,Z)=>vQ(Q,z,Z),reorder:(z,Z)=>yQ(Q,z,Z),readSettings:()=>nQ(Q),updateSettings:(z,Z)=>sQ(Q,z,Z),recordIdentity:(z,Z,W,B)=>hQ(Q,z,Z,W,B),refresh:(z,Z,W)=>dQ(Q,z,Z,W),recordQuota:(z,Z,W)=>V2(Q,z,Z,W),requestReading:(z)=>G.fire(z,"admission"),pullsSettled:()=>G.settled()}}var eL=[/\b[\w-]*(?:secret|token|password|passwd|api[_-]?key|authorization|verifier)["']?\s*[:=]\s*["']?(?:(?:Bearer|Basic)\s+)?[^\s"'&,;}]+/gi,/\b[0-9a-fA-F]{32,}\b/g];function P5(X={}){let{redactStrings:J}=M2({...X,extraValuePatterns:[...eL,...X.extraValuePatterns??[]]});return($)=>J($)}class I6 extends Error{code;constructor(X,J,$){super(J,$);this.name="CommandError",this.code=X}}var rQ=/^[a-z][a-z0-9-]{0,63}$/,D5={code:"action-failed",text:"That action failed."},XD=new Set(["unknown-row","invalid-row","invalid-input","id-exists","id-removed","type-mismatch","no-credential","row-disabled","row-protected","duplicate-identity","row-key-changed","invalid-order","pending-migration","provider","pull","attribution"]);function g4(X){if(X instanceof I6)return{code:rQ.test(X.code)?X.code:D5.code,text:X.message};if(X instanceof K0)return{code:`pool-${X.kind}`,text:XD.has(X.kind)?X.message:`The account pool could not do that (${X.kind}).`};return D5}var tQ="This cannot be undone. Continue?",JD=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function $D(X){let J=X.toLowerCase().replace(/[-_]/g,"");return JD.has(J)||J.endsWith("token")||J.endsWith("key")||J.endsWith("secret")}function YD(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function F5(X,J,$){if(typeof X==="string"){let G=$.redact(X);if(G!==X)$.redacted.push(J);return G}if(Array.isArray(X))return X.map((G,Q)=>F5(G,`${J}[${Q}]`,$));if(!YD(X))return X;let Y={};for(let[G,Q]of Object.entries(X)){if($D(G)){$.dropped.push(`${J}.${G}`);continue}Object.defineProperty(Y,G,{value:F5(Q,`${J}.${G}`,$),enumerable:!0,writable:!0,configurable:!0})}return Y}function eQ(X,J,$){let Y={redact:$.redact,dropped:[],redacted:[]},G=F5(X,"payload",Y);if(Y.dropped.length>0)$.logger.warn("credential-shaped field dropped from a command payload",{command:J,fields:Y.dropped});if(Y.redacted.length>0)$.logger.warn("secret-shaped text masked in a command payload",{command:J,fields:Y.redacted});return G}function GD(X){return{value:String(X.value),label:String(X.label)}}function QD(X){switch(X.kind){case"choice":return{kind:"choice",id:X.id,label:X.label,choices:(X.choices??[]).map(GD),...X.value!==void 0?{value:X.value}:{}};case"toggle":return{kind:"toggle",id:X.id,label:X.label,value:X.value===!0};case"number":return{kind:"number",id:X.id,label:X.label,...X.value!==void 0?{value:X.value}:{},...X.min!==void 0?{min:X.min}:{},...X.max!==void 0?{max:X.max}:{},...X.required?{required:!0}:{}};case"text":return{kind:"text",id:X.id,label:X.label,...X.value!==void 0&&!X.masked?{value:X.value}:{},...X.placeholder!==void 0?{placeholder:X.placeholder}:{},...X.masked?{masked:!0}:{},...X.required?{required:!0}:{}}}}function O5(X){if(X.irreversible===!0)return{message:X.confirm||tQ,irreversible:!0};if(X.confirm)return{message:X.confirm,irreversible:!1};return}function Xz(X){let J=O5(X);return{id:X.id,label:X.label,...X.description!==void 0?{description:X.description}:{},...X.group!==void 0?{group:String(X.group)}:{},knobs:(X.knobs??[]).map(QD),...J?{confirm:J}:{}}}function zD(X){return{id:X.id,...X.label!==void 0?{label:X.label}:{},enabled:X.enabled,type:X.type,...X.identity!==void 0?{identity:X.identity}:{}}}function ZD(X){return{id:X.id,label:X.label,...X.detail!==void 0?{detail:X.detail}:{},...X.group!==void 0?{group:String(X.group)}:{},...X.status!==void 0?{status:String(X.status)}:{},...X.account?{account:zD(X.account)}:{},...X.facts!==void 0?{facts:X.facts}:{},actions:(X.actions??[]).map(Xz)}}function WD(X){let{content:J}=X;return{id:X.id,slot:X.slot,title:X.title,lines:(J.lines??[]).map(String),items:(J.items??[]).map(ZD),actions:(J.actions??[]).map(Xz),...J.facts!==void 0?{facts:J.facts}:{}}}function Jz(X,J,$){return{command:X,title:J,sections:$.map(WD)}}function $z(X,J,$,Y){return eQ({command:X,menu:Jz(X,J,$)},X,Y)}function Yz(X,J,$,Y,G){return eQ({command:X,ok:Y.ok,text:String(Y.text),...!Y.ok&&Y.code!==void 0?{code:rQ.test(Y.code)?Y.code:"refused"}:{},...Y.needsConfirmation?{needsConfirmation:!0}:{},menu:Jz(X,J,$)},X,G)}var Zz="disabled from the command menu";function BD(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function o8(X){return BD(X)?{...X}:{}}function HD(X){if(X.status!=="ready")return[];let J=new Set;return X.rows.filter(($)=>{if(J.has($.id))return!1;return J.add($.id),!0})}function VD(X,J){return X.label??J??X.id}function _2(X,J){return Y6(X.quota)?f0(X.quota,J):void 0}function Wz(X,J){return`${X} ${J}${X===1?"":"s"}`}var m4="Actions";function UD(X){if(X.status==="pending-migration")return"The account pool has not been migrated yet.";if(X.status==="error")return`The ${X.file} file cannot be read: ${X.reason}`;return}function Gz(X,J){switch(J.outcome){case"added":return`Added ${X}.`;case"added-disabled":return`Added ${X}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${X}.`;case"rotated":return`${X} was already in the pool; its credential was updated.`;case"exists":return`${X} was already in the pool; its credential is unchanged.`}}function Qz(X){return g4(X).text}async function KD(X){let J=await X.read(),$=await X.readSettings();return{load:J,rows:HD(J),settings:$.status==="error"?{}:$.settings}}function A2(X,J){let $=J.accounts?.describeIdentity?J.accounts.describeIdentity(X):X.identity;return{account:{id:X.id,...X.label!==void 0?{label:X.label}:{},enabled:X.enabled,type:X.type,...$!==void 0?{identity:$}:{}},name:VD(X,$)}}function jD(X,J){let{store:$,extraLocks:Y}=X,G=Y?{extraLocks:Y}:{},Q=J.rows.map((U)=>U.id),z=UD(J.load),Z=J.rows.filter((U)=>U.enabled).length,W=J.rows.map((U,j)=>{let{account:q,name:K}=A2(U,X),L=[U.type==="api"?"API key":"OAuth",...q.identity!==void 0?[q.identity]:[],...!U.invalid&&!U.enabled&&U.disabledReason?[`disabled: ${U.disabledReason}`]:[]].join(" · "),F=U.invalid?"invalid":U.enabled?"enabled":"disabled",O=[];if(!U.invalid&&U.enabled)O.push({id:"disable",label:"Disable",run:async()=>{return await $.disable(U.id,Zz,G),`Disabled ${K}.`}});if(!U.invalid&&!U.enabled)O.push({id:"enable",label:"Enable",run:async()=>{return await $.enable(U.id,G),`Enabled ${K}.`}});if(Q.length>1)O.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:Q.map((_,C)=>({value:String(C+1),label:String(C+1)})),value:String(j+1)}],run:async({values:_})=>{let C=Number(_.position),N=Q.filter((A)=>A!==U.id);return N.splice(C-1,0,U.id),(await $.reorder(N,G)).outcome==="unchanged"?`${K} is already at position ${C}.`:`Moved ${K} to position ${C}.`}});return O.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${K}? Its stored credential is deleted.`,run:async()=>{return await $.remove(U.id,{...G,...X.accounts?.protect?{protect:X.accounts.protect}:{}}),`Removed ${K}.`}}),{id:U.id,label:K,detail:L,group:"Accounts",status:F,account:q,actions:O}}),B=X.accounts?.login,H=[];if(B&&!z)H.push({id:"add",label:B.label??"Add account",group:m4,knobs:B.knobs??[],run:async({values:U,invocation:j})=>{let q=await B.run(U,j);if(q.status==="cancelled")return{ok:!1,text:q.message??"Login cancelled."};if(q.status==="ready"){let K=await $.add(q.account,G);return Gz(q.account.label??K.id,K)}return q.completion.then(async(K)=>{if(!K){j.notify("Login cancelled.","warning");return}let L=await $.add(K,G);j.notify(Gz(K.label??L.id,L))},(K)=>{j.notify(`Adding the account failed: ${Qz(K)}`,"error")}).catch((K)=>{j.notify(`Adding the account failed: ${Qz(K)}`,"error")}),q.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:z?[z]:[J.rows.length===0?"No accounts yet":`${Wz(J.rows.length,"account")}, ${Z} enabled`],items:z?[]:W,actions:H}}}function qD(X,J){let $=X.quota?.scope??"all",Y=X.now(),G=$==="all"?"Accounts":`Accounts · ${$}`,Q=async(H,U)=>{if(X.quota?.check)await X.quota.check(H,U);else{for(let j of H)X.store.requestReading(j);await X.store.pullsSettled()}},z=J.rows.filter((H)=>H.candidate),Z=z.map((H)=>{let{account:U,name:j}=A2(H,X),q=_2(H,$);return{id:H.id,label:j,group:G,status:_8(q,{now:Y,form:"compact"}),detail:_8(q,{now:Y,form:"full"}),account:U,actions:[{id:"check",label:"Check this account",run:async({invocation:K})=>{return await Q([H.id],K),`Checked quota for ${j}.`}}]}}),W=J.rows.filter((H)=>!H.candidate).map((H)=>{let{name:U}=A2(H,X),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",q=_8(_2(H,$),{now:Y,form:"compact"});return`${U} (${j}): ${q}`}),B=[];if(z.length>0)B.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:m4,run:async({invocation:H})=>{let U=z.map((j)=>j.id);return await Q(U,H),`Checked quota for ${Wz(U.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:J.rows.length===0?["No accounts yet"]:W,items:Z,actions:B}}}function ND(X,J){let{store:$,extraLocks:Y}=X,G=Y?{extraLocks:Y}:{},Q=[{value:"ordered",label:"Ordered (roster order)"},...X.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],z=o8(J.settings.routing).mode,Z=typeof z==="string"&&Q.some((K)=>K.value===z)?z:"ordered",W=dX(Z),B=J.rows.map((K)=>K.id),H=I1(B,W.placement,X.routing?.formerMainId??$2),j=[`Mode: ${Q.find((K)=>K.value===Z)?.label??Z}`];if(B.length>0)j.push(`Roster order: ${B.join(", ")}`);if(W.mode==="ordered"&&H.join()!==B.join())j.push(`Tried in order: ${H.join(", ")}`);let q=[{id:"mode",label:"Change mode",group:m4,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:Q,value:Z}],run:async({values:K})=>{let L=String(K.mode);return await $.updateSettings((F)=>{F.routing={...o8(F.routing),mode:L};return},G),`Routing mode set to ${Q.find((F)=>F.value===L)?.label??L}.`}}];if(B.length>1)q.push({id:"order",label:"Set order",group:m4,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:B.join(", "),required:!0}],run:async({values:K})=>{let L=String(K.order).split(/[\s,]+/).filter((O)=>O.length>0),F=await $.reorder(L,G);return F.outcome==="unchanged"?"The order is unchanged.":`Order set to ${F.ids.join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:q}}}function LD(X,J){if(X.limits?.labels)return[...X.limits.labels];let $=X.quota?.scope??"all",Y=[];for(let G of J.rows)for(let Q of _2(G,$)?.limits??[])if(!Y.includes(Q.label))Y.push(Q.label);return Y.length>0?Y:["primary"]}function DD(X,J){let $=X.quota?.scope??"all",Y=new Map;for(let G of J.rows)for(let Q of _2(G,$)?.limits??[])if(Q.windowMinutes!==void 0&&!Y.has(Q.label))Y.set(Q.label,zz(Q));return(G)=>Y.get(G)??G}function FD(X,J){let{store:$,extraLocks:Y}=X,G=Y?{extraLocks:Y}:{},Q=o8(J.settings.killswitch),z=Q.enabled===!0,Z=o8(Q.accounts),W=LD(X,J),B=DD(X,J),H=z?"on":"off",U=J.rows.map((j)=>{let{account:q,name:K}=A2(j,X),L=o8(Z[j.id]),F=W.filter((O)=>typeof L[O]==="number");return{id:j.id,label:K,group:`Floors · killswitch ${H}`,status:F.length===0?"no floors":F.map((O)=>`${B(O)} ≥${L[O]}%`).join(" · "),account:q,actions:[{id:"floors",label:"Set floors",knobs:W.map((O)=>({kind:"number",id:O,label:`Minimum % left for ${B(O)}`,min:0,max:100,...typeof L[O]==="number"?{value:L[O]}:{}})),run:async({values:O})=>{return await $.updateSettings((_)=>{let C=o8(_.killswitch),N=o8(C.accounts),P=o8(N[j.id]);for(let A of W){let T=O[A];if(typeof T==="number")P[A]=T;else if(T===null)delete P[A]}if(Object.keys(P).length>0)N[j.id]=P;else delete N[j.id];if(Object.keys(N).length>0)C.accounts=N;else delete C.accounts;_.killswitch=C;return},G),`Floors updated for ${K}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${H}`],items:U,actions:[{id:"killswitch",label:z?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:m4,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!z}],run:async({values:j})=>{let q=j.enabled===!0;return await $.updateSettings((K)=>{K.killswitch={...o8(K.killswitch),enabled:q};return},G),`Killswitch ${q?"on":"off"}.`}}]}}}async function Bz(X){let J=await KD(X.store);return[jD(X,J),qD(X,J),ND(X,J),FD(X,J)]}var PD=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),M5=["accounts","quota","routing","limits"];function Hz(X,J){let{sessionId:$}=X,Y=X.notify.bind(X);return Object.freeze({...$!==void 0?{sessionId:$}:{},notify:(G,Q)=>Q===void 0?Y(J(String(G))):Y(J(String(G)),Q)})}function OD(X,J){switch(X.kind){case"choice":{let $=J??X.value;if(typeof $==="string"&&X.choices.some((Y)=>Y.value===$))return{value:$};return{problem:`Choose one of the options for ${X.label}.`}}case"toggle":{let $=J??X.value;return typeof $==="boolean"?{value:$}:{problem:`${X.label} must be on or off.`}}case"number":{let $=J===void 0?X.value??null:J;if($===null||$==="")return X.required?{problem:`${X.label} needs a number.`}:{value:null};let Y=typeof $==="number"?$:Number($);if(typeof $==="boolean"||!Number.isFinite(Y))return{problem:`${X.label} needs a number.`};if(X.min!==void 0&&Y<X.min)return{problem:`${X.label} must be at least ${X.min}.`};if(X.max!==void 0&&Y>X.max)return{problem:`${X.label} must be at most ${X.max}.`};return{value:Y}}case"text":{let $=J===void 0?X.value??null:J;if($===null||$==="")return X.required?{problem:`${X.label} cannot be empty.`}:{value:null};return typeof $==="string"?{value:$}:{problem:`${X.label} must be text.`}}}}function MD(X,J){let $={};for(let Y of X){let G=J&&Object.hasOwn(J,Y.id)?J[Y.id]:void 0,Q=OD(Y,G);if("problem"in Q)return Q;$[Y.id]=Q.value}return{values:$}}function _D(X,J){let $=X.find((G)=>G.id===J.sectionId);if(!$)return;return(J.itemId===void 0?$.content.actions:$.content.items?.find((G)=>G.id===J.itemId)?.actions)?.find((G)=>G.id===J.actionId)}function l9(X){let J=X.logger??Z0("commands"),$=P5(X.redaction),Y={logger:J,redact:$},G=X.now??Date.now,Q=X.extras??[],z=X.replace??{},Z=M5.filter((j)=>!z[j]);for(let j of M5)if(z[j]&&X[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let W=X.store;if(Z.length>0&&!W)throw Error(`a store is required for the built-in ${Z.join(", ")} section${Z.length>1?"s":""}`);let B=new Set;for(let j of Q){if(PD.has(j.id)||B.has(j.id))throw Error(`extra section id ${j.id} is taken`);B.add(j.id)}async function H(j,q,K,L){try{return{id:j,slot:q,title:K.title,content:await K.build(L)}}catch(F){return J.warn("command menu section failed to build",{command:X.command,section:j,error:$(F instanceof Error?F.message:String(F))}),{id:j,slot:q,title:K.title,content:{lines:["This section could not be loaded."]}}}}async function U(j){let q=W&&Z.length>0?await Bz({store:W,now:G,...X.extraLocks?{extraLocks:X.extraLocks}:{},...X.accounts?{accounts:X.accounts}:{},...X.quota?{quota:X.quota}:{},...X.routing?{routing:X.routing}:{},...X.limits?{limits:X.limits}:{}}):[],K=[];for(let L of M5){let F=z[L];if(F)K.push(await H(L,L,F,j));else{let O=q.find((_)=>_.slot===L);if(O)K.push(O)}}if(X.cache)K.push(await H("cache","cache",X.cache,j));if(X.diagnostics)K.push(await H("diagnostics","diagnostics",X.diagnostics,j));for(let L of Q)K.push(await H(L.id,"extra",L,j));return K}return{command:X.command,async open(j){let q=Hz(j,$);return $z(X.command,X.title,await U(q),Y)},async apply(j,q){let K=Hz(q,$),L=async(N)=>Yz(X.command,X.title,await U(K),N,Y),F=j.command===X.command?_D(await U(K),j):void 0;if(!F)return L({ok:!1,code:"unavailable",text:"That action is no longer available."});let O=O5(F);if(O&&j.confirmed!==!0)return L({ok:!1,code:"needs-confirmation",text:O.message,needsConfirmation:!0});let _=MD(F.knobs??[],j.values);if("problem"in _)return L({ok:!1,code:"invalid-input",text:_.problem});let C;try{let N=await F.run({values:_.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:K});C=typeof N==="string"?{ok:!0,text:N}:{ok:N.ok,text:N.text,...N.ok?{}:{code:N.code??"refused"}}}catch(N){let P=g4(N);J.warn("command menu action failed",{command:X.command,section:j.sectionId,action:j.actionId,code:P.code,error:$(N instanceof Error?N.message:String(N))}),C={ok:!1,...P}}return L(C)}}}function AD(X){return X===null||typeof X==="string"||typeof X==="boolean"||typeof X==="number"&&Number.isFinite(X)}function _5(X){if(X===null||typeof X!=="object"||Array.isArray(X))return;let J=X;if(typeof J.command!=="string"||typeof J.sectionId!=="string"||typeof J.actionId!=="string")return;if(J.itemId!==void 0&&typeof J.itemId!=="string")return;if(J.sessionId!==void 0&&typeof J.sessionId!=="string")return;if(J.confirmed!==void 0&&typeof J.confirmed!=="boolean")return;let $={};if(J.values!==void 0){if(J.values===null||typeof J.values!=="object"||Array.isArray(J.values))return;for(let[Y,G]of Object.entries(J.values)){if(!AD(G))return;Object.defineProperty($,Y,{value:G,enumerable:!0,writable:!0,configurable:!0})}}return{command:J.command,sectionId:J.sectionId,actionId:J.actionId,...typeof J.itemId==="string"?{itemId:J.itemId}:{},...J.values!==void 0?{values:$}:{},...J.confirmed===!0?{confirmed:!0}:{},...typeof J.sessionId==="string"?{sessionId:J.sessionId}:{}}}import{createHash as mP,randomUUID as uP}from"node:crypto";import{setTimeout as pP}from"node:timers/promises";import{createHash as TD}from"node:crypto";var A5=86400000,RD=300000,CD=3600000,ED=60000,SD=900000,ID=300000;function T5(X){return X instanceof Error?X.message:String(X)}function R5(X){let J=X?.status;if(typeof J==="number")return J===429||J>=500;if(!(X instanceof Error))return!1;return X.name==="AbortError"||X.name==="TimeoutError"||X.message.includes("fetch failed")||"code"in X&&(X.code==="ECONNRESET"||X.code==="ECONNREFUSED"||X.code==="ETIMEDOUT"||X.code==="UND_ERR_CONNECT_TIMEOUT")}function C5(X){let J=T5(X),$=X?.status;if(typeof $==="number")return $===429||$>=500;if(!(X instanceof Error))return!1;let Y=X.code;return X.name==="AbortError"||X.name==="TimeoutError"||J.includes("fetch failed")||Y==="ECONNRESET"||Y==="ECONNREFUSED"||Y==="ETIMEDOUT"||Y==="UND_ERR_CONNECT_TIMEOUT"}function Q8(X){return TD("sha256").update(X).digest("hex")}function m1(X){let J=Q8(X.refreshToken),Y=(X.previous?.tokenHash===J?X.previous.retryCount??0:0)+1,G,Q=X.error?.retryAfter;if(typeof Q==="number"&&Q>0)G=Q*1000;else if(R5(X.error))G=Math.min(CD,RD*2**Math.min(Y-1,6));else G=A5;return{message:T5(X.error),checkedAt:X.now,nextRetryAt:X.now+G,retryCount:Y,tokenHash:J}}function t0(X,J,$){if(!X?.nextRetryAt||X.nextRetryAt<=$)return!1;if(!J)return!0;return X.tokenHash===Q8(J)}function r8(X,J){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((X.nextRetryAt??J)-J)/1000))}s after: ${X.message}`}function u4(X){let $=(X.previous?.retryCount??0)+1,Y,G=X.error?.retryAfter;if(typeof G==="number"&&G>0)Y=G*1000;else if(C5(X.error))Y=Math.min(SD,ED*2**Math.min($-1,6));else Y=ID;return{message:T5(X.error),checkedAt:X.now,nextRetryAt:X.now+Y,retryCount:$}}function u1(X,J){if(!X?.nextRetryAt||X.nextRetryAt<=J)return!1;return!0}function E5(X){if(!X)return;let J=Number(X);if(Number.isFinite(J)&&J>0)return Math.ceil(J);let $=Date.parse(X);if(Number.isFinite($)){let Y=Math.ceil(($-Date.now())/1000);return Y>0?Y:void 0}return}import{createServer as Vz}from"node:http";import{setTimeout as bD}from"node:timers/promises";var C2="app_EMoamEEZ73f0CkXaXp7hrann",n9="https://auth.openai.com",c4=1455,kD=3000,xD="cortexkit-opencode-openai-auth";function E2(X){return`${xD}/${X}`}var Kz="main",wD=`"${Kz}" is a reserved account id; choose a different label.`;function S2(X){let J=new Uint8Array(X),$=String.fromCharCode(...J);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function I5(){let J=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((Y)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[Y%66]).join(""),$=S2(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(J)));return{verifier:J,challenge:$}}function H6(X){if(X.length>16384)return;let J=X.split(".");if(J.length!==3)return;let $=J[1];if(!$||$.length>8192)return;try{return JSON.parse(Buffer.from($,"base64url").toString())}catch{return}}function V6(X){let J=X.chatgpt_account_id;if(typeof J==="string"&&J.length>0)return J;let $=X["https://api.openai.com/auth"];if($&&typeof $==="object"&&!Array.isArray($)&&typeof $.chatgpt_account_id==="string"&&$.chatgpt_account_id.length>0)return $.chatgpt_account_id;let Y=X.organizations;if(Array.isArray(Y)){let G=Y[0];if(G&&typeof G==="object"&&!Array.isArray(G)&&typeof G.id==="string"&&G.id.length>0)return G.id}return}function z8(X){if(X.id_token){let J=H6(X.id_token),$=J&&V6(J);if($)return $}if(X.access_token){let J=H6(X.access_token);return J?V6(J):void 0}return}function vD(X){return typeof X==="string"&&X.toLowerCase()===Kz}function S5(X){if(vD(X))throw Error(wD);return X}function b5(X,J,$){let Y=new URLSearchParams({response_type:"code",client_id:C2,redirect_uri:X,scope:"openid profile email offline_access",code_challenge:J.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:$,originator:"opencode"});return`${n9}/oauth/authorize?${Y.toString()}`}async function yD(X,J,$){let Y=await fetch(`${n9}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:X,redirect_uri:J,client_id:C2,code_verifier:$.verifier}).toString()});if(!Y.ok)throw Error(`Token exchange failed: ${Y.status}`);return await Y.json()}function hD(X){return X.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var fD=`<!doctype html>
2
- <html>
3
- <head>
4
- <title>CortexKit OpenAI Auth - Authorization Successful</title>
5
- <style>
6
- body {
7
- font-family:
8
- system-ui,
9
- -apple-system,
10
- sans-serif;
11
- display: flex;
12
- justify-content: center;
13
- align-items: center;
14
- height: 100vh;
15
- margin: 0;
16
- background: #131010;
17
- color: #f1ecec;
18
- }
19
- .container {
20
- text-align: center;
21
- padding: 2rem;
22
- }
23
- h1 {
24
- color: #f1ecec;
25
- margin-bottom: 1rem;
26
- }
27
- p {
28
- color: #b7b1b1;
29
- }
30
- </style>
31
- </head>
32
- <body>
33
- <div class="container">
34
- <h1>Authorization Successful</h1>
35
- <p>You can close this window and return to OpenCode.</p>
36
- </div>
37
- <script>
38
- setTimeout(() => window.close(), 2000)
39
- </script>
40
- </body>
41
- </html>`,T2=(X)=>`<!doctype html>
42
- <html>
43
- <head>
44
- <title>CortexKit OpenAI Auth - Authorization Failed</title>
45
- <style>
46
- body {
47
- font-family:
48
- system-ui,
49
- -apple-system,
50
- sans-serif;
51
- display: flex;
52
- justify-content: center;
53
- align-items: center;
54
- height: 100vh;
55
- margin: 0;
56
- background: #131010;
57
- color: #f1ecec;
58
- }
59
- .container {
60
- text-align: center;
61
- padding: 2rem;
62
- }
63
- h1 {
64
- color: #fc533a;
65
- margin-bottom: 1rem;
66
- }
67
- p {
68
- color: #b7b1b1;
69
- }
70
- .error {
71
- color: #ff917b;
72
- font-family: monospace;
73
- margin-top: 1rem;
74
- padding: 1rem;
75
- background: #3c140d;
76
- border-radius: 0.5rem;
77
- }
78
- </style>
79
- </head>
80
- <body>
81
- <div class="container">
82
- <h1>Authorization Failed</h1>
83
- <p>An error occurred during authorization.</p>
84
- <div class="error">${hD(X)}</div>
85
- </div>
86
- </body>
87
- </html>`,R2=[],p4,t8=new Map;function Uz(X,J){return new Promise(($,Y)=>{let G=(z)=>{X.off("listening",Q),Y(z)},Q=()=>{X.off("error",G),$()};X.once("error",G),X.once("listening",Q),X.listen(c4,J)})}function jz(X){X.close(()=>{}),X.closeIdleConnections?.(),setTimeout(()=>{X.closeAllConnections?.()},25).unref?.()}function d9(){return t8.size}function e8(X){if(t8.delete(X),d9()===0)i9()}async function k5(){let X=`http://localhost:${c4}/auth/callback`;if(R2.length>0)return{port:c4,redirectUri:X};if(p4)return p4;p4=(async()=>{let J=(Q,z)=>{let Z=new URL(Q.url||"/",`http://127.0.0.1:${c4}`);if(Z.pathname==="/auth/callback"){let W=Z.searchParams.get("code"),B=Z.searchParams.get("state"),H=Z.searchParams.get("error"),U=Z.searchParams.get("error_description");if(H){let q=U||H;if(B){let K=t8.get(B);if(K)K.reject(Error(q)),e8(B);else if(d9()===0)i9()}else if(d9()===0)i9();z.writeHead(200,{"Content-Type":"text/html"}),z.end(T2(q));return}if(!B){if(d9()===0)i9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(T2("Missing state parameter"));return}if(!W){if(d9()===0)i9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(T2("Missing authorization code"));return}let j=t8.get(B);if(!j){if(d9()===0)i9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(T2("Unknown state — authorization may have expired"));return}e8(B),yD(W,X,j.pkce).then((q)=>j.resolve(q)).catch((q)=>j.reject(q)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(fD);return}if(Z.pathname==="/cancel"){let W=Z.searchParams.get("state"),B=W?[W]:[...t8.keys()];z.writeHead(200),z.end("Login cancelled");for(let H of B){let U=t8.get(H);if(!U)continue;U.reject(Error("Login cancelled")),e8(H)}if(d9()===0)i9();return}z.writeHead(404),z.end("Not found")},$=Vz(J);await Uz($,"127.0.0.1");let Y=[$],G=Vz(J);try{await Uz(G,"::1"),Y.push(G)}catch(Q){let z=Q.code;if(z!=="EADDRNOTAVAIL"&&z!=="EAFNOSUPPORT")throw jz($),Q}return R2=Y,{port:c4,redirectUri:X}})();try{return await p4}finally{p4=void 0}}function i9(){let X=R2;R2=[];for(let J of X)jz(J)}function x5(X,J,$=300000,Y){return new Promise((G,Q)=>{if(Y?.aborted){e8(J),Q(Error("Login cancelled"));return}let z=setTimeout(()=>{if(t8.get(J))e8(J),Q(Error("OAuth callback timeout — authorization took too long"))},$),Z=()=>{if(clearTimeout(z),t8.get(J))e8(J),Q(Error("Login cancelled"))};if(Y)Y.addEventListener("abort",Z);t8.set(J,{pkce:X,state:J,resolve:(W)=>{if(clearTimeout(z),Y)Y.removeEventListener("abort",Z);G(W)},reject:(W)=>{if(clearTimeout(z),Y)Y.removeEventListener("abort",Z);Q(W)}})})}async function w5(X){let J=await fetch(`${n9}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":E2(X)},body:JSON.stringify({client_id:C2})});if(!J.ok)throw Error("Failed to initiate device authorization");let $=await J.json();return{deviceData:$,url:`${n9}/codex/device`,instructions:`Enter code: ${$.user_code}`}}async function v5(X,J,$){let Y=Math.max(parseInt(X.interval,10)||5,1)*1000,G=typeof X.expires_in==="number"?X.expires_in:parseInt(X.expires_in||"",10),Q=!Number.isNaN(G)&&G>0?G*1000:900000,z=Date.now();while(!0){if($?.aborted)throw Error("Device authorization cancelled");if(Date.now()-z>Q)throw Error("Device authorization expired");let Z=await fetch(`${n9}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":E2(J)},body:JSON.stringify({device_auth_id:X.device_auth_id,user_code:X.user_code})});if(Z.ok){let H=await Z.json(),U=await fetch(`${n9}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:H.authorization_code,redirect_uri:`${n9}/deviceauth/callback`,client_id:C2,code_verifier:H.code_verifier}).toString()});if(!U.ok)throw Error(`Token exchange failed: ${U.status}`);return await U.json()}if(Z.status!==403&&Z.status!==404)throw Error(`Device authorization failed: ${Z.status}`);let W=Q-(Date.now()-z);if(W<=0)throw Error("Device authorization expired");let B=Math.min(Y+kD,W);try{await bD(B,void 0,{signal:$})}catch(H){if(H instanceof Error&&H.name==="AbortError")throw Error("Device authorization cancelled");throw H}}}async function I2(X){let{label:J,headless:$=!1,signal:Y,version:G}=X;if(S5(J),$){let{deviceData:H,url:U,instructions:j}=await w5(G),q=(async()=>{let K=await v5(H,G,Y),L=Date.now(),F=z8(K);return{id:S5(J||F||crypto.randomUUID()),label:J||void 0,type:"oauth",access:K.access_token,refresh:K.refresh_token,expires:L+(K.expires_in??3600)*1000,enabled:!0,addedAt:L,lastUsed:L,lastRefreshedAt:L,accountId:F}})();return{url:U,instructions:j,completion:q}}let{redirectUri:Q}=await k5(),z=await I5(),Z=S2(crypto.getRandomValues(new Uint8Array(32)).buffer),W=b5(Q,z,Z),B=(async()=>{try{if(Y?.aborted)throw Error("Login cancelled");let H=await x5(z,Z,void 0,Y),U=Date.now(),j=z8(H);return{id:S5(J||j||crypto.randomUUID()),label:J||void 0,type:"oauth",access:H.access_token,refresh:H.refresh_token,expires:U+(H.expires_in??3600)*1000,enabled:!0,addedAt:U,lastUsed:U,lastRefreshedAt:U,accountId:j}}finally{e8(Z)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:B}}function b2(X){if(X==null||X==="")return;let J=typeof X==="number"?X:Number(X);if(Number.isFinite(J)){let Y=J<100000000000?J*1000:J,G=new Date(Y);return Number.isNaN(G.getTime())?void 0:G.toISOString()}let $=new Date(X);return Number.isNaN($.getTime())?void 0:$.toISOString()}function y5(X){let J=Number(X);return Number.isFinite(J)&&J>0?J:void 0}function qz(X){return typeof X==="number"&&Number.isFinite(X)&&X>=0?X:void 0}function Nz(X,J){let $=X.get(J);if($===null||$.trim()==="")return;let Y=Number($);if(!Number.isFinite(Y)||Y<0||Y>100)return;let G=J.slice(0,-13),Q=y5(X.get(`${G}-window-minutes`)),z=b2(X.get(`${G}-reset-at`)??void 0);if(Y===0&&X.get(`${G}-window-minutes`)==="0"&&!z)return;return{usedPercent:Y,remainingPercent:100-Y,resetsAt:z,checkedAt:Date.now(),...Q!==void 0?{windowMinutes:Q}:{}}}var Fz=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function Pz(X,J){let $=X.get(J);if($===null)return"absent";if($.trim()==="")return"invalid";let Y=Number($);return Number.isFinite(Y)&&Y>=0&&Y<=100?"valid":"invalid"}function s9(X){if(Fz.some((G)=>Pz(X,G)==="invalid"))return{};let J={},$=Nz(X,"x-codex-primary-used-percent");if($)J.primary=$;let Y=Nz(X,"x-codex-secondary-used-percent");if(Y)J.secondary=Y;return J}function c1(X){let J=Fz.map(($)=>Pz(X,$));return J.includes("valid")&&!J.includes("invalid")}function Lz(X){if(!X)return;if(!Number.isFinite(X.used_percent)||X.used_percent<0||X.used_percent>100)return;let J=y5(X.window_minutes),$=b2(X.reset_at);if(X.used_percent===0&&J===void 0&&!$)return;return{usedPercent:X.used_percent,remainingPercent:100-X.used_percent,resetsAt:$,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J}:{}}}function Oz(X){let J={},$=Lz(X.rate_limits?.primary);if($)J.primary=$;let Y=Lz(X.rate_limits?.secondary);if(Y)J.secondary=Y;return J}function p1(X){if(X==null||X==="")return;let J=Number(X);return Number.isFinite(J)&&J>=0?J:void 0}function Dz(X){if(!X)return;if(!Number.isFinite(X.used_percent)||X.used_percent<0||X.used_percent>100)return;let J=y5(X.limit_window_seconds),$=b2(X.reset_at);if(X.used_percent===0&&J===void 0&&!$)return;return{usedPercent:X.used_percent,remainingPercent:100-X.used_percent,resetsAt:$,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J/60}:{}}}function Mz(X){let J={},$=Dz(X.rate_limit?.primary_window);if($)J.primary=$;let Y=Dz(X.rate_limit?.secondary_window);if(Y)J.secondary=Y;let G=qz(X.rate_limit_reset_credits?.available_count);if(G!==void 0)J.resetCreditsAvailable=G;let Q=qz(X.rate_limit_reset_credits?.applicable_available_count);if(Q!==void 0)J.resetCreditsApplicable=Q;let z=X.spend_control?.individual_limit;if(X.spend_control===null||z===null)J.spendControlCleared=!0;if(z&&typeof X.spend_control?.reached==="boolean"){let W=p1(z.limit),B=p1(z.used),H=p1(z.remaining),U=p1(z.used_percent),j=p1(z.remaining_percent);if(W!==void 0&&B!==void 0&&H!==void 0&&U!==void 0&&j!==void 0)J.spendControl={limit:W,used:B,remaining:H,usedPercent:U,remainingPercent:j,resetsAt:b2(z.reset_at),unit:z.unit,source:z.source,reached:X.spend_control.reached}}let Z=X.credits;if(Z&&typeof Z.has_credits==="boolean"&&typeof Z.unlimited==="boolean"&&typeof Z.overage_limit_reached==="boolean"){let W=p1(Z.balance);J.credits={hasCredits:Z.has_credits,unlimited:Z.unlimited,overageLimitReached:Z.overage_limit_reached,...W!==void 0?{balance:W}:{}}}return J}import{readdirSync as _F,statSync as AF}from"node:fs";import{tmpdir as JZ,userInfo as TF}from"node:os";import{join as n1}from"node:path";import{debuglog as oD}from"node:util";import{createHmac as pD,randomBytes as cD,timingSafeEqual as lD}from"node:crypto";import uD from"node:net";var f6=2,k2=21,x2=5,h5=67108864,u;(function(X){X[X.Request=0]="Request",X[X.Response=1]="Response",X[X.Push=2]="Push",X[X.StreamData=3]="StreamData",X[X.StreamEnd=4]="StreamEnd",X[X.Error=5]="Error",X[X.Cancel=6]="Cancel",X[X.Ping=7]="Ping",X[X.Pong=8]="Pong",X[X.Hello=9]="Hello",X[X.HelloAck=10]="HelloAck",X[X.Goodbye=11]="Goodbye"})(u||(u={}));var _z=u.Goodbye;function Az(X){return X===u.Cancel||X===u.Ping||X===u.Pong||X===u.Goodbye}var e0;(function(X){X[X.Passive=0]="Passive",X[X.Interactive=1]="Interactive",X[X.Background=2]="Background"})(e0||(e0={}));var U6;(function(X){X[X.Normal=0]="Normal",X[X.Expedite=1]="Expedite",X[X.Sheddable=2]="Sheddable"})(U6||(U6={}));var Tz=1,Rz=6,f5=1,gD=8,Cz=48,g5=4;var Ez=0;function A6(X,J,$,Y=U6.Normal){let G=0;if(X)G|=Tz;if(G|=J<<f5,$)G|=gD;return G|=Y<<g5,G}function m5(X){return(X&Tz)!==0}function Sz(X){let J=new Uint8Array(21),$=new DataView(J.buffer);return $.setUint32(0,X.len,!0),J[4]=X.ver,J[5]=X.ty,J[6]=X.flags,$.setUint16(7,X.channel,!0),$.setUint32(9,X.epoch,!0),$.setBigUint64(13,X.corr,!0),J}class I0 extends Error{code;constructor(X,J){super(X);this.code=J,this.name="DecodeError"}}function mD(X){let J=X.len>>>0,$=X.ver>>>0&255,Y=X.ty>>>0&255,G=X.flags>>>0&255,Q=X.channel>>>0&65535,z=X.epoch>>>0;if(BigInt.asUintN(64,X.corr),$!==2)throw new I0(`unsupported envelope version ${$}`,"unsupported_version");if(Y>_z)throw new I0(`unknown frame type byte ${Y}`,"unknown_frame_type");let Z=Y;if((G&Ez)!==0)throw new I0(`reserved flag bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((G&Rz)>>f5===3)throw new I0(`reserved priority bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(G&Cz)>>g5;if(W===3)throw new I0(`reserved admission class set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===U6.Sheddable&&Z!==u.Push&&Z!==u.StreamData)throw new I0(`SHEDDABLE admission class is illegal on ${u[Z]} in flags 0b${G.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(Q===0&&z!==0)throw new I0(`control channel carried nonzero epoch ${z}`,"nonzero_epoch_on_control_channel");if(Az(Z)&&J!==0)throw new I0(`pure-header frame ${u[Z]} declared non-zero body length ${J}`,"pure_header_frame_with_body")}function u5(X){if(X.length<5)throw new I0(`header shorter than frozen prefix: have ${X.length} bytes`,"too_short_for_prefix");let J=X[4];if(J!==2)throw new I0(`unsupported envelope version ${J}`,"unsupported_version");if(X.length<21)throw new I0(`header too short for version: have ${X.length} bytes, need 21`,"too_short_for_header");let $=new DataView(X.buffer,X.byteOffset,X.byteLength),Y=$.getUint32(0,!0),G=X[5];if(G>_z)throw new I0(`unknown frame type byte ${G}`,"unknown_frame_type");let Q=G,z=X[6];if((z&Ez)!==0)throw new I0(`reserved flag bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((z&Rz)>>f5===3)throw new I0(`reserved priority bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Z=(z&Cz)>>g5;if(Z===3)throw new I0(`reserved admission class set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Z===U6.Sheddable&&Q!==u.Push&&Q!==u.StreamData)throw new I0(`SHEDDABLE admission class is illegal on ${u[Q]} in flags 0b${z.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=$.getUint16(7,!0),B=$.getUint32(9,!0);if(W===0&&B!==0)throw new I0(`control channel carried nonzero epoch ${B}`,"nonzero_epoch_on_control_channel");if(Az(Q)&&Y!==0)throw new I0(`pure-header frame ${u[Q]} declared non-zero body length ${Y}`,"pure_header_frame_with_body");return{len:Y,ver:J,ty:Q,flags:z,channel:W,epoch:B,corr:$.getBigUint64(13,!0)}}function K6(X,J,$,Y,G,Q){return A8(2,X,J,$,Y,G,Q)}function A8(X,J,$,Y,G,Q,z){if(z.length>67108864)throw new I0(`frame body ${z.length} exceeds max 67108864`,"frame_body_too_large");let Z={len:z.length,ver:X,ty:J,flags:$,channel:Y,epoch:G,corr:Q};return mD(Z),{header:Z,body:z}}function Z8(X){if(X.header.len!==X.body.length)throw new I0(`frame header length ${X.header.len} does not match body length ${X.body.length}`,"frame_length_mismatch");let J=Sz(X.header),$=new Uint8Array(J.length+X.body.length);return $.set(J,0),$.set(X.body,J.length),$}class X9 extends Error{}class W8 extends Error{}class T8 extends Error{cause;constructor(X,J){super(X);this.cause=J}}class D9 extends Error{cause;constructor(X,J){super(X);this.cause=J}}function Iz(X){return Buffer.from(X.buffer,X.byteOffset,X.byteLength)}var bz=Symbol("subc.socket.writeBorrowed"),kz=Symbol("subc.socket.writeTrackedBorrowed");function B8(X,J,$){let Y=X[bz];return Y?Y.call(X,J,$):X.write(J,$)}function p5(X,J,$){let Y=X[kz];return Y?Y.call(X,J,$):X.writeTracked(J,$)}class a9{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor(X){this.sock=X,X.on("data",($)=>{this.chunks.push($),this.buffered+=$.length,this.tryServe()});let J=($)=>{if(!this.closedErr)this.closedErr=$;this.tryServe()};X.on("error",($)=>J($ instanceof Error?$:Error(String($)))),X.on("end",()=>J(new X9("subc closed the connection"))),X.on("close",()=>J(new X9("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect(X,J,$){return new Promise((Y,G)=>{let Q=uD.connect({host:X,port:J});Q.setNoDelay(!0);let z=setTimeout(()=>{Q.destroy(),G(new W8(`timed out connecting to ${X}:${J}`))},Math.max(0,$-Date.now()));Q.once("connect",()=>{clearTimeout(z),Y(new a9(Q))}),Q.once("error",(Z)=>{clearTimeout(z),G(Z)})})}async readFrame(X,J,$){let Y=await this.readExact(x2,X),G=Y[4];if(G!==f6)throw new I0(`unsupported envelope version ${G}`,"unsupported_version");let Q=await this.readExact(k2-x2,X),z=new Uint8Array(k2);z.set(Y),z.set(Q,x2);let Z=u5(z);if(Z.len>h5)throw new I0(`frame body ${Z.len} exceeds max ${h5}`,"frame_body_too_large");$?.();let W=typeof J==="number"?J:Date.now()+J.afterHeaderMs,B=Z.len===0?new Uint8Array(0):await this.readExact(Z.len,W);return{header:Z,body:B}}readExact(X,J){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if(X===0)return Promise.resolve(new Uint8Array(0));return new Promise(($,Y)=>{let G=null;if(Number.isFinite(J)){let Q=J-Date.now();if(Q<=0){Y(new W8(`timed out waiting for ${X} bytes`));return}G=setTimeout(()=>{this.waiter=null,Y(new W8(`timed out waiting for ${X} bytes`))},Q)}this.waiter={need:X,resolve:$,reject:Y,timer:G},this.tryServe()})}async write(X,J){await this.writeBuffer(Buffer.from(X),J)}writeTracked(X,J){return this.writeTrackedBuffer(Buffer.from(X),J)}async[bz](X,J){await this.writeBuffer(Iz(X),J)}[kz](X,J){return this.writeTrackedBuffer(Iz(X),J)}async writeBuffer(X,J){try{await this.writeTrackedBuffer(X,J).completed}catch($){if($ instanceof T8||$ instanceof D9)throw $.cause??$;throw $}}writeTrackedBuffer(X,J){if(this.closedErr)return{queued:!1,completed:Promise.reject(new T8("subc socket was closed before bytes could be queued",this.closedErr))};let $=!1,Y=!1,G=null,Q=new Promise((z,Z)=>{let W=(H)=>{if(Y)return;if(Y=!0,G)clearTimeout(G);H()},B=J-Date.now();if(B<=0){W(()=>Z(new T8("timed out before bytes could be queued to subc",new W8("timed out writing to subc"))));return}G=setTimeout(()=>{let H=new W8("timed out writing to subc");W(()=>Z($?new D9("timed out after bytes were handed to the subc socket",H):new T8("timed out before bytes could be queued to subc",H)))},B);try{this.sock.write(X,(H)=>{W(()=>{if(H)Z(new D9("subc socket reported a write error after bytes were handed to the socket",H instanceof Error?H:Error(String(H))));else z()})}),$=!0}catch(H){W(()=>Z(new T8("subc socket write threw before bytes could be queued",H instanceof Error?H:Error(String(H)))))}});return{queued:$,completed:Q}}close(){this.sock.destroy()}tryServe(){let X=this.waiter;if(!X)return;if(this.buffered>=X.need){let J=this.take(X.need);if(this.waiter=null,X.timer)clearTimeout(X.timer);X.resolve(J);return}if(this.closedErr){if(this.waiter=null,X.timer)clearTimeout(X.timer);X.reject(this.closedErr)}}take(X){let J=Buffer.allocUnsafe(X),$=0;while($<X){let Y=this.chunks[0],G=X-$;if(Y.length<=G)Y.copy(J,$),$+=Y.length,this.chunks.shift();else Y.copy(J,$,0,G),this.chunks[0]=Y.subarray(G),$+=G}return this.buffered-=X,J}}var vz=32;var w2=4096,yz="subc-server-v1",hz="subc-client-v1",dD="client";class T6 extends Error{}function l5(X,J,$,Y,G){let Q=pD("sha256",Buffer.from(X));return Q.update(Buffer.from(J,"utf8")),Q.update(Buffer.from($)),Q.update(Buffer.from(Y)),Q.update(Buffer.from(G)),new Uint8Array(Q.digest())}function xz(X,J){if(X.length!==J.length)return!1;return lD(Buffer.from(X),Buffer.from(J))}async function wz(X,J,$){let Y=Buffer.from(JSON.stringify(J),"utf8");if(Y.length>w2)throw new T6(`auth message too large: ${Y.length} > ${w2}`);let G=new Uint8Array(4);new DataView(G.buffer).setUint32(0,Y.length,!0),await B8(X,G,$),await B8(X,Y,$)}async function iD(X,J){let $=await X.readExact(4,J),Y=new DataView($.buffer,$.byteOffset,4).getUint32(0,!0);if(Y>w2)throw new T6(`auth message too large: ${Y} > ${w2}`);let G=Y===0?new Uint8Array(0):await X.readExact(Y,J);try{return JSON.parse(Buffer.from(G).toString("utf8"))}catch(Q){throw new T6(`auth message JSON decode failed: ${String(Q)}`)}}function c5(X,J){if(!Array.isArray(X))throw new T6(`auth field '${J}' must be a byte array`);for(let $ of X)if(typeof $!=="number"||!Number.isInteger($)||$<0||$>255)throw new T6(`auth field '${J}' has invalid byte ${String($)}`);return Uint8Array.from(X)}async function l4(X,J,$){let Y=new Uint8Array(cD(vz));await wz(X,{client_nonce:Array.from(Y),role:dD},$);let G=await iD(X,$),Q=c5(G.server_nonce,"server_nonce"),z=c5(G.daemon_id,"daemon_id"),Z=c5(G.server_proof,"server_proof"),W=l5(J.key,yz,Y,Q,z);if(!xz(W,Z))throw new T6("server proof mismatch — wrong key or impostor daemon");if(!xz(z,J.daemonId))throw new T6("daemon id mismatch — connection file points at a different daemon");let B=l5(J.key,hz,Y,Q,z);await wz(X,{client_auth:Array.from(B)},$)}import{promises as d5}from"node:fs";var fz=1,gz=32,mz=16;class G6 extends Error{}function uz(X,J){if(!Array.isArray(X))throw new G6(`connection file field '${J}' must be a JSON array of bytes`);for(let $ of X)if(typeof $!=="number"||!Number.isInteger($)||$<0||$>255)throw new G6(`connection file field '${J}' has invalid byte ${String($)}`);return Uint8Array.from(X)}function nD(X){if(X.schema!==fz)throw new G6(`unsupported connection file schema ${X.schema}; expected ${fz}`);if(X.endpoints.length===0)throw new G6("connection file must include at least one endpoint");if(X.key.length<gz)throw new G6(`connection file key is too short: ${X.key.length} bytes, need at least ${gz}`);if(X.daemonId.length!==mz)throw new G6(`connection file daemon_id must be ${mz} bytes, got ${X.daemonId.length}`)}async function sD(X){if(process.platform==="win32")return;let $=(await d5.stat(X)).mode&511;if(($&63)!==0)throw new G6(`connection file ${X} has insecure permissions 0o${$.toString(8)}; expected owner-only 0600`)}async function l1(X){await sD(X);let J=await d5.readFile(X,"utf8"),$;try{$=JSON.parse(J)}catch(Z){throw new G6(`connection file JSON read failed for ${X}: ${String(Z)}`)}let Y=$.wire_version;if(Y!==void 0&&Y!==f6)throw new G6(`connection file wire_version ${String(Y)} but this client speaks ${f6}; the client library must be upgraded`);let G=$.endpoints;if(!Array.isArray(G))throw new G6("connection file 'endpoints' must be an array");let Q=G.map((Z)=>{let W=Z;if(typeof W.host!=="string"||typeof W.port!=="number")throw new G6("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),z={schema:$.schema,endpoints:Q,key:uz($.key,"key"),daemonId:uz($.daemon_id,"daemon_id"),pid:$.pid,daemonVer:$.daemon_ver??""};return nD(z),z}var pz=new WeakMap,i5=new WeakMap;class n5 extends Error{methodFamily;code="reverse_request_capability_not_declared";constructor(X){super(`reverse-request capability ${JSON.stringify(X)} was not registered before route.open`);this.methodFamily=X,this.name="ReverseRequestRegistrationError"}}class F9{handlers=new Map;declaredFamilies=null;onRequest(X,J){if(!aD(X))throw TypeError(`reverse-request method family must be a capability identifier, got ${JSON.stringify(X)}`);if(typeof J!=="function")throw TypeError("reverse-request handler must be a function");if(this.declaredFamilies&&!this.declaredFamilies.has(X))throw new n5(X);this.handlers.set(X,J)}capabilities(){return[...this.handlers.keys()].sort()}handler(X){return this.handlers.get(X)}seal(){this.declaredFamilies??=new Set(this.handlers.keys())}}class v2{channel;epoch;constructor(X,J,$,Y){if(!Number.isInteger(X)||X<=0||X>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${X}`);if(!Number.isInteger(J)||J<=0||J>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${J}`);this.channel=X,this.epoch=J,Y.seal(),pz.set(this,$),i5.set(this,Y),Object.freeze(this)}onRequest(X,J){i5.get(this).onRequest(X,J)}static create(X,J,$,Y){return new v2(X,J,$,Y)}}function y2(X,J,$,Y=new F9){return v2.create(X,J,$,Y)}function cz(X,J){return i5.get(X)?.handler(J)}function aD(X){return/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(X)}class J9 extends Error{handle;code="stale_route_handle";constructor(X){super(`route handle (${X.channel}, ${X.epoch}) is not live on the current connection`);this.handle=X,this.name="StaleRouteHandleError"}}function d1(){return Object.freeze({})}function d4(X,J){return pz.get(X)===J}function h2(X,J){return X===J}var lz=oD("subc-client"),rD=1e4,i1=30000,tD=50,eD=2000,dz="request_deadline",s5="deadline_exceeded_no_drop_observed",XF=30000,JF=30000,iz=new Uint8Array(0),$F="management_surface",u2="SUBC_MODULE_ID",p2="SUBC_LAUNCH_NONCE",c2={baseMs:100,capMs:2000,maxAttempts:6};class Q6 extends Error{kind;code;cause;constructor(X,J,$,Y){super(J);this.kind=X,this.code=$,this.cause=Y,this.name="SubcCallError"}get detail(){return this.cause instanceof q0?this.cause.detail:void 0}}class q0 extends Error{code;detail;constructor(X,J,$){super(X);this.code=J,this.detail=$}}var nz=new WeakMap;function a5(X){if(X instanceof Uint8Array)return X;let J=X===null?"null":Array.isArray(X)?"array":typeof X;throw new q0(`binary request body must be a Uint8Array; got ${J}`,"binary_body_required")}class o9{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=d1();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor(X,J,$){this.sock=X,this.currentConn=J,this.opts=$,this.readLoop(X,this.generation)}get conn(){return this.currentConn}static async connect(X){let J=QF(X),$=await o9.openConnection(J);return new o9($.sock,$.conn,J)}async catalogList(X){let J=this.encode(X===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:X}),$=await this.controlRpc(J);return this.parseJson($).modules??[]}async resolveProvider(X){let J=await this.resolveProviders(X);if(J.length===0)throw new q0(`no catalog claimant for capability ${X}`,"capability_unprovided");if(J.length>1)throw new q0(`multiple catalog claimants for capability ${X}: ${J.join(", ")}`,"capability_ambiguous");return J[0]}async resolveProviders(X){if(!rz(X))throw new q0(`malformed capability identifier ${JSON.stringify(X)}`,"invalid_capability_identifier");return(await this.catalogList()).filter(($)=>$.capabilities?.provides.includes(X)??!1).map(($)=>$.module_id).sort()}async routeOpen(X,J,$={}){let Y=o5($),G=$.reverseRequests??new F9;G.seal();let Q=G.capabilities(),z=this.encode({op:"route.open",target:X,identity:J,...Y?{consumer_identity:Y}:{},...Q.length>0?{consumer_capabilities:Q}:{}}),Z=null,W=(H)=>{if(H.header.ty!==u.Response)return!0;let U=this.parseJson(H);if(typeof U.route_channel!=="number"||typeof U.route_epoch!=="number")throw new q0(`route.open returned no route handle: ${JSON.stringify(U)}`);return Z=this.installRoute(U.route_channel,U.route_epoch,G),!0},B=(H)=>{if(H.header.ty!==u.Response)return;try{let U=this.parseJson(H);if(typeof U.route_channel!=="number"||typeof U.route_epoch!=="number")return;let j=this.installRoute(U.route_channel,U.route_epoch);this.failHandle(j,new q0("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(z,W,B),!Z)throw new q0("route.open response was not installed");return Z}async request(X,J,$={}){this.assertLiveHandle(X);let Y=$.binary??!1,G=Y?a5(J):J instanceof Uint8Array?J:this.encode(J),Q=$.priority??e0.Interactive,z=$.admissionClass??U6.Normal,Z=await this.send(X,G,Q,z,$.timeoutMs,$.onProgress,void 0,void 0,Y,$.signal);return this.decodeReply(Z)}async call(X,J,$,Y={}){if(Y.binary)throw new q0("call() builds a JSON body and cannot send a binary request; use callBinary(moduleId, body, opts) with a Uint8Array","binary_call_requires_call_binary");let G=$===void 0?{method:J}:{method:J,params:$};return await this.managedCall(X,G,Y)}async callBinary(X,J,$={}){let Y=a5(J);return this.managedCall(X,Y,{...$,binary:!0})}async managedCall(X,J,$){let Y=!1;for(;;){let G=await this.cachedRouteHandle(X,$);try{return await this.managedRequest(G,J,$)}catch(Q){if(!(Q instanceof Q6))throw this.terminalCallError("managed call failed",Q);let z=l2(Q.cause instanceof q0?nz.get(Q.cause)??0:0,Q.code);if(z&&!Y&&!this.closeStarted){Y=!0,this.evictRouteHandle(G);continue}if(z&&Y)this.evictRouteHandle(G);if(Q.code==="route_closed")throw this.evictRouteHandle(G),Q;if(Q.kind==="not_sent"){if(!this.closedErr)throw Q;try{await this.reconnectAfterDrop(Q)}catch(Z){throw this.notSentRecoveryError("managed call was not sent",Z)}continue}if(Q.kind==="outcome_unknown"&&Q.code!==s5){if(this.closedErr)this.scheduleReconnectAfterDrop(Q)}else if(Q.kind==="outcome_unknown"&&Q.code===s5)this.probeLivenessAfterDeadline();throw Q}}}subscribe(X,J,$,Y={}){this.assertLiveHandle(X);let G=J instanceof Uint8Array?J:this.encode(J),Q=Y.priority??e0.Interactive,z=Y.admissionClass??U6.Normal,Z=this.allocateCorr(),W=f2(X,Z),B=null,H=null,U=new Promise((K,L)=>{if(this.closedErr){L(this.closedErr);return}H=K,B={handle:X,resolve:()=>K(),reject:L,onProgress:$,timer:null,subscription:!0},this.pending.set(W,B);let F=K6(u.Request,A6(!1,Q,!1,z),X.channel,X.epoch,Z,G);B8(this.sock,Z8(F),Date.now()+i1).catch((O)=>{let _=this.pending.get(W);if(_)this.rejectPending(W,_,O instanceof Error?O:new q0(String(O)))})}),j=!1;return{unsubscribe:()=>{if(j)return;if(j=!0,B&&H)this.settle(W,B,H);if(this.isLiveHandle(X))this.cancel(X,Z,Q)},closed:U}}attachCancelSignal(X,J,$,Y,G){if(!$)return;let Q=()=>{if(!this.pending.has(J))return;try{this.cancel($,Y,G)}catch{}};if(X.aborted){Q();return}X.addEventListener("abort",Q,{once:!0});let z=this.pending.get(J);if(z){let Z=z.onSettle;z.onSettle=()=>{Z?.(),X.removeEventListener("abort",Q)}}}cancel(X,J,$=e0.Interactive){this.assertLiveHandle(X);let Y=K6(u.Cancel,A6(!1,$,!1),X.channel,X.epoch,J,iz);B8(this.sock,Z8(Y),Date.now()+i1).catch(()=>{return})}async routePoll(X,J){this.assertLiveHandle(X);let $=this.encode({op:"route.poll",route_channel:X.channel,route_epoch:X.epoch,kind:J}),Y=await this.controlRpc($,(G)=>{if(G.header.ty!==u.Response)return!0;let Q=this.parseJson(G);return Q.route_channel===X.channel&&Q.route_epoch===X.epoch});return this.parseJson(Y)}async closeRoute(X,J={}){this.assertLiveHandle(X);for(let[$,Y]of this.routes)if(Y.handle&&h2(Y.handle,X))Y.closed=!0,Y.handle=null,this.routes.delete($);if(J.drain)await this.drainUnaryOnHandle(X);if(this.failHandle(X,new q0("route closed by closeRoute","route_closed")),this.liveRoutes.get(X.channel)===X)this.liveRoutes.delete(X.channel);this.sendRouteGoodbye(X)}async closeManagedRoute(X,J,$={}){let Y=sz(X,J,o5($),($.reverseRequests??new F9).capabilities()),G=this.routes.get(Y);if(!G)return;G.closed=!0,this.routes.delete(Y);let Q=G.handle;if(G.handle=null,Q)await this.closeRoute(Q,$)}async closeRouteChannel(X,J={}){await this.closeRoute(X,J)}close(){this.closeStarted=!0,this.fail(new q0("client closed")),this.sock.close()}drainUnaryOnHandle(X){let J=[];for(let $ of this.pending.values())if($.handle===X&&!$.subscription)J.push(new Promise((Y)=>{let G=$.onSettle;$.onSettle=()=>{G?.(),Y()}}));return Promise.all(J).then(()=>{return})}sendRouteGoodbye(X,J=!1){if(this.assertLiveConnection(X),this.closedErr){if(J)this.closeConnectionAfterCleanupFailure();return}let $=K6(u.Goodbye,A6(!1,e0.Interactive,!1),X.channel,X.epoch,0n,iz),Y=p5(this.sock,Z8($),Date.now()+i1);if(!Y.queued&&J)this.closeConnectionAfterCleanupFailure();Y.completed.catch(()=>{if(J&&!Y.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection(X){let J=await l1(X.connectionFile),$=Date.now()+(X.handshakeTimeoutMs??rD),Y=J.endpoints[0],G=await a9.connect(Y.host,Y.port,$);try{await l4(G,J,$)}catch(Q){throw G.close(),Q}return{sock:G,conn:J}}async controlRpc(X,J,$){return this.send(null,X,e0.Interactive,U6.Normal,void 0,void 0,J,$)}send(X,J,$,Y,G,Q,z,Z,W=!1,B){if(X)this.assertLiveHandle(X);if(this.closedErr)return Promise.reject(this.closedErr);let H;try{H=this.allocateCorr()}catch(L){return Promise.reject(L)}let U=f2(X,H),j=X?.channel??0,q=X?.epoch??0,K=K6(u.Request,A6(W,$,!1,Y),j,q,H,J);return new Promise((L,F)=>{let O=G??i1,_={handle:X,resolve:L,reject:F,onProgress:Q,timer:null,acceptFrame:z,onLateResponse:Z};if(_.timer=setTimeout(()=>this.arbitrateTimeout(U,_,j,H,O),O),this.pending.set(U,_),B)this.attachCancelSignal(B,U,X,H,$);B8(this.sock,Z8(K),Date.now()+O).catch((C)=>{let N=this.pending.get(U);if(N)this.rejectPending(U,N,C instanceof Error?C:new q0(String(C)))})})}arbitrateTimeout(X,J,$,Y,G){let Q=()=>{if(J.onLateResponse)this.lateResponses.set(X,J.onLateResponse);this.rejectPending(X,J,new q0(this.timeoutMessage($,Y,G),dz))},z=Date.now()+this.opts.timeoutArbitrationGraceMs,Z=()=>{if(this.pending.get(X)!==J)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<z){setImmediate(Z);return}Q()};setImmediate(Z)}async managedRequest(X,J,$){let Y=$.binary??!1,G=Y?a5(J):J instanceof Uint8Array?J:this.encode(J),Q=$.priority??e0.Interactive,z=$.admissionClass??U6.Normal;try{let Z=await this.sendManaged(X,G,Q,z,$.timeoutMs,$.onProgress,Y,$.signal);return this.decodeReply(Z)}catch(Z){if(Z instanceof Q6)throw Z;throw this.terminalCallError("managed call failed",Z)}}sendManaged(X,J,$,Y,G,Q,z=!1,Z){try{this.assertLiveHandle(X)}catch(q){return Promise.reject(this.notSentCallError("request used a stale route handle",q))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let W;try{W=this.allocateCorr()}catch(q){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",q))}let B=f2(X,W),H=K6(u.Request,A6(z,$,!1,Y),X.channel,X.epoch,W,J),U=!1,j=(q)=>{if(!U)return this.notSentCallError("request bytes were not queued to the subc socket",q);if(q instanceof q0&&q.code===dz)return new Q6("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${i4(q)}`,s5,q);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",q)};return new Promise((q,K)=>{let L=G??i1,F={handle:X,resolve:q,reject:K,onProgress:Q,timer:null,classifyFailure:j};if(F.timer=setTimeout(()=>this.arbitrateTimeout(B,F,X.channel,W,L),L),this.pending.set(B,F),Z)this.attachCancelSignal(Z,B,X,W,$);let O=p5(this.sock,Z8(H),Date.now()+L);U=O.queued,O.completed.catch((_)=>{let C=this.pending.get(B);if(C)this.rejectPending(B,C,_ instanceof Error?_:new q0(String(_)))})})}async cachedRouteHandle(X,J){let $=J.identity??this.opts.identity;if(!$)throw new Q6("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let Y={kind:J.targetKind??this.opts.targetKind,module_id:X},G=o5(J),Q=J.reverseRequests??new F9;Q.seal();let z=sz(Y,$,G,Q.capabilities()),Z=this.routes.get(z);if(!Z)Z={key:z,moduleId:X,target:Y,identity:$,consumerIdentity:G,reverseRequests:Q,handle:null,opening:null},this.routes.set(z,Z);if(Z.handle&&this.isLiveHandle(Z.handle))return Z.handle;if(!Z.opening)Z.opening=this.openCachedRoute(Z).finally(()=>{Z.opening=null});return Z.opening}async openCachedRoute(X){let J=Date.now()+this.opts.routeOpenRetryDeadlineMs,$=this.opts.reconnectBackoff.baseMs,Y=0;for(;;){if(X.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(G){throw this.notSentRecoveryError("route.open could not run because reconnect failed",G)}if(X.handle&&this.isLiveHandle(X.handle))return X.handle;try{let G=await this.routeOpen(X.target,X.identity,{consumerIdentity:X.consumerIdentity??null,reverseRequests:X.reverseRequests});if(X.closed)throw this.liveRoutes.delete(G.channel),this.sendRouteGoodbye(G),this.routeClosedDuringOpen();return X.handle=G,G}catch(G){if(G instanceof Q6&&G.code==="route_closed")throw G;if(!this.closeStarted&&g2(G)){try{await this.reconnectAfterDrop(G)}catch(Q){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",Q)}continue}if(!this.closeStarted&&G instanceof q0&&GF(G.code)){if(Y+=1,Date.now()<J){await this.opts.sleep($),$=Math.min($*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${X.moduleId}: ${G.code} (retry deadline exhausted after ${Y} attempts)`,G)}throw this.terminalCallError(`route.open failed for module ${X.moduleId}`,G)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let X of this.pending.values())if(X.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let X=this.sock,J=this.generation,$;try{$=this.allocateCorr()}catch{return}let Y=Date.now(),G=K6(u.Ping,A6(!1,e0.Interactive,!1,U6.Normal),0,0,$,new Uint8Array),Q=(async()=>{if(await B8(X,Z8(G),Y+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==X||this.generation!==J||this.closeStarted)return;if(this.lastInboundAtMs>=Y)return;if(this.hasControlPending())return;this.fail(new X9(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),X.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=Q}async ensureConnectedForManaged(){if(this.closeStarted)throw new q0("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop(X){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop(X).catch(()=>{})}reconnectAfterDrop(X){if(this.closeStarted)return Promise.reject(new q0("client closed"));if(this.reconnecting)return this.reconnecting;let J=this.reconnectWithRetry(X).finally(()=>{if(this.reconnecting===J)this.reconnecting=null});return this.reconnecting=J,J}async reconnectWithRetry(X){let J=0,$=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new q0("client closed");J+=1;try{let Y=await o9.openConnection(this.opts);if(this.closeStarted)throw Y.sock.close(),new q0("client closed");this.replaceConnection(Y),await this.reopenCachedRoutes();return}catch(Y){if(!g2(Y)||J>=this.opts.reconnectBackoff.maxAttempts){if(Y instanceof T6&&J>1)throw new T6(`reconnect gave up after ${J} attempts: ${Y.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw Y}await this.opts.sleep($),$=Math.min($*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection(X){this.fail(new q0("subc connection replaced")),this.sock.close(),this.sock=X.sock,this.currentConn=X.conn,this.closedErr=null,this.generation+=1,this.connectionToken=d1(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop(X.sock,this.generation)}async reopenCachedRoutes(){let X=[...this.routes.keys()];for(let J of X){let $=this.routes.get(J);if($)$.handle=null}for(let J of X){let $=this.routes.get(J);if(!$||$.closed)continue;try{let Y=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null,reverseRequests:$.reverseRequests});if($.closed){this.liveRoutes.delete(Y.channel),this.sendRouteGoodbye(Y);continue}$.handle=Y}catch(Y){if(YF(Y)){this.routes.delete(J);continue}throw Y}}}timeoutMessage(X,J,$){let Y=this.sock.localPort();return`request on ${Y===null?"channel":`local_port=${Y} channel`} ${X} corr ${J} timed out after ${$}ms`}routeClosedDuringOpen(){return new Q6("not_sent","route was closed before route.open completed","route_closed")}async readLoop(X,J){try{for(;;){this.readerActive=!1;let $=await X.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:JF},()=>{this.readerActive=!0});try{if(this.sock===X&&this.generation===J)this.dispatch($)}finally{this.readerActive=!1}}}catch($){if(this.sock===X&&this.generation===J)this.fail($ instanceof Error?$:new q0(String($)))}}dispatch(X){if(this.lastInboundAtMs=Date.now(),X.header.channel===0&&X.header.ty===u.Push){let Q=this.opts.onControlPush;if(Q){let z=null;try{let Z=this.parseJson(X);if(Z&&typeof Z.op==="string")z={op:Z.op,body:Z}}catch{}if(z)try{Q(z)}catch{}}return}let J=null;if(X.header.channel!==0){if(J=this.liveRoutes.get(X.header.channel)??null,!J||J.epoch!==X.header.epoch){this.ingressEpochDropCount+=1;return}}if(X.header.ty===u.Request&&J){this.dispatchReverseRequest(X,J);return}let $=f2(J,X.header.corr),Y=this.pending.get($);if(Y){if(Y.acceptFrame&&!Y.acceptFrame(X))return;switch(X.header.ty){case u.Push:case u.StreamData:try{Y.onProgress?.(X.body)}catch{}return;case u.Response:case u.StreamEnd:this.settle($,Y,()=>Y.resolve(X));return;case u.Error:this.settle($,Y,()=>Y.reject(this.errorFromFrame(X)));return;default:return}}let G=this.lateResponses.get($);if(G&&(X.header.ty===u.Response||X.header.ty===u.Error)){this.lateResponses.delete($),G(X);return}if(X.header.ty===u.Goodbye&&J){if(this.failHandle(J,new q0("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(J.channel)===J)this.liveRoutes.delete(J.channel);this.evictRouteHandle(J);return}if(X.header.ty===u.Response||X.header.ty===u.Error||X.header.ty===u.StreamEnd)lz("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",X.header.ty,X.header.channel,X.header.epoch,X.header.corr,this.sock.localPort()??"?")}settle(X,J,$){if(this.pending.get(X)!==J)return!1;if(this.pending.delete(X),J.timer)clearTimeout(J.timer);return $(),J.onSettle?.(),!0}rejectPending(X,J,$){this.settle(X,J,()=>J.reject(J.classifyFailure?.($)??$))}dispatchReverseRequest(X,J){let $=zF(X.body),Y=$?.split("/",1)[0],G=Y?cz(J,Y):void 0,Q=this.sock,z=this.generation;(async()=>{if(!G||!$){await this.sendReverseError(X,J,"reverse_request_unhandled",Y?`no reverse-request handler is registered for ${Y}`:"reverse request has no valid method",Q,z);return}let W;try{if(W=await G(X.body,{corr:X.header.corr,method:$}),!(W instanceof Uint8Array))throw TypeError("reverse-request handler must return a Uint8Array")}catch(B){await this.sendReverseError(X,J,"reverse_request_unhandled",B instanceof Error?B.message:String(B),Q,z);return}await this.sendReverseReply(X,J,u.Response,W,Q,z)})().catch((W)=>{if(this.sock===Q&&this.generation===z&&!this.closeStarted)lz("failed to answer reverse request: %s",i4(W))})}async sendReverseError(X,J,$,Y,G,Q){await this.sendReverseReply(X,J,u.Error,this.encode({code:$,message:Y}),G,Q)}async sendReverseReply(X,J,$,Y,G,Q){if(this.sock!==G||this.generation!==Q||!this.isLiveHandle(J)||this.closeStarted||this.closedErr)return;let z=K6($,A6(!1,e0.Interactive,!1),J.channel,J.epoch,X.header.corr,Y);await B8(G,Z8(z),Date.now()+i1)}errorFromFrame(X){try{let J=JSON.parse(Buffer.from(X.body).toString("utf8")),$=new q0(J.message??"subc error",J.code,J.detail);return nz.set($,X.header.flags),$}catch{return new q0(Buffer.from(X.body).toString("utf8")||"subc error")}}evictRouteHandle(X){for(let J of this.routes.values())if(J.handle&&h2(J.handle,X))J.handle=null}failHandle(X,J){for(let[$,Y]of this.pending)if(Y.handle&&h2(Y.handle,X))this.rejectPending($,Y,J)}fail(X){if(!this.closedErr)this.closedErr=X;for(let[J,$]of this.pending)this.rejectPending(J,$,X)}notSentCallError(X,J){return new Q6("not_sent",`${X}${i4(J)}`,m2(J),J)}outcomeUnknownCallError(X,J){return new Q6("outcome_unknown",`${X}${i4(J)}`,m2(J),J)}terminalCallError(X,J){if(J instanceof Q6)return J;return new Q6("terminal",`${X}${i4(J)}`,m2(J),J)}notSentRecoveryError(X,J){if(J instanceof Q6)return J;if(g2(J))return this.notSentCallError(X,J);return this.terminalCallError(X,J)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute(X,J,$=new F9){let Y=y2(X,J,this.connectionToken,$);return this.liveRoutes.set(X,Y),Y}isLiveHandle(X){return d4(X,this.connectionToken)&&this.liveRoutes.get(X.channel)===X}assertLiveConnection(X){if(!d4(X,this.connectionToken))throw new J9(X)}assertLiveHandle(X){if(!this.isLiveHandle(X))throw new J9(X)}allocateCorr(){let X=0xffffffffffffffffn;if(this.nextCorr>X){let $=new q0("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($),$}let J=this.nextCorr;return this.nextCorr+=1n,J}closeConnectionAfterCleanupFailure(){let X=new q0("late route cleanup could not be queued","late_route_cleanup_failed");this.fail(X),this.sock.close(),this.scheduleReconnectAfterDrop(X)}encode(X){return Buffer.from(JSON.stringify(X),"utf8")}decodeReply(X){return m5(X.header.flags)?X.body:this.parseJson(X)}parseJson(X){let J=X.body;return JSON.parse(Buffer.from(J.buffer,J.byteOffset,J.byteLength).toString("utf8"))}}function g2(X){if(X instanceof X9||X instanceof W8)return!0;if(X instanceof T8||X instanceof D9)return!0;if(X instanceof Q6)return X.kind==="not_sent"||X.kind==="outcome_unknown";if(X instanceof T6)return!0;if(X instanceof q0||X instanceof G6)return!1;let J=m2(X);return J==="ECONNREFUSED"||J==="ECONNRESET"||J==="EPIPE"||J==="ETIMEDOUT"||J==="ENOENT"}function YF(X){return X instanceof q0&&typeof X.code==="string"}function GF(X){if(X==="capability_forbidden")return!1;return X==="module_reloading"||X==="module_warming"||X==="target_unavailable"||X==="module_timeout"}var az="unknown_channel",oz="stale_route_epoch";function l2(X,J){return J===az||J===oz}function QF(X){return{connectionFile:X.connectionFile,handshakeTimeoutMs:X.handshakeTimeoutMs,identity:X.identity,targetKind:X.targetKind??$F,reconnectBackoff:X.reconnectBackoff??c2,sleep:X.sleep??((J)=>new Promise(($)=>setTimeout($,J))),routeOpenRetryDeadlineMs:X.routeOpenRetryDeadlineMs??XF,timeoutArbitrationGraceMs:X.timeoutArbitrationGraceMs??tD,livenessProbeWindowMs:X.livenessProbeWindowMs??eD,onControlPush:X.onControlPush}}function rz(X){if(/\s/u.test(X))return!1;let J=X.indexOf("/v");if(J<=0||X.indexOf("/v",J+1)!==-1)return!1;let $=X.slice(0,J),Y=X.slice(J+2);if(new TextEncoder().encode($).byteLength>64||Y.length===0)return!1;if(!/^[a-z][a-z0-9-]*[a-z0-9]$/u.test($)&&!/^[a-z]$/u.test($))return!1;if($.includes("--"))return!1;if(!/^\d+$/u.test(Y)||Y.length>1&&Y.startsWith("0"))return!1;let G=Number(Y);return Number.isSafeInteger(G)&&G>=1&&G<=4294967295}function sz(X,J,$,Y){let G=$?`${$.module_id}\x00${$.launch_nonce}`:"",Q=[...Y].sort().join("\x00");return`${X.kind}\x00${X.module_id}\x00${J.project_root}\x00${J.harness}\x00${J.session}\x00${G}\x00${Q}`}function o5(X={}){if(X.consumerIdentity!==void 0)return X.consumerIdentity??void 0;let J=process.env[u2],$=process.env[p2];if(!J||!$)return;return{module_id:J,launch_nonce:$}}function m2(X){if(typeof X==="object"&&X!==null&&"code"in X){let J=X.code;if(typeof J==="string")return J}return}function i4(X){if(X===void 0)return"";return`: ${X instanceof Error?X.message:String(X)}`}function f2(X,J){return X?`${X.channel}:${X.epoch}:${J}`:`0:0:${J}`}function zF(X){try{let J=JSON.parse(Buffer.from(X).toString("utf8"));return typeof J.method==="string"&&J.method.length>0?J.method:void 0}catch{return}}import{Buffer as $J}from"node:buffer";var ZF=1e4,WF=30000,ez=30000,BF=250,r5=64,XJ="health.check",XZ=1n,HF=/^[0-9a-f]{32}$/;function JJ(X){let J=X.machine_id;return typeof J==="string"&&HF.test(J)?J:void 0}class i2{available;waiters=[];constructor(X){if(!Number.isInteger(X)||X<=0)throw new w0("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=X}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise((X)=>{this.waiters.push(X)}),this.releaseOnce()}releaseOnce(){let X=!1;return()=>{if(X)return;X=!0;let J=this.waiters.shift();if(J)J();else this.available+=1}}}class w0 extends Error{code;kind;detail;constructor(X,J,$="terminal",Y){super(X);this.code=J,this.kind=$,this.detail=Y}}class n4{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=d1();nextCorr=1n;ingressEpochDropCount=0;requestGate=new i2(r5);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;machineId;constructor(X,J,$,Y){this.sock=X,this.currentConn=J,this.opts=$,this.storage=Y.storage,this.machineId=JJ(Y),this.closed=new Promise((G)=>{this.resolveClosed=G}),this.readLoop(X,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request(X,J,$={}){this.assertLiveHandle(X);let Y=this.allocateCorr(),G=d2(X,Y),Q=$.timeoutMs??ez,z=K6(u.Request,A6(!1,$.priority??e0.Interactive,!1,$.admissionClass??U6.Normal),X.channel,X.epoch,Y,J);return await new Promise((Z,W)=>{let B=setTimeout(()=>{if(this.pending.delete(G))W(new w0("reverse request timed out","request_timeout"))},Q);this.pending.set(G,{resolve:(H)=>Z(H.body),reject:W,timer:B}),this.sendOn(this.sock,this.generation,z).catch((H)=>{let U=this.pending.get(G);if(!U)return;this.pending.delete(G),clearTimeout(U.timer),W(H instanceof Error?H:new w0(String(H)))})})}async push(X,J,$={}){this.assertLiveHandle(X),await this.sendOn(this.sock,this.generation,K6(u.Push,A6(!1,$.priority??e0.Interactive,!1,$.admissionClass??U6.Normal),X.channel,X.epoch,0n,J))}cancel(X,J){this.assertLiveHandle(X),this.sendOn(this.sock,this.generation,K6(u.Cancel,R8(),X.channel,X.epoch,J,new Uint8Array(0))).catch(()=>{return})}closeRoute(X){this.assertLiveHandle(X),this.liveRoutes.delete(X.channel),this.abortHandle(X),this.sendOn(this.sock,this.generation,K6(u.Goodbye,R8(),X.channel,X.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect(X){if(X.manifest.protocol_ver!==f6)throw new w0(`manifest protocol_ver ${X.manifest.protocol_ver} does not match client protocol ${f6}`,"invalid_manifest");let J=UF(X),$=await n4.openConnection(J);return new n4($.sock,$.conn,J,$.ack)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let X=this.sock;try{await e5(X,K6(u.Goodbye,R8(),0,0,0n,new Uint8Array(0)))}catch{}finally{X.close(),this.finishClosed()}}await this.closed}static async openConnection(X,J){let $=await l1(X.connectionFile),Y=Date.now()+(X.handshakeTimeoutMs??ZF),G=$.endpoints[0],Q=await a9.connect(G.host,G.port,Y);try{J?.(Q),await l4(Q,$,Y),await e5(Q,jF(X));let z=await DF(Q,Y);return{sock:Q,conn:$,ack:z}}catch(z){throw Q.close(),z}}async readLoop(X,J){try{for(;;){let $=await X.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:WF});if(!await this.dispatch($,X,J)){if(this.sock===X&&this.generation===J)this.closeStarted=!0;break}}}catch($){if(this.sock===X&&this.generation===J&&!this.closeStarted){this.handleUnexpectedDrop(X,J,$ instanceof Error?$:new w0(String($)));return}}finally{if(this.sock===X&&this.generation===J){if(X.close(),this.closeStarted)this.finishClosed()}}}async dispatch(X,J,$){let Y=null;if(X.header.channel!==0){if(Y=this.liveRoutes.get(X.header.channel)??null,!Y||Y.epoch!==X.header.epoch)return this.ingressEpochDropCount+=1,!0}if(Y){let G=d2(Y,X.header.corr),Q=this.pending.get(G);if(Q){if(X.header.ty===u.Push||X.header.ty===u.StreamData)return!0;if(X.header.ty===u.Response||X.header.ty===u.StreamEnd)return this.pending.delete(G),clearTimeout(Q.timer),Q.resolve(X),!0;if(X.header.ty===u.Error)return this.pending.delete(G),clearTimeout(Q.timer),Q.reject(VF(X)),!0}}switch(X.header.ty){case u.Ping:if(X.header.channel===0)await this.sendOn(J,$,A8(X.header.ver,u.Pong,X.header.flags,0,0,X.header.corr,new Uint8Array(0)));return!0;case u.Goodbye:if(!Y)return!1;return this.liveRoutes.delete(Y.channel),this.abortHandle(Y),await this.reportRouteGone(Y),!0;case u.Cancel:if(Y)this.inflight.get(d2(Y,X.header.corr))?.abort();return!0;case u.Request:if(X.header.channel===0)await this.handleControlRequest(X,J,$);else if(Y)this.handleDataRequest(X,Y,J,$).catch((G)=>{if(!this.closeStarted&&this.sock===J&&this.generation===$)console.warn("SubcProvider handler failed after its request was dispatched",G)});return!0;default:return!0}}async reportRouteBound(X){if(!this.opts.onBound)return;try{await this.opts.onBound(X)}catch(J){console.warn("SubcProvider bound callback failed",J)}}async reportRouteGone(X){if(!this.opts.onRouteGone)return;try{await this.opts.onRouteGone(X)}catch(J){console.warn("SubcProvider route-gone callback failed",J)}}abortHandle(X){let J=`${X.channel}:${X.epoch}:`;for(let[$,Y]of this.inflight)if($.startsWith(J))Y.abort();for(let[$,Y]of this.pending){if(!$.startsWith(J))continue;this.pending.delete($),clearTimeout(Y.timer),Y.reject(new J9(X))}}abortGeneration(X){this.abortAllInflight();for(let[J,$]of this.pending)this.pending.delete(J),clearTimeout($.timer),$.reject(new w0("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let X of this.inflight.values())X.abort()}async handleControlRequest(X,J,$){let Y=s2(X.body);if(Y.op===XJ){this.handleHealthRequest(X,J,$).catch((U)=>{if(!this.closeStarted&&this.sock===J&&this.generation===$)console.warn("SubcProvider health handler failed after its request was dispatched",U)});return}if(Y.op!=="route.bind")throw new w0(`unsupported module control request ${Y.op??"<missing op>"}`);let G=tz(Y.route_channel,"route_channel"),Q=tz(Y.epoch,"epoch"),z=this.liveRoutes.get(G);if(z){if(Q<=z.epoch){await this.sendError(X,"route_rejected",`route.bind epoch ${Q} does not supersede installed epoch ${z.epoch} on channel ${G}`,R8(),J,$);return}this.liveRoutes.delete(z.channel),this.abortHandle(z),await this.reportRouteGone(z)}let Z=y2(G,Q,this.connectionToken),W={handle:Z,target:Y.target,identity:Y.identity,principal:Y.principal,consumer_capabilities:Y.consumer_capabilities},B;try{B=await this.opts.onBind?.(W)}catch(U){try{await this.sendError(X,"route_rejected",U instanceof Error?U.message:String(U),R8(),J,$)}finally{await this.reportRouteGone(Z)}return}let H=FF(B);if(H){try{await this.sendError(X,H.code,H.message,R8(),J,$)}finally{await this.reportRouteGone(Z)}return}try{await this.sendOn(J,$,A8(X.header.ver,u.Response,R8(),0,0,X.header.corr,n2({op:"route.bind"})))}catch(U){throw await this.reportRouteGone(Z),U}if(this.sock!==J||this.generation!==$||this.closeStarted||this.closedErr){await this.reportRouteGone(Z);return}this.liveRoutes.set(Z.channel,Z),await this.reportRouteBound(Z)}async handleDataRequest(X,J,$,Y){let{corr:G,ver:Q}=X.header,z=d2(J,G),Z=new AbortController;this.inflight.set(z,Z);let W={handle:J,signal:Z.signal,currentEpoch:()=>this.connectionEpoch,emit:async(U,j={})=>{if(this.assertLiveHandle(J),Z.signal.aborted)return;await this.sendOn($,Y,A8(Q,u.StreamData,A6(!1,j.priority??e0.Interactive,!1,j.admissionClass??U6.Normal),J.channel,J.epoch,G,U))}},B=await(this.requestGate??new i2(r5)).acquire(),H=A6(!1,e0.Interactive,!1);try{if(Z.signal.aborted){await this.sendError(X,"cancelled","request cancelled",H,$,Y);return}let U=await this.opts.handler(J,X.body,W);if(Z.signal.aborted){await this.sendError(X,"cancelled","request cancelled",H,$,Y);return}if(this.assertLiveHandle(J),U===void 0)await this.sendOn($,Y,A8(Q,u.StreamEnd,H,J.channel,J.epoch,G,new Uint8Array(0)));else if(U instanceof Uint8Array)await this.sendOn($,Y,A8(Q,u.Response,H,J.channel,J.epoch,G,U));else throw new w0("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(U){if(U instanceof J9)return;if(Z.signal.aborted){await this.sendError(X,"cancelled","request cancelled",H,$,Y);return}await this.sendError(X,U instanceof w0&&U.code?U.code:"handler_error",U instanceof Error?U.message:String(U),H,$,Y)}finally{if(B(),this.inflight.get(z)===Z)this.inflight.delete(z)}}async handleHealthRequest(X,J,$){let{corr:Y,ver:G}=X.header,Q=`control:${$}:${Y}`,z=new AbortController;this.inflight.set(Q,z);let Z=await(this.requestGate??new i2(r5)).acquire();try{if(z.signal.aborted)return;let W=await this.opts.health();await this.sendOn(J,$,A8(G,u.Response,R8(),0,0,Y,n2({op:XJ,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError(X,W instanceof w0&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),R8(),J,$)}finally{if(Z(),this.inflight.get(Q)===z)this.inflight.delete(Q)}}async sendError(X,J,$,Y,G,Q){if(X.header.channel!==0){let z=this.liveRoutes.get(X.header.channel);if(!z||z.epoch!==X.header.epoch||!this.isLiveHandle(z))return}await this.sendOn(G,Q,A8(X.header.ver,u.Error,Y,X.header.channel,X.header.epoch,X.header.corr,n2({code:J,message:$})))}async sendOn(X,J,$){if(this.sock!==X||this.generation!==J||this.closeStarted||this.closedErr)return;await e5(X,$)}handleUnexpectedDrop(X,J,$){if(this.closeStarted||this.sock!==X||this.generation!==J)return;if(!this.opts.reconnectOnDrop){this.failFatal($);return}this.cancelRestoredDebounce(),this.abortGeneration(J),this.generation+=1,X.close(),this.scheduleReconnectAfterDrop($,this.generation,X)}scheduleReconnectAfterDrop(X,J,$){if(this.closeStarted)return;let Y=this.reconnecting;if(Y){if(!this.shouldSupersedeReconnect(Y,J,$))return;Y.superseded=!0,Y.socket?.close()}let G={generation:J,socket:null,socketDied:!1,superseded:!1};this.reconnecting=G,this.enqueueConnectionState({state:"down",cause:X}),this.reconnectWithRetry(G).catch((Q)=>{if(this.isCurrentReconnect(G)&&!this.closeStarted)this.failFatal(Q instanceof Error?Q:new w0(String(Q)))}).finally(()=>{if(this.isCurrentReconnect(G))this.reconnecting=null})}async reconnectWithRetry(X){let J=0,$=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect(X))return;if(this.closeStarted)throw new w0("provider closed");X.socket=null,X.socketDied=!1,J+=1,this.enqueueReconnectState(X,J);try{let Y=await n4.openConnection(this.opts,(Q)=>{if(!this.isCurrentReconnect(X)){Q.close();return}X.socket=Q});if(!this.isCurrentReconnect(X)||this.closeStarted){if(Y.sock.close(),this.closeStarted)throw new w0("provider closed");return}let G=this.replaceConnection(Y,X.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new w0("reconnect state must clear before restored","reconnect_state");this.scheduleRestored(X.generation,G);return}catch(Y){if(!this.isCurrentReconnect(X))return;if(X.socket)X.socketDied=!0;if(this.closeStarted)throw Y;if(!qF(Y))throw Y;await this.opts.sleep($),$=Math.min($*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect(X){return!X.superseded&&this.reconnecting===X&&this.generation===X.generation}shouldSupersedeReconnect(X,J,$){return X.generation<J||X.socketDied||X.socket===$}enqueueReconnectState(X,J){if(!this.isCurrentReconnect(X))return;this.enqueueConnectionState({state:"reconnecting",attempt:J},X.generation,X)}replaceConnection(X,J){return this.sock.close(),this.sock=X.sock,this.currentConn=X.conn,this.storage=X.ack.storage,this.machineId=JJ(X.ack),this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=d1(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop(X.sock,J),this.connectionEpoch}scheduleRestored(X,J){if(!this.opts.onConnectionState)return;let $=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if($===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===X&&this.connectionEpoch===J)this.enqueueConnectionState({state:"restored",epoch:J},X)}).catch((Y)=>{if($===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",Y)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState(X,J,$){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:X,generation:J,reconnect:$}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let X=this.stateQueue[0];if(this.closeStarted||X.generation!==void 0&&X.generation!==this.generation||X.reconnect?.superseded){this.stateQueue.shift();continue}let{event:J}=X;try{await this.opts.onConnectionState?.(J),this.stateQueue.shift()}catch($){if(J.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",$),await LF();continue}console.warn("SubcProvider connection-state callback failed",$),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle(X){return d4(X,this.connectionToken)&&this.liveRoutes.get(X.channel)===X}assertLiveHandle(X){if(!this.isLiveHandle(X))throw new J9(X)}allocateCorr(){let X=0xffffffffffffffffn;if(this.nextCorr>X){let $=new w0("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,$),$}let J=this.nextCorr;return this.nextCorr+=1n,J}failFatal(X){if(!this.closedErr)this.closedErr=X;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function d2(X,J){return`${X.channel}:${X.epoch}:${J}`}function VF(X){try{let J=s2(X.body);return new w0(J.message??"subc error",J.code,l2(X.header.flags,J.code)?"not_sent":"terminal",J.detail)}catch{return new w0($J.from(X.body).toString("utf8")||"subc error")}}function t5(X){return X&&X.length>0?X:void 0}function UF(X){let J=t5(process.env[u2]),$=t5(process.env[p2]),Y=J!==void 0&&$!==void 0;return{connectionFile:X.connectionFile,manifest:X.manifest,handler:X.handler,health:X.health??(()=>({status:"ok"})),handshakeTimeoutMs:X.handshakeTimeoutMs,controlOps:X.controlOps,onBind:X.onBind,onBound:X.onBound,onRouteGone:X.onRouteGone,reconnectBackoff:X.reconnectBackoff??c2,sleep:X.sleep??((G)=>new Promise((Q)=>setTimeout(Q,G))),restoredDebounceMs:X.restoredDebounceMs??BF,onConnectionState:X.onConnectionState,launchNonce:t5(X.launchNonce??$),reconnectOnDrop:X.reconnectOnDrop??!Y}}function KF(X){if(X===null)return null;let J=new Set(X??[]);return J.add(XJ),[...J]}function jF(X){let J=X.launchNonce;return K6(u.Hello,R8(),0,0,XZ,n2({manifest:PF(X.manifest),protocol_ver:f6,control_ops:KF(X.controlOps),...J?{launch_nonce:J}:{}}))}function qF(X){if(X instanceof w0)return X.code==="duplicate_module_id";if(X instanceof X9||X instanceof W8)return!0;if(X instanceof T8||X instanceof D9)return!0;if(X instanceof T6)return!0;if(X instanceof G6)return!1;let J=NF(X);return J==="ECONNREFUSED"||J==="ECONNRESET"||J==="EPIPE"||J==="ETIMEDOUT"||J==="ENOENT"}function NF(X){if(typeof X==="object"&&X!==null&&"code"in X){let J=X.code;if(typeof J==="string")return J}return}async function LF(){await new Promise((X)=>setTimeout(X,0))}function R8(){return A6(!1,e0.Passive,!1)}async function e5(X,J){await B8(X,Z8(J),Date.now()+ez)}async function DF(X,J){let $=await X.readFrame(J,J);switch($.header.ty){case u.HelloAck:{let Y=s2($.body);if(Y.negotiated_ver!==f6)throw new w0(`subc negotiated protocol ${Y.negotiated_ver}; expected exactly ${f6}`,"unsupported_version");return Y}case u.Error:{let Y=s2($.body);throw new w0(`subc rejected HELLO: ${Y.code??"unknown"} — ${Y.message??"subc error"}`,Y.code)}default:throw new w0(`unexpected frame ${u[$.header.ty]} awaiting HELLO_ACK`)}}function n2(X){return new Uint8Array($J.from(JSON.stringify(X),"utf8"))}function s2(X){return JSON.parse($J.from(X).toString("utf8"))}function tz(X,J){if(typeof X!=="number"||!Number.isInteger(X))throw new w0(`route.bind ${J} must be an integer`);return X}function FF(X){if(X===void 0||X===!0)return null;if(X===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if(X.accept)return null;return{code:X.code??"route_rejected",message:X.message??"route.bind rejected by provider"}}function PF(X){return{module_id:X.module_id,module_version:X.module_version,protocol_ver:X.protocol_ver,trust_tier:X.trust_tier,provides:X.provides.map(OF),consumes:X.consumes.map(MF),bindings:{storage:{kind:X.bindings.storage.kind,scope:X.bindings.storage.scope,owns_schema:X.bindings.storage.owns_schema},vault_grants:X.bindings.vault_grants.map((J)=>({secret:J.secret,reason:J.reason})),identity:{requires:[...X.bindings.identity.requires],optional:[...X.bindings.identity.optional]}}}}function OF(X){switch(X.role){case"tool_provider":return{role:"tool_provider",tools:X.tools.map((J)=>({name:J.name,...J.description===void 0?{}:{description:J.description},execution_mode:J.execution_mode,schema:J.schema})),identity_scope:[...X.identity_scope],concurrency:X.concurrency,emits_push:X.emits_push,sub_supervises:X.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:X.stage,applies_to:{provider:X.applies_to.provider,model:X.applies_to.model},interface:X.interface,declares_frozen_floor:X.declares_frozen_floor,needs_signals:[...X.needs_signals],conformance_class:X.conformance_class};case"management_surface":return{role:"management_surface",operations:X.operations.map((J)=>({name:J.name,kind:J.kind})),config_schema:X.config_schema,observability:X.observability.map((J)=>({name:J.name,kind:J.kind})),identity_scope:[...X.identity_scope],concurrency:X.concurrency};case"internal_service":return{role:"internal_service",service_id:X.service_id,transport:X.transport,agent_facing:X.agent_facing,operations:[...X.operations]}}}function MF(X){switch(X.role){case"tool_client":return{role:"tool_client",of:[...X.of]};case"llm_client":return{role:"llm_client",via:X.via,auth:X.auth};case"service_client":return{role:"service_client",of:[...X.of]}}}var o2="subc-connection.json",$Z="subc-",YZ=".connection.json";function GZ(){let X=process.env.HOME;return X?n1(X,".local","share","cortexkit","run",o2):void 0}function RF(){let X=process.env.XDG_RUNTIME_DIR;if(X)return n1(X,o2);let J=GZ();if(J)return J;return n1(TF().homedir,".local","share","cortexkit","run",o2)}function CF(){if(process.env.SUBC_CONNECTION_FILE)return process.env.SUBC_CONNECTION_FILE;let X=process.env.XDG_RUNTIME_DIR;if(X){let G=n1(X,o2);if(a2(G))return G}let J=GZ();if(J&&a2(J))return J;let $=n1(JZ(),`${$Z}${EF()}${YZ}`);if(a2($))return $;let Y=SF(JZ());return Y.length===1?Y[0]:void 0}function EF(X=process.getuid??null,J=process.env){if(X)return String(X());for(let $ of["USER","USERNAME","HOME","USERPROFILE"]){let Y=J[$];if(Y)return Array.from(Y,(G)=>/^[a-zA-Z0-9_-]$/.test(G)?G:"_").join("")}return"unknown"}function QZ(){return CF()??RF()}function r9(X){return X?.trim()||process.env.SUBC_CONNECTION_FILE||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||QZ()}function a2(X){try{return AF(X).isFile()}catch{return!1}}function SF(X){let J;try{J=_F(X)}catch{return[]}let $=[];for(let Y of J){if(typeof Y!=="string")continue;if(!Y.startsWith($Z)||!Y.endsWith(YZ))continue;let G=n1(X,Y);if(a2(G))$.push(G)}return $.sort(),$}import{createHash as IF}from"node:crypto";import{existsSync as bF,realpathSync as zZ}from"node:fs";import{dirname as kF,relative as xF,resolve as wF}from"node:path";function ZZ(X){let J=X,$;try{$=zZ(J)}catch(Y){if(Y.code!=="ENOENT")throw Y;let G=J;while(!bF(G)){let Q=kF(G);if(Q===G)break;G=Q}$=wF(zZ(G),xF(G,J))}return IF("sha256").update($).digest("hex")}function YJ(X,J){return{project_root:X,harness:"opencode",session:`store-${ZZ(J)}`}}import{AsyncLocalStorage as vF}from"node:async_hooks";import{readFile as WZ}from"node:fs/promises";var yF=new vF;function BZ(X,J){return X.split(`
88
- `).filter(($)=>$.trim()!==""&&!$.trimStart().startsWith("#")).map(($)=>{let Y=$.split(":");if(Y.length!==J||!Y[0]||/\s/.test(Y[0])||!/^\d+$/.test(Y[2])||!Number.isSafeInteger(Number(Y[2]))||Number(Y[2])>4294967295||J===7&&(!/^\d+$/.test(Y[3])||!Number.isSafeInteger(Number(Y[3]))||Number(Y[3])>4294967295))throw Error("malformed account record");if(J===4&&Y[3]!==""&&Y[3].split(",").some((G)=>G===""||/\s/.test(G)))throw Error("malformed group members");return Y})}async function r2(X,J=yF.getStore()??{euid:process.geteuid?.(),egid:process.getegid?.(),passwdPath:"/etc/passwd",groupPath:"/etc/group"}){if((X.mode&18)===0||(X.mode&512)!==0)return!0;if((X.mode&2)!==0||J.euid===void 0||J.egid===void 0||X.uid!==J.euid||X.gid!==J.egid)return!1;try{let $=BZ(new TextDecoder("utf-8",{fatal:!0}).decode(await WZ(J.passwdPath)),7),Y=BZ(new TextDecoder("utf-8",{fatal:!0}).decode(await WZ(J.groupPath)),4),G=$.filter((Z)=>Number(Z[2])===J.euid),Q=Y.filter((Z)=>Number(Z[2])===J.egid);if(G.length!==1||Q.length!==1)return!1;let z=G[0][0];return(Q[0][3]===""||Q[0][3].split(",").every((Z)=>Z===z))&&!$.some((Z)=>Number(Z[2])!==J.euid&&Number(Z[3])===J.egid)}catch{return!1}}import{randomBytes as hF}from"node:crypto";import{chmod as fF,mkdir as gF,open as mF,realpath as uF,rename as pF,stat as cF,unlink as lF}from"node:fs/promises";import{basename as dF,dirname as HZ,join as iF}from"node:path";var nF=/^[0-9a-f]{64}$/;function sF(X){if(!nF.test(X.token))throw Error("enrollment token must be exactly 64 lowercase hex characters");if(!Number.isSafeInteger(X.token_generation)||X.token_generation<1)throw Error("enrollment token generation must be a positive safe integer")}async function aF(X){let J;try{J=await uF(X)}catch{return}for(;;){let $=await cF(J).catch(()=>{return});if($&&!await r2($))throw Error(`enrollment token ancestor ${J} is group- or world-writable without sticky bit`);let Y=HZ(J);if(Y===J)return;J=Y}}async function GJ(X,J){sF(J);let $=HZ(X);await gF($,{recursive:!0,mode:448}),await aF($);let Y=iF($,`.${dF(X)}.${process.pid}.${hF(12).toString("hex")}.tmp`),G=!1;try{let Q=await mF(Y,"wx",384);G=!0;try{await Q.writeFile(`${JSON.stringify(J)}
89
- `,"utf8"),await Q.sync(),await fF(Y,384)}finally{await Q.close()}await pF(Y,X),G=!1}finally{if(G)await lF(Y).catch(()=>{return})}}var VZ=["transient","permanent","auth_required","context_overflow"];class H8 extends Error{code;action;["class"];constructor(X,J,$){super(`Claustrum credential request failed: ${X}`);this.code=X,this.action=$,this.name="ClaustrumCredentialError",this.class=J}}function s1(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function UZ(X){switch(X){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function O0(X,J="invalid_response",$=(Y)=>console.warn(Y)){let Y=s1(X)&&s1(X.result)?X.result:void 0,G=Y&&s1(Y.error)?Y.error:void 0,Q=G?.class,z=G?.code,Z=typeof Q==="string"&&VZ.includes(Q),W=typeof z==="string",H=Z&&W?Q:"transient";if(typeof Q!=="string")$("unknown");else if(!Z)$(Q);return new H8(W?z:J,H,UZ(H))}function t9(X){return s1(X)&&s1(X.result)&&s1(X.result.error)}var KZ="claustrum",tF=60000;function g6(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function zJ(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=0?X:void 0}function C8(X){return X===void 0||typeof X==="string"}function jZ(X,J){if(t9(X))throw O0(X,"invalid_response",J);let $=g6(X)&&g6(X.result)?X.result:void 0,Y=$?.payload;if(!Array.isArray(Y)||Y.length===0||!Y.every((q)=>typeof q==="number"&&Number.isInteger(q)&&q>=0&&q<=255))throw O0(X,"invalid_response",J);let G=zJ($?.record_version);if(G===void 0)throw O0(X,"invalid_record_version",J);let Q=$?.expires_at_ms,z=Q===void 0||Q===null?null:typeof Q==="number"&&Number.isFinite(Q)?Q:void 0;if(z===void 0)throw O0(X,"invalid_expiry",J);let Z=$?.credential_id,W=$?.project_id,B=$?.account_id,H=$?.email,U=$?.org_name;if(!C8(Z)||!C8(W)||!C8(B)||!C8(H)||!C8(U))throw O0(X,"invalid_response",J);let j;try{j=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(Y))}catch{throw O0(X,"invalid_response",J)}return{material:j,recordVersion:G,expiresAtMs:z,credentialId:Z,projectId:W,accountId:B,email:H,orgName:U}}function eF(X,J){if(t9(X))throw O0(X,"invalid_response",J);let $=g6(X)&&g6(X.result)?X.result:void 0,Y=$?.record_version,G=Y===void 0?void 0:zJ(Y),Q=$?.credential_id;if(typeof $?.ready!=="boolean"||$?.last_error_code!==void 0&&$?.last_error_code!==null&&typeof $?.last_error_code!=="string"||typeof $?.lease_held!=="boolean"||Y!==void 0&&G===void 0||!C8(Q)||$?.stale_pending!==void 0&&typeof $.stale_pending!=="boolean")throw O0(X,"invalid_status",J);return{ready:$.ready,lastErrorCode:$.last_error_code??null,leaseHeld:$.lease_held,...Q===void 0?{}:{credentialId:Q},...G===void 0?{}:{recordVersion:G},...$.stale_pending===void 0?{}:{stalePending:$.stale_pending}}}class e9{#X;#J;#z;#$;#W;#G;#Y=null;#Z=0;#H=!1;constructor(X,J,$,Y,G,Q){this.#X=X,this.#J=J,this.#z=$,this.#$=Y,this.#W=G,this.#G=Q}static async connect(X={}){let J=r9(X.connectionFile),$=X.connector??((Q)=>o9.connect(Q)),Y=X.identity??YJ(X.projectRoot??process.cwd(),X.storagePath??process.cwd()),G=await $({connectionFile:J,handshakeTimeoutMs:X.handshakeTimeoutMs});return new e9(G,$,J,X.handshakeTimeoutMs,Y,X.logger??((Q)=>console.warn(Q)))}async getCredential(X,J){let $=await this.#Q("credential.get",{handle:X,min_ttl_ms:J,force_refresh:!1});return jZ($,this.#G)}async statusCredential(X){let J=await this.#Q("credential.status",{handle:X});return eF(J,this.#G)}async reportAuthFailure(X){let J=await this.#Q("credential.report_auth_failure",{handle:X.handle,provider_status:X.providerStatus,record_version:X.recordVersion,reporter_source:X.reporterSource});if(t9(J))throw O0(J,"invalid_response",this.#G);if((g6(J)&&g6(J.result)?J.result:void 0)?.accepted!==!0)throw O0(J,"invalid_response",this.#G)}async listScoped(X){let J=await this.#Q("credential.list_scoped",X===void 0?{}:{enrollment_token:X});return XP(J,this.#G)}async getScoped(X){let J=await this.#Q("credential.get_scoped",{credential_id:X.credentialId,enrollment_token:X.enrollmentToken,min_ttl_ms:X.minTtlMs});return jZ(J,this.#G)}async reportAuthFailureScoped(X){let J=await this.#Q("credential.report_auth_failure",{credential_id:X.credentialId,enrollment_token:X.enrollmentToken,provider_status:X.providerStatus,record_version:X.recordVersion,reporter_source:X.reporterSource});if(t9(J))throw O0(J,"invalid_response",this.#G);if((g6(J)&&g6(J.result)?J.result:void 0)?.accepted!==!0)throw O0(J,"invalid_response",this.#G)}async enrollPropose(X){let J=await this.#Q("auth.enroll_propose",{proposed_name:X.name,request_secret_hash:X.requestSecretHash}),Y=QJ(J,this.#G).request_id;if(typeof Y!=="string"||Y.length===0)throw O0(J,"invalid_response",this.#G);return{requestId:Y}}async enrollPoll(X){let J=await this.#Q("auth.enroll_poll",{request_id:X.requestId,request_secret:X.requestSecret});return JP(J,this.#G)}async enrollRotate(X){let J=await this.#Q("auth.enroll_rotate",{token:X.token,expected_token_generation:X.expectedTokenGeneration}),$=QJ(J,this.#G),Y=$.token,G=$.token_generation;if(typeof Y!=="string"||Y.length===0||typeof G!=="number"||!Number.isInteger(G)||G<0)throw O0(J,"invalid_response",this.#G);return{token:Y,tokenGeneration:G}}close(){this.#H=!0,this.#X.close()}async#Q(X,J){let $=this.#X;try{return await $.call(KZ,X,J,{identity:this.#W,consumerIdentity:null})}catch(Y){if(this.#V(Y)){try{if(this.#X===$)await this.#U()}catch(G){throw this.#B(G)}try{return await this.#X.call(KZ,X,J,{identity:this.#W,consumerIdentity:null})}catch(G){throw this.#B(G)}}throw this.#B(Y)}}#B(X){if(X instanceof H8)return X;let J=X instanceof Q6&&X.code?X.code:"transport_error";return new H8(J,"transient","retry")}#V(X){return!this.#H&&X instanceof Q6&&X.kind==="terminal"&&X.code!=="missing_identity"&&X.code!=="invalid_control_body"&&X.code!=="unknown_module"}async#U(){if(this.#H)throw Error("Claustrum client is closed");if(this.#Y){await this.#Y;return}let X=Date.now();if(X<this.#Z)throw Error("Claustrum client reconnect is backed off");this.#Z=X+tF,this.#Y=this.#J({connectionFile:this.#z,handshakeTimeoutMs:this.#$}).then((J)=>{if(this.#H)throw J.close(),Error("Claustrum client is closed");let $=this.#X;this.#X=J,$.close()}).finally(()=>{this.#Y=null}),await this.#Y}}function XP(X,J){if(t9(X))throw O0(X,"invalid_response",J);let $=g6(X)&&g6(X.result)?X.result:void 0,Y=$?.credentials;if(!Array.isArray(Y))throw O0(X,"invalid_response",J);let G=$?.view;if(typeof G!=="string"||G.length===0)throw O0(X,"invalid_response",J);return{rows:Y.map((z)=>{if(!g6(z))throw O0(X,"invalid_response",J);let Z=zJ(z.record_version);if(Z===void 0)throw O0(X,"invalid_record_version",J);let W=(U)=>{if(!Array.isArray(U)||!U.every((j)=>typeof j==="string"))throw O0(X,"invalid_response",J);return U};if(typeof z.id!=="string"||typeof z.type!=="string"||typeof z.state!=="string")throw O0(X,"invalid_response",J);let B=z.created_at_ms===void 0||z.created_at_ms===null?null:typeof z.created_at_ms==="number"&&Number.isFinite(z.created_at_ms)?z.created_at_ms:void 0;if(B===void 0)throw O0(X,"invalid_response",J);let H=z.auth_method;if(H!==void 0&&H!=="apikey"&&H!=="chatgpt"&&H!=="antigravity"&&H!=="oauth")throw O0(X,"invalid_response",J);if(!C8(z.refresh_adapter))throw O0(X,"invalid_response",J);if(!C8(z.account_id)||!C8(z.email)||!C8(z.org_name))throw O0(X,"invalid_response",J);return{id:z.id,categories:W(z.categories),credentialType:z.type,serves:W(z.serves),providerIds:z.provider_ids===void 0?[]:W(z.provider_ids),authMethod:H,state:z.state,refreshAdapter:z.refresh_adapter,recordVersion:Z,operations:W(z.operations),createdAtMs:B,accountId:z.account_id,email:z.email,orgName:z.org_name}}),view:G}}function QJ(X,J){if(t9(X))throw O0(X,"invalid_response",J);let $=g6(X)&&g6(X.result)?X.result:void 0;if($===void 0)throw O0(X,"invalid_response",J);return $}function JP(X,J){let $=QJ(X,J),Y=$.status;if(Y==="pending")return{status:"pending"};if(Y==="denied")return{status:"denied"};if(Y!=="approved")throw O0(X,"invalid_response",J);let{name:G,token:Q,token_generation:z}=$;if(typeof G!=="string"||typeof Q!=="string"||Q.length===0||typeof z!=="number"||!Number.isInteger(z))throw O0(X,"invalid_response",J);return{status:"approved",name:G,token:Q,tokenGeneration:z}}function s4(X){let J=new AbortController,$=[],Y=!1,G=()=>{if(Y)return;Y=!0;for(let{source:Z,listener:W}of $)Z.removeEventListener("abort",W);$.length=0},Q=(Z)=>{if(Y||J.signal.aborted)return;J.abort(Z),G()},z=X.find((Z)=>Z.aborted);if(z)return J.abort(z.reason),{signal:J.signal,dispose:G};for(let Z of X){if(J.signal.aborted)break;let W=()=>Q(Z.reason);if($.push({source:Z,listener:W}),Z.addEventListener("abort",W,{once:!0}),Z.aborted)Q(Z.reason)}return{signal:J.signal,dispose:G}}import{createHash as $P,randomBytes as YP,randomUUID as GP}from"node:crypto";import{constants as qZ}from"node:fs";import{chmod as QP,mkdir as zP,open as PZ,readFile as NZ,realpath as ZP,rename as WP,stat as OZ,unlink as MZ}from"node:fs/promises";import{basename as _Z,dirname as J1,extname as LZ,isAbsolute as DZ,join as BJ,resolve as BP}from"node:path";class $0 extends Error{kind;constructor(X,J){super(J);this.name="ClaustrumConsumerError",this.kind=X}}var HP=1,ZJ=16384,AZ=30000,HJ=/^[0-9a-f]{64}$/,TZ=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),RZ=new Set(["pending_queue_full"]);function WJ(X){if(!(X instanceof H8))return;if(TZ.has(X.code))return{code:X.code,disposition:"terminal"};if(RZ.has(X.code))return{code:X.code,disposition:"retry"};return{code:X.code,disposition:X.action==="retry"?"retry":"terminal"}}function VJ(X,J){if(!/^[a-z0-9][a-z0-9-]*$/.test(X)||!/^[a-z0-9][a-z0-9-]*$/.test(J))throw new $0("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${X}-${J}`}function UJ(X){return e9.connect(X)}function CZ(X){let J=LZ(X)||".json",$=_Z(X,LZ(X));return{statePath:BJ(J1(X),`${$}-state${J}`),tokenPath:X}}function KJ(X){let J=X.override?.trim();if(J&&!DZ(J)&&!X.cwd)throw new $0("invalid-state","A relative Claustrum enrollment override needs a base directory");let $=J?DZ(J)?J:BP(X.cwd,J):BJ(X.stateDir,`${X.host}-enrollment.json`);return CZ($)}function EZ(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function t2(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=0}function SZ(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=1}function a4(){return new $0("invalid-state","invalid Claustrum enrollment state")}function X7(X){if(!EZ(X)||X.version!==HP||typeof X.proposedName!=="string"||X.proposedName.length===0)throw a4();if(X.phase==="pending"){if(!HJ.test(String(X.requestSecret??""))||X.requestId!==void 0&&(typeof X.requestId!=="string"||X.requestId.length===0)||!t2(X.createdAt)||!t2(X.updatedAt))throw a4();return{version:1,phase:"pending",proposedName:X.proposedName,requestSecret:X.requestSecret,...X.requestId!==void 0&&{requestId:X.requestId},createdAt:X.createdAt,updatedAt:X.updatedAt}}if(X.phase==="approved"){if(X.approvedName!==void 0&&(typeof X.approvedName!=="string"||X.approvedName.length===0)||!SZ(X.tokenGeneration)||!t2(X.updatedAt))throw a4();return{version:1,phase:"approved",proposedName:X.proposedName,...X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:X.tokenGeneration,updatedAt:X.updatedAt}}if(X.phase==="denied"||X.phase==="blocked"){if(X.errorCode!==void 0&&typeof X.errorCode!=="string"||!t2(X.updatedAt))throw a4();return{version:1,phase:X.phase,proposedName:X.proposedName,...X.errorCode!==void 0&&{errorCode:X.errorCode},updatedAt:X.updatedAt}}throw a4()}function jJ(X){if(!EZ(X)||!HJ.test(String(X.token??""))||!SZ(X.token_generation))throw new $0("invalid-token","invalid Claustrum enrollment token file");return{token:X.token,token_generation:X.token_generation}}function VP(X){if(!X.isFile())throw new $0("unsafe-file","Claustrum enrollment file must be a regular file");if((X.mode&63)!==0)throw new $0("unsafe-file","Claustrum enrollment file must be owner-only");let J=process.geteuid?.();if(J!==void 0&&X.uid!==J)throw new $0("unsafe-file","Claustrum enrollment file must be owned by the current user")}function UP(X){try{return JSON.parse(X)}catch{throw new $0("invalid-state","Claustrum enrollment file is not valid JSON")}}async function O9(X){let J;try{J=await PZ(X,qZ.O_RDONLY|qZ.O_NOFOLLOW)}catch($){if($.code==="ENOENT")return;throw new $0("unsafe-file","Claustrum enrollment file could not be opened safely")}try{VP(await J.stat());let $=Buffer.alloc(ZJ+1),{bytesRead:Y}=await J.read($,0,$.byteLength,0);if(Y>ZJ)throw new $0("unsafe-file","Claustrum enrollment file is too large");return UP($.subarray(0,Y).toString("utf8"))}finally{await J.close()}}function FZ(X,J){let $=[];for(let Y of X.split(`
90
- `)){if(Y.trim()===""||Y.startsWith("#"))continue;let G=Y.split(":");if(G.length!==J||!/^[^\s:,]+$/.test(G[0]??"")||!/^\d+$/.test(G[2]??"")||!Number.isSafeInteger(Number(G[2]))||J===7&&(!/^\d+$/.test(G[3]??"")||!Number.isSafeInteger(Number(G[3])))||J===4&&G[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(G[3]??""))return;$.push(G)}return $}async function KP(X,J,$){try{let[Y,G]=await Promise.all([NZ($.passwdPath??"/etc/passwd","utf8"),NZ($.groupPath??"/etc/group","utf8")]),Q=FZ(Y,7),z=FZ(G,4);if(!Q||!z)return!1;let Z=Q.filter((U)=>Number(U[2])===X),W=z.filter((U)=>Number(U[2])===J);if(Z.length!==1||W.length!==1)return!1;let B=Z[0]?.[0],H=W[0]?.[3]??"";return(H===""||H.split(",").every((U)=>U===B))&&!Q.some((U)=>Number(U[2])!==X&&Number(U[3])===J)}catch{return!1}}async function IZ(X,J={}){let $=process.geteuid?.();if($===void 0)return;let Y=process.getegid?.(),G;try{G=await ZP(X)}catch{return}let Q;for(;;){let z=await OZ(G).catch(()=>{return});if(z&&(z.mode&18)!==0&&(z.mode&512)===0){if(Q===void 0)Q=Y!==void 0&&await KP($,Y,J);if((z.mode&2)!==0||z.uid!==$||z.gid!==Y||!Q)throw new $0("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${G}. Another user could replace it. Run: chmod g-w,o-w ${G}`)}let Z=J1(G);if(Z===G)return;G=Z}}async function e2(X){await zP(X,{recursive:!0,mode:448});let J=await OZ(X),$=process.geteuid?.();if($!==void 0&&J.uid!==$)throw new $0("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((J.mode&63)!==0)await QP(X,448)}async function X1(X,J,$={}){let Y=J1(X);await e2(Y),await IZ(Y,$);let G=`${JSON.stringify(J)}
91
- `;if(Buffer.byteLength(G)>ZJ)throw new $0("invalid-state","Claustrum enrollment state is too large");let Q=BJ(Y,`.${_Z(X)}.${process.pid}.${GP()}.tmp`),z,Z=!1;try{z=await PZ(Q,"wx",384),Z=!0,await z.writeFile(G,"utf8"),await z.chmod(384),await z.sync(),await z.close(),z=void 0,await WP(Q,X),Z=!1}finally{if(await z?.close().catch(()=>{}),Z)await MZ(Q).catch(()=>{})}}async function o4(X,J){let $=await O9(X.tokenPath),Y=$===void 0?void 0:jJ($),G=await O9(X.statePath),Q=G===void 0?void 0:X7(G);if(Y)return{state:"approved",proposedName:Q?.proposedName??J,...Q?.phase==="approved"&&Q.approvedName!==void 0&&{approvedName:Q.approvedName},tokenGeneration:Y.token_generation};if(!Q)return{state:"idle"};if(Q.phase==="approved")return{state:"blocked",proposedName:Q.proposedName,code:"missing_token"};return P9(Q)}async function r4(X,J){let $;try{$=await o4(X,J)}catch(Y){if(!(Y instanceof $0)||Y.kind!=="invalid-state"&&Y.kind!=="invalid-token")return"unreadable";try{let G=await O9(X.statePath);if(G===void 0)return"unreadable";let Q=X7(G);return Q.phase==="approved"&&Q.proposedName===J?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in $&&$.proposedName!==J)return"unreadable";if($.state==="approved"||$.state==="blocked"&&$.code==="missing_token")return"vault";return"local"}async function qJ(X){let J=await O9(X);if(J===void 0)throw new $0("not-enrolled","Claustrum enrollment is not configured");return jJ(J)}function P9(X){if(X.phase==="pending")return{state:"pending",proposedName:X.proposedName,...X.requestId!==void 0&&{requestId:X.requestId}};if(X.phase==="approved")return{state:"approved",proposedName:X.proposedName,...X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:X.tokenGeneration};if(X.phase==="denied")return{state:"denied",proposedName:X.proposedName};return{state:"blocked",proposedName:X.proposedName,code:X.errorCode??"unknown"}}function bZ(){return new $0("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class J7{#X;#J;#z;#$;#W;#G;#Y;constructor(X){this.#Y=X.ancestorOptions??{},this.#X=X.client,this.#J=X.paths,this.#z=X.proposedName,this.#$=X.now??Date.now,this.#W=X.mintSecret??(()=>YP(32).toString("hex")),this.#G=X.writeTokenFile??GJ}async status(){return o4(this.#J,this.#z)}async resetTerminal(){return kZ(this.#J,this.#z)}async#Z(X,J){let $={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:J,updatedAt:this.#$()};return await X1(this.#J.statePath,$,this.#Y),P9($)}async reconcile(){await e2(J1(this.#J.statePath));let X=await g0({name:"ceremony",path:this.#J.statePath,ttlMs:AZ,renew:!0});if(!X)return{state:"busy"};try{let J=await O9(this.#J.tokenPath),$=J===void 0?void 0:jJ(J),Y=await O9(this.#J.statePath),G=Y===void 0?void 0:X7(Y);if(G&&G.proposedName!==this.#z)throw bZ();if($){if(!G||G.phase==="pending"){let z={version:1,phase:"approved",proposedName:G?.proposedName??this.#z,tokenGeneration:$.token_generation,updatedAt:this.#$()};await X1(this.#J.statePath,z,this.#Y),G=z}return{state:"approved",proposedName:G.proposedName,...G.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:$.token_generation}}if(G?.phase==="approved"){let z={version:1,phase:"blocked",proposedName:G.proposedName,errorCode:"missing_token",updatedAt:this.#$()};return await X1(this.#J.statePath,z,this.#Y),P9(z)}if(G&&G.phase!=="pending")return P9(G);if(!G){let z=this.#$();if(G={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#W(),createdAt:z,updatedAt:z},!HJ.test(G.requestSecret))throw new $0("invalid-state","invalid minted Claustrum enrollment secret");await X1(this.#J.statePath,G,this.#Y)}if(!G.requestId)try{let z=$P("sha256").update(Buffer.from(G.requestSecret,"hex")).digest("hex"),Z=await this.#X.enrollPropose({name:G.proposedName,requestSecretHash:z});G={...G,requestId:Z.requestId,updatedAt:this.#$()},await X1(this.#J.statePath,G,this.#Y)}catch(z){let Z=WJ(z);if(!Z)throw z;if(Z.disposition==="retry")return{state:"pending",proposedName:G.proposedName,retryCode:Z.code};return this.#Z(G,Z.code)}let Q=G.requestId;if(!Q)return P9(G);try{let z=await this.#X.enrollPoll({requestId:Q,requestSecret:G.requestSecret});if(z.status==="pending")return P9(G);if(z.status==="denied"){let W={version:1,phase:"denied",proposedName:G.proposedName,updatedAt:this.#$()};return await X1(this.#J.statePath,W,this.#Y),P9(W)}await e2(J1(this.#J.tokenPath)),await IZ(J1(this.#J.tokenPath),this.#Y),await this.#G(this.#J.tokenPath,{token:z.token,token_generation:z.tokenGeneration});let Z={version:1,phase:"approved",proposedName:G.proposedName,approvedName:z.name,tokenGeneration:z.tokenGeneration,updatedAt:this.#$()};return await X1(this.#J.statePath,Z,this.#Y),P9(Z)}catch(z){let Z=WJ(z);if(!Z)throw z;if(Z.disposition==="retry")return{state:"pending",proposedName:G.proposedName,requestId:Q,retryCode:Z.code};return this.#Z(G,Z.code)}}finally{await X.release()}}}async function kZ(X,J){await e2(J1(X.statePath));let $=await g0({name:"ceremony",path:X.statePath,ttlMs:AZ,renew:!0});if(!$)return"busy";try{if(await O9(X.tokenPath)!==void 0)return"refused-approved";let Y=await O9(X.statePath);if(Y===void 0)return"idle";let G=X7(Y);if(G.proposedName!==J)throw bZ();if(G.phase==="pending")return"refused-pending";return await $.assertOwned(),await MZ(X.statePath),"reset"}finally{await $.release()}}var t4="claustrum-tombstone:v1:";function $7(X){return`${t4}${X}`}function NJ(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function Y7(X){return typeof X==="string"&&X.startsWith(t4)}function xZ(X,J){if(!NJ(X)||X.type!=="oauth")return!1;return X.refresh===$7(J)}function wZ(X,J){if(xZ(X,J))return"placeholder";if(NJ(X)&&X.type==="oauth"&&typeof X.refresh==="string"&&X.refresh.length>0&&!Y7(X.refresh))return"login";if(NJ(X)&&X.type==="api"&&typeof X.key==="string"&&X.key.length>0)return"login";return"empty"}function LJ(X){let J=wZ(X.auth,X.provider);if(X.mode==="custody"&&J==="login")throw new $0("host-slot-login",`${X.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if(X.mode==="local"&&J==="placeholder")throw new $0("host-slot-placeholder",`${X.provider} host slot holds the vault placeholder; sign in to use local accounts`);return J}function vZ(X,J){return J!==void 0&&J.credentialId===X.credentialId&&J.accountIdentity===X.accountIdentity&&J.recordVersion!==X.recordVersion}function jP(X,J){if(J===void 0)return"reauthorize-failed";if(J.credentialId!==X.credentialId)return"credential-changed";if(J.accountIdentity!==X.accountIdentity)return"account-changed";if(J.recordVersion===X.recordVersion)return"version-unchanged";return"rotated"}var yZ=Z0("claustrum");function PJ(X,J,$,Y=yZ){let G=vZ(J,$);return Y.debug("scoped 401 re-authorized",{site:X,credentialId:J.credentialId,servedVersion:J.recordVersion,currentVersion:$?.recordVersion??null,retry:G,reason:jP(J,$)}),G}var FJ=300000;function DJ(){return new $0("invalid-material","Claustrum returned invalid credential material")}function qP(X){let J=X.trim();if(J.startsWith("{")){let $;try{$=JSON.parse(J)}catch{throw DJ()}if(!$||typeof $!=="object")throw DJ();let Y=$,G=Y.access_token??Y.access;J=typeof G==="string"?G:""}if(!/^[\x21-\x7e]+$/.test(J)||J.startsWith(t4))throw DJ();return J}function NP(X,J){if(!X.operations.includes("read"))return;if(!X.categories.includes(J.category))return;if(X.credentialType==="oauth")return X.refreshAdapter===J.refreshAdapter?"oauth":void 0;if(X.credentialType==="api_key"&&J.apiKeys)return X.refreshAdapter===void 0?"api_key":void 0;return}class G7{#X;#J;#z;#$;#W;#G;#Y;#Z=new WeakMap;#H=new WeakMap;#Q=!1;constructor(X){let J=X.tokenPath;if(X.readToken)this.#J=X.readToken;else if(J)this.#J=()=>qJ(J);else throw new $0("not-enrolled","Claustrum enrollment token path is required");this.#X=X.client,this.#$=X.family,this.#W=X.parseIdentity,this.#G=X.requireAssertion??!1,this.#z=X.now??Date.now,this.#Y=X.logger??yZ}#B(X){if(this.#Q)throw new $0("closed","Claustrum scoped custody is closed");X?.throwIfAborted()}async#V(X){this.#B(X);let J=await this.#J();if(this.#B(X),!/^[0-9a-f]{64}$/.test(J.token)||!Number.isSafeInteger(J.token_generation)||J.token_generation<1)throw new $0("invalid-token","Invalid Claustrum enrollment token");return J.token}async#U(X,J){this.#B(J);let $,Y;try{let G=X();$=J?await Promise.race([G,new Promise((Q,z)=>{let Z=()=>z(J.reason);if(J.addEventListener("abort",Z,{once:!0}),Y=()=>J.removeEventListener("abort",Z),J.aborted)Z()})]):await G}catch(G){if(this.#B(J),G instanceof H8)throw G;throw new $0("unavailable","Claustrum scoped operation unavailable")}finally{Y?.()}return this.#B(J),$}async discover(X){let J=await this.#V(X),$=await this.#U(()=>this.#X.listScoped(J),X),Y=[],G=[],Q=new Map;for(let Z of $.rows){let W=NP(Z,this.#$);if(!W)continue;G.push({row:Z,type:W}),Q.set(Z.id,(Q.get(Z.id)??0)+1)}let z=[];for(let{row:Z,type:W}of G){let B;if(!Z.id.trim())B="empty credential id";else if((Q.get(Z.id)??0)>1)B="duplicate credential id";else if(Z.accountId!==void 0&&!Z.accountId.trim())B="blank account identity";else if(!Z.state.trim())B="empty state";if(B){Y.push({...Z.id.trim()&&{credentialId:Z.id},reason:B});continue}z.push(Object.freeze({credentialId:Z.id,credentialType:W,...Z.accountId!==void 0&&{accountIdentity:Z.accountId},state:Z.state,...Z.email!==void 0&&{email:Z.email},...Z.orgName!==void 0&&{orgName:Z.orgName}}))}for(let Z of Y)this.#Y.warn("skipped malformed vault record",Z);return{view:$.view,credentials:Object.freeze(z),skipped:Object.freeze(Y)}}async authorize(X,J){if(!X.credentialId)throw new $0("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:$,credentialType:Y,accountIdentity:G}=X;if(this.#G&&G===void 0)throw new $0("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#V(J),z=await this.#U(()=>this.#X.getScoped({credentialId:$,enrollmentToken:Q,...Y==="oauth"&&{minTtlMs:FJ}}),J);if(z.credentialId!==void 0&&z.credentialId!==$)throw new $0("identity-changed","Claustrum served credential identity changed");let Z=z.expiresAtMs;if(!Number.isSafeInteger(z.recordVersion)||z.recordVersion<0||Z===null&&Y==="oauth"||Z!==null&&(!Number.isFinite(Z)||Z-this.#z()<FJ))throw new $0("insufficient-validity","Claustrum served credential has insufficient validity");let W=qP(z.material),B=z.accountId?.trim()?z.accountId:void 0;if(this.#G&&(z.credentialId===void 0||B===void 0))throw new $0("identity-unasserted","Claustrum served credential did not assert its identity");let H=B===void 0?this.#W?.(W):void 0,U=B??H;if(G!==void 0&&U!==void 0&&U!==G)throw new $0("identity-changed","Claustrum served credential identity changed");let j=U??G,K=Object.freeze(Object.defineProperty({credentialId:$,credentialType:Y,...j!==void 0&&{accountIdentity:j},accountIdentitySource:B!==void 0?"asserted":H!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...z.credentialId!==void 0&&{assertedCredentialId:z.credentialId},...B!==void 0&&{assertedAccountIdentity:B},...z.projectId!==void 0&&{projectId:z.projectId},recordVersion:z.recordVersion,expiresAtMs:Z},"accessToken",{value:W,enumerable:!1}));return this.#Z.set(K,Q),K}async reportFailure(X,J,$){if(J!==401)return;this.#B();let Y=this.#Z.get(X);if(!Y)throw new $0("no-receipt","Claustrum failure report requires an original dispatch receipt");let G=this.#H.get(X);if(G)return G;let Q=this.#U(()=>this.#X.reportAuthFailureScoped({credentialId:X.credentialId,enrollmentToken:Y,providerStatus:401,recordVersion:X.recordVersion,reporterSource:$}));this.#H.set(X,Q);try{await Q,this.#Y.debug("scoped 401 reported",{credentialId:X.credentialId,recordVersion:X.recordVersion,reporterSource:$})}catch(z){throw this.#H.delete(X),z}}close(){if(this.#Q)return;this.#Q=!0,this.#X.close()}}import{createHash as LP}from"node:crypto";import{readFile as DP}from"node:fs/promises";function hZ(X,J,$){if(X.accountIdentity!==void 0&&$!==void 0)return X.accountIdentity===$;return X.credentialId===J}function OJ(X,J,$){return X.some((Y)=>hZ(Y,J,$))}function MJ(X,J,$){let Y={credentialId:J,...$!==void 0&&{accountIdentity:$}};return[...X.filter((G)=>G.credentialId!==J||G.accountIdentity!==$),Y]}function _J(X,J,$){return X.filter((Y)=>!J.some((G)=>hZ(Y,G,$)))}var mZ="vault:";function FP(X){return LP("sha256").update(X).digest("hex")}function PP(X){let J=X.credentialId.split(":");return(J.length>=3?J.slice(2).join(":").trim():void 0)||X.email||X.credentialId}function OP(X){return X.identity!==void 0?`identity:${X.identity}`:`credential:${X.credential.credentialId}`}function M9(X){return[X.credentialId,...X.aliases??[]]}function uZ(X,J,$={}){let Y=$.now??Date.now(),G=$.routePrefix??mZ,Q=$.reservedRouteIds??new Set,z=X?.rows??[],Z=[...X?.declined??[]],W=J.skipped.length===0,B=new Set(J.credentials.map((N)=>N.credentialId)),H=new Set(J.skipped.flatMap((N)=>N.credentialId===void 0?[]:[N.credentialId])),U=J.skipped.some((N)=>N.credentialId===void 0),j=(N)=>!B.has(N)&&(H.has(N)||U),q=new Map;for(let N of z){if(N.accountIdentity===void 0)continue;for(let P of M9(N))if(!q.has(P))q.set(P,N.accountIdentity)}let K=new Map;for(let N of J.credentials){let P=N.accountIdentity!==void 0?{credential:N,identity:N.accountIdentity,claimed:!0}:{credential:N,identity:q.get(N.credentialId),claimed:!1},A=OP(P),T=K.get(A)??[];T.push(P),K.set(A,T)}let L=new Set,F=new Set(Q),O=[],_=(N,P)=>N.credential.credentialId.localeCompare(P.credential.credentialId),C=[...K.values()].map((N)=>N.toSorted(_)).sort((N,P)=>N[0]&&P[0]?_(N[0],P[0]):0);for(let N of C){let P=N[0]?.identity,A=N.filter((r)=>r.credential.state==="active"),T=A.length?A:N,b=T.filter((r)=>r.claimed),p=b.length?b:T,i=new Set(N.map((r)=>r.credential.credentialId)),X0=z.find((r)=>!L.has(r)&&M9(r).some((a)=>i.has(a))&&(r.accountIdentity===void 0||r.accountIdentity===P)),w=p.find((r)=>r.credential.credentialId===X0?.credentialId)??p[0];if(!w)continue;let J0=w.credential,G0=X0??(P===void 0?void 0:z.find((r)=>!L.has(r)&&r.accountIdentity===P));if(G0)L.add(G0);let L0=G0?.routeId;if(!L0||Q.has(L0)){let r=`${G}${J0.credentialId}${P===void 0?"":`~${FP(P).slice(0,10)}`}`;L0=r;for(let a=2;F.has(L0);a++)L0=`${r}~${a}`}F.add(L0);let m=G0?M9(G0).filter(j):[],c0=[...new Set([...N.map((r)=>r.credential.credentialId),...m])].filter((r)=>r!==J0.credentialId).sort((r,a)=>r.localeCompare(a)),m0=$.mapAccount?.(J0)??{};O.push({previousIndex:G0?z.indexOf(G0):1/0,row:{routeId:L0,credentialId:J0.credentialId,credentialType:J0.credentialType,...P!==void 0&&{accountIdentity:P},...c0.length&&{aliases:c0},state:J0.state,label:m0.label?.trim()||PP(J0),...J0.email!==void 0&&{email:J0.email},...J0.orgName!==void 0&&{orgName:J0.orgName},enabled:![J0.credentialId,...c0].some((r)=>OJ(Z,r,P)),addedAt:G0?.addedAt??Y,...G0?.quota!==void 0&&{quota:G0.quota},...!w.claimed&&P!==void 0&&{unclaimed:!0}}})}return z.forEach((N,P)=>{if(L.has(N)||!M9(N).some(j))return;if(F.has(N.routeId))return;let[A,...T]=M9(N).filter((i)=>!B.has(i));if(A===void 0)return;F.add(N.routeId);let{aliases:b,...p}=N;O.push({previousIndex:P,row:{...p,credentialId:A,...T.length&&{aliases:T},stale:!0}})}),O.sort((N,P)=>N.previousIndex===P.previousIndex?N.row.credentialId.localeCompare(P.row.credentialId):N.previousIndex-P.previousIndex),{version:1,view:J.view,complete:W,...!W&&{rejected:J.skipped.map((N)=>({...N.credentialId!==void 0&&{credentialId:N.credentialId},reason:N.reason}))},rows:O.map((N)=>N.row),declined:Z}}function AJ(X){return(X?.rows??[]).filter((J)=>J.enabled&&J.state==="active").map((J)=>({id:J.routeId,kind:J.credentialType==="oauth"?"oauth":"api-key",...J.quota!==void 0&&{quota:J.quota}}))}function Q7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function a1(X){return X===void 0||typeof X==="string"}function MP(X){if(!Q7(X)||typeof X.routeId!=="string"||typeof X.credentialId!=="string"||X.credentialType!=="oauth"&&X.credentialType!=="api_key"||typeof X.state!=="string"||typeof X.label!=="string"||typeof X.enabled!=="boolean"||typeof X.addedAt!=="number"||!a1(X.accountIdentity)||!a1(X.email)||!a1(X.orgName)||X.aliases!==void 0&&(!Array.isArray(X.aliases)||!X.aliases.every((J)=>typeof J==="string"))||X.quota!==void 0&&!Y6(X.quota)||X.stale!==void 0&&X.stale!==!0||X.unclaimed!==void 0&&X.unclaimed!==!0)return;return X}var _P=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function fZ(X){if(!Array.isArray(X))return;let J=[];for(let $ of X){if(!Q7($)||!a1($.credentialId)||typeof $.reason!=="string"||!_P.has($.reason))return;J.push($)}return J}function AP(X){if(!Q7(X)||X.version!==1||!a1(X.view)||!Array.isArray(X.rows)||!Array.isArray(X.declined)||X.complete!==void 0&&typeof X.complete!=="boolean"||X.rejected!==void 0&&!fZ(X.rejected))throw new $0("invalid-state","Claustrum roster file is not valid");let J=[];for(let G of X.rows){let Q=MP(G);if(!Q)throw new $0("invalid-state","Claustrum roster file is not valid");J.push(Q)}let $=[];for(let G of X.declined){if(!Q7(G)||typeof G.credentialId!=="string"||!a1(G.accountIdentity))throw new $0("invalid-state","Claustrum roster file is not valid");$.push(G)}let Y=fZ(X.rejected);return{version:1,...typeof X.view==="string"&&{view:X.view},complete:X.complete!==!1,...Y&&{rejected:Y},rows:J,declined:$}}async function _9(X){let J;try{J=await DP(X,"utf8")}catch(Y){if(Y.code==="ENOENT")return;throw Y}let $;try{$=JSON.parse(J)}catch{throw new $0("invalid-state","Claustrum roster file is not valid")}return AP($)}var TP={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},RP={name:"claustrum-roster",ttlMs:30000};async function e4(X,J,$={}){return gZ(X,TP,async(Y)=>{let G=await _9(X),{next:Q,result:z}=await J(G,{assertOwned:()=>Y.assertOwned()});if(Q)await Y.assertOwned(),await O6(X,Q,{beforeRename:async()=>{await $.beforePublish?.(),await Y.assertOwned()}});return z})}function TJ(X,J){return e4(X,($)=>{let Y=$?.rows.find((Q)=>Q.routeId===J);if(!$||!Y)throw new $0("route-unavailable","Claustrum route is not in the roster");let G=MJ($.declined,Y.credentialId,Y.accountIdentity);return{next:{...$,declined:G,rows:$.rows.map((Q)=>Q===Y?{...Q,enabled:!1}:Q)},result:void 0}})}function RJ(X,J){return e4(X,($)=>{let Y=$?.rows.find((G)=>G.routeId===J);if(!$||!Y)throw new $0("route-unavailable","Claustrum route is not in the roster");return{next:{...$,declined:_J($.declined,M9(Y),Y.accountIdentity),rows:$.rows.map((G)=>G===Y?{...G,enabled:!0}:G)},result:void 0}})}function CP(X,J){if(!M9(X).includes(J.credentialId))return"refuse";if(X.unclaimed&&(J.accountIdentitySource==="expected"||J.accountIdentitySource==="none"))return"refuse";if(X.accountIdentity===J.accountIdentity)return"hold";if(X.accountIdentity===void 0&&J.expectedAccountIdentity===void 0&&J.accountIdentity!==void 0&&(J.accountIdentitySource==="asserted"||J.accountIdentitySource==="parsed")&&M9(X).length===1)return"bind";return"refuse"}function CJ(X,J){return e4(X,($)=>{let Y=$?.rows.find((Z)=>Z.routeId===J.routeId),G=!$||!Y?"refuse":CP(Y,J);if(!$||!Y||G==="refuse")return{result:!1};let Q=z7(Y.quota,J.observation),z=G==="bind"?{accountIdentity:J.accountIdentity,unclaimed:!0}:{};return{next:{...$,rows:$.rows.map((Z)=>Z===Y?{...Z,...z,quota:Q}:Z)},result:!0}})}async function EJ(X){X.signal?.throwIfAborted();let J=async()=>await X.isActive?.()??!0;if(!await J())return;let $=await g0({...RP,path:X.path,renew:!0});if(!$){let Y=await _9(X.path);if(X.signal?.throwIfAborted(),!Y?.view)throw new $0("roster-busy","Claustrum account discovery is already in progress");return Y}try{let Y=await X.custody.discover(X.signal);return X.signal?.throwIfAborted(),await e4(X.path,async(G)=>{if(!await J())return{result:void 0};X.signal?.throwIfAborted(),await $.assertOwned();let Q=typeof X.projection==="function"?X.projection():X.projection,z=uZ(G,Y,Q);return{...JSON.stringify(G)!==JSON.stringify(z)&&{next:z},result:z}})}finally{await $.release()}}class Z7{#X;#J=new AbortController;#z;#$;#W;#G;#Y;#Z;#H=!1;constructor(X){this.#X=X,this.#z=X.logger??Z0("claustrum")}#Q(X){this.#J.signal.throwIfAborted(),X?.throwIfAborted()}async#B(){return await this.#X.isCustodyActive?.()??!0}#V(X,J){let $=s4([this.#J.signal,...J?[J]:[]]);return new Promise((Y,G)=>{let Q=()=>{$.signal.removeEventListener("abort",z),$.dispose()},z=()=>{Q(),G($.signal.reason)};if($.signal.addEventListener("abort",z,{once:!0}),X.then((Z)=>{if(Q(),$.signal.aborted)G($.signal.reason);else Y(Z)},(Z)=>{Q(),G(Z)}),$.signal.aborted)z()})}async#U(){if(this.#Q(),this.#$)return this.#$;if(!this.#W)this.#W=this.#X.connect().then((X)=>{if(this.#J.signal.aborted)X.close(),this.#Q();return this.#$=new G7({client:X,family:this.#X.family,tokenPath:this.#X.tokenPath,parseIdentity:this.#X.parseIdentity,requireAssertion:this.#X.requireAssertion,now:this.#X.now,logger:this.#z}),this.#$}).finally(()=>{this.#W=void 0});return this.#V(this.#W)}snapshot(){return this.#Y}routingRows(){return AJ(this.#Y)}refresh(){if(this.#Q(),this.#G)return this.#G;return this.#G=(async()=>{if(!await this.#B()){this.#Y=void 0,this.#$?.close(),this.#$=void 0;return}let X=await this.#U(),J=await EJ({path:this.#X.rosterPath,custody:X,isActive:()=>this.#B(),signal:this.#J.signal,projection:()=>({reservedRouteIds:new Set(this.#X.reservedRouteIds?.()??[]),routePrefix:this.#X.routePrefix,mapAccount:this.#X.mapAccount,now:(this.#X.now??Date.now)()})});this.#Q();let $=J?.view!==this.#Y?.view;if(this.#Y=J,J&&$)this.#X.onRoster?.(J);return J})().finally(()=>{this.#G=void 0}),this.#G}start(){if(this.#H)return;this.#Q(),this.#H=!0;let X=async()=>{try{await this.refresh()}catch($){if(!this.#J.signal.aborted)this.#X.onError?.($)}if(this.#J.signal.aborted)return;let J=this.#X.pollIntervalMs??5000;if(J<=0)return;this.#Z=(this.#X.setTimeoutImpl??setTimeout)(()=>{this.#Z=void 0,X()},J),this.#Z.unref?.()};X()}async authorize(X,J){this.#Q(J);let $=this.#Y??await this.#V(this.refresh(),J);if(!$||!await this.#B())throw new $0("not-active","Claustrum scoped custody is not active");let Y=await _9(this.#X.rosterPath);this.#Q(J);let G=$.rows.find((W)=>W.routeId===X),Q=Y?.rows.find((W)=>W.routeId===X);if(Q&&!Q.enabled)throw new $0("route-declined","Claustrum route is disabled");if(!G||!Q||Q.state!=="active"||Q.credentialId!==G.credentialId||Q.accountIdentity!==G.accountIdentity)throw new $0("route-unavailable","Claustrum route is disabled, removed or changed");let z=await this.#V(this.#U(),J),Z=s4([this.#J.signal,...J?[J]:[]]);try{return await z.authorize({credentialId:Q.credentialId,credentialType:Q.credentialType,...Q.accountIdentity!==void 0&&{accountIdentity:Q.accountIdentity}},Z.signal)}finally{Z.dispose()}}async reportFailure(X,J,$){if(this.#Q(),!this.#$)throw new $0("no-receipt","Claustrum dispatch receipt has no active owner");await this.#$.reportFailure(X,J,$)}async send(X,J,$){let Y=$.signal,G=await this.authorize(X,Y),Q=await J(G,Y);if(Q.status===401&&!Y?.aborted){let z;try{z=await this.authorize(X,Y)}catch{}if(PJ($.site,G,z,this.#z))await Q.body?.cancel().catch(()=>{}),G=z,Q=await J(z,Y)}if(Q.status===401)await this.reportFailure(G,401,$.reporterSource??"direct").catch((z)=>this.#X.onError?.(z)),Promise.resolve().then(()=>this.refresh()).catch((z)=>{if(!this.#J.signal.aborted)this.#X.onError?.(z)});return Q}async decline(X){this.#Q(),await TJ(this.#X.rosterPath,X),this.#Y=await _9(this.#X.rosterPath)}async accept(X){this.#Q(),await RJ(this.#X.rosterPath,X),this.#Y=await _9(this.#X.rosterPath)}async recordQuota(X,J,$){this.#Q();let Y=await CJ(this.#X.rosterPath,{routeId:X,observation:J,credentialId:$.credentialId,accountIdentitySource:$.accountIdentitySource,...$.accountIdentity!==void 0&&{accountIdentity:$.accountIdentity},...$.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:$.expectedAccountIdentity}});if(Y)this.#Y=await _9(this.#X.rosterPath);return Y}close(){if(this.#J.signal.aborted)return;if(this.#J.abort(new $0("closed","Claustrum consumer is closed")),this.#Z)(this.#X.clearTimeoutImpl??clearTimeout)(this.#Z);this.#Z=void 0,this.#$?.close(),this.#Y=void 0}}function pZ(X){return e9.connect(X)}var cZ=$7("openai");function lZ(X){return Y7(X)}function T0(X){if(!X||X.corrupt===!0)return!1;return lZ(X.refresh)}class $1 extends Error{code="tombstone-refresh";constructor(){super("This OpenAI account was moved into the Claustrum vault by an older version of OpenAI auth and holds no local credential. Connect the vault, or sign in to the account again.");this.name="TombstoneRefreshError"}}function W7(X){if(lZ(X))throw new $1}var EP=Z0("quota"),SJ="primary",IJ="secondary",SP="app_EMoamEEZ73f0CkXaXp7hrann",IP="https://auth.openai.com";async function X3(X){W7(X.refreshToken);let J=await X.fetchImpl(`${IP}/oauth/token`,{method:"POST",signal:AbortSignal.timeout(15000),headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:X.refreshToken,client_id:SP}).toString()});if(!J.ok){let G=E5(J.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${J.status}`),{status:J.status,retryAfter:G,isRefreshError:!0})}let $=await J.json();if(!$||typeof $.access_token!=="string"||!$.access_token||typeof $.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:J.status,isRefreshError:!0});if($.refresh_token!==void 0&&typeof $.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:J.status,isRefreshError:!0});let Y=typeof $.refresh_token==="string"&&$.refresh_token?$.refresh_token:X.refreshToken;return{access:$.access_token,refresh:Y,expires:X.now()+$.expires_in*1000,expiresIn:$.expires_in}}var bP="https://chatgpt.com/backend-api/wham/usage";async function E8(X){let J=X.logger??EP,$=X.accountKey??"unknown",Y=Date.now();J.debug("wham usage fetch started",{pid:process.pid,accountId:$});try{let G=await X.fetchImpl(bP,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${X.accessToken}`,"chatgpt-account-id":X.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!G.ok){let z=E5(G.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${G.status}`),{status:G.status,retryAfter:z})}let Q=Mz(await G.json());return J.debug("wham usage fetch succeeded",{pid:process.pid,accountId:$,status:G.status,elapsedMs:Date.now()-Y}),Q}catch(G){throw J.warn("wham usage fetch failed",{pid:process.pid,accountId:$,status:typeof G?.status==="number"?G.status:"error",elapsedMs:Date.now()-Y,error:n0(G)}),G}}import{createHash as kP}from"node:crypto";var xP=globalThis.setTimeout,wP=5;function J3(X){let J=X?.quota?.checkIntervalMinutes??wP;return Math.max(1,J)*60000}function vP(X){return X?.quota?.enabled!==!1}function B7(X,J){if(!X?.resetsAt)return!1;let $=Date.parse(X.resetsAt);return Number.isFinite($)&&$<=J}function nZ(X,J,$,Y,G){if(G!==void 0&&Number.isFinite(G)&&G>$)return G;let Q=J===SJ?X?.primary:J===IJ?X?.secondary:void 0,z=Q?.resetsAt?Date.parse(Q.resetsAt):NaN;if(Number.isFinite(z)&&z>$)return z;return $+Y}function yP(X){let J=X?.quota?.minimumRemaining||{};return{primary:J.primary??J["5h"]??15,secondary:J.secondary??J["1w"]??10}}function dZ(X,J,$){if(!vP(J))return $+J3(J);let Y=yP(J),G=[];for(let Q of["primary","secondary"]){let z=X?.[Q];if(!z)continue;if(z.remainingPercent>=Y[Q])continue;let Z=z.resetsAt?Date.parse(z.resetsAt):Number.NaN;if(!Number.isFinite(Z)||Z<=$)return $+J3(J);G.push(Z)}if(!G.length)return $+J3(J);return Math.min(...G)+60000}function hP(X){if(!X?.quota?.mainQuota||!X.quota.mainQuotaCheckedAt)return null;return{quota:X.quota.mainQuota,checkedAt:X.quota.mainQuotaCheckedAt,tokenFingerprint:X.quota.mainQuotaToken}}function fP(X){let J=X?.quota?.refreshEveryNRequests;return typeof J==="number"&&Number.isFinite(J)&&J>0?Math.floor(J):0}function b6(X){return kP("sha256").update(X).digest("hex").slice(0,16)}class S8{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;configPath;constructor(X){this.storage=X.storage,this.fetchImpl=X.fetchImpl??fetch,this.configPath=X.configPath,this.now=X.now??Date.now,this.fetchQuotaFn=X.fetchQuotaFn,this.onMainQuotaFetched=X.onMainQuotaFetched,this.onApiError=X.onApiError,this.seedMainFromStorage(X.storage),this.seedMainBackoffFromStorage(X.storage)}getMain(X){if(X&&this.main&&this.mainTokenFp&&this.mainTokenFp!==b6(X))this.main=null,this.mainTokenFp=null;return this.main}getFallback(X,J){let $=this.fallbacks.get(X)??null;if(!J||!$)return $;if(this.fallbackTokenFps.get(X)!==b6(J))return this.fallbacks.delete(X),this.fallbackTokenFps.delete(X),null;return $}getAllFallbacks(){return this.fallbacks}setMain(X,J,$,Y=!1){if(!Y&&!iZ(J.quota))return;if(this.mainTokenFp=b6(X),$&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)this.clearRateLimited("main");if($)this.mainQuotaAccountId=$;if(this.main=J,bJ(J.quota))this.clearRateLimited("main")}peekMainForPolicy(X){if(X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)return null;return this.main}peekFallbackForPolicy(X,J){let $=this.fallbacks.get(X)??null;if(J&&$?.accountId&&$.accountId!==J)return null;return $}setFallback(X,J,$,Y=!1,G){if(!Y&&!iZ(J.quota))return;let Q=this.fallbacks.get(X)?.accountId;if(G&&Q&&G!==Q)this.clearRateLimited(X);let z=G??Q;if(this.fallbacks.set(X,{...J,accountId:z}),$)this.fallbackTokenFps.set(X,b6($));else this.fallbackTokenFps.delete(X);if(bJ(J.quota))this.clearRateLimited(X)}markRateLimited(X,J){let $=this.rateLimitedUntilMap.get(X);if($!==void 0&&$>J)return;this.rateLimitedUntilMap.set(X,J)}isRateLimited(X){let J=this.rateLimitedUntilMap.get(X);return J!==void 0&&this.now()<J}rateLimitedUntil(X){return this.rateLimitedUntilMap.get(X)}clearRateLimited(X){this.rateLimitedUntilMap.delete(X)}async refreshMain(X){let J=b6(X);if(this.mainTokenFp&&this.mainTokenFp!==J)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===J)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=J,this.inflightMain=this._fetchMain(X),this.inflightMain}async refreshFallback(X,J){let $=S8.fallbackInflightKey(X,J),Y=this.inflightFallbacks.get($);if(Y)return Y;if(this.isFallbackBackedOff(X,J)){let Q=this.getFallback(X,J);if(Q)return Q.quota;throw Error("Quota API rate-limited — try again later")}let G=this._fetchFallback(X,J);return this.inflightFallbacks.set($,G),G}async refreshAllFallbacks(X){let J=this.now();for(let $ of X){if($.enabled===!1)continue;if(T0($)||!$.access)continue;let Y=this.getFallback($.id,$.access);if(Y&&J<Y.refreshAfter)continue;try{await this.refreshFallback($.id,$.access)}catch{}}}refreshMainInBackground(X){let J=b6(X);if(this.inflightMain&&this.inflightMainFp===J)return;if(this.isBackedOff())return;this.refreshMain(X).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(X,J){let $=this.getFallback(X,J);if(!$)return!0;return this.now()>=$.refreshAfter}shouldRefreshOnRequestCount(X){let J=fP(this.storage);if(J<=0)return!1;return X>0&&X%J===0}needsRefresh(X){return this.isMainStale()||this.shouldRefreshOnRequestCount(X)}updateStorage(X){this.storage=X,this.seedMainFromStorage(X),this.seedMainBackoffFromStorage(X)}seedMainFromStorage(X,J){let $=hP(X);if(!$)return;let Y=J?b6(J):null;if(Y&&$.tokenFingerprint&&$.tokenFingerprint!==Y)return;let G={quota:$.quota,refreshAfter:dZ($.quota,X,$.checkedAt),checkedAt:$.checkedAt};if(this.main&&this.main.checkedAt>=G.checkedAt&&(!Y||!this.mainTokenFp||this.mainTokenFp===Y))return;if(this.main=G,this.mainTokenFp=$.tokenFingerprint??null,X?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==X.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=X.mainAccountId}}seedMainBackoffFromStorage(X){let J=X?.quota?.mainLastQuotaApiError;this.mainLastApiError=J&&u1(J,this.now())?J:void 0}seedFallbacksFromAccounts(X){let J=J3(this.storage);for(let $ of X){if($.enabled===!1)continue;if(!$.quota)continue;let Y=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(Y<=0)continue;let G=this.getFallback($.id,$.access);if(G&&G.checkedAt>=Y)continue;this.setFallback($.id,{quota:$.quota,refreshAfter:Y+J,checkedAt:Y},$.access,!1,$.accountId)}}isBackedOff(){return u1(this.mainLastApiError,this.now())}isFallbackBackedOff(X,J){if(J){if(this.fallbackErrorTokenFps.get(X)!==b6(J))return!1}return u1(this.fallbackApiErrors.get(X),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(X,J){return JSON.stringify([X,b6(J)])}static quotaLockName(X){return`opencode-fallback-quota-refresh-${X.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(X){let J=async()=>{let Y=this.now()-this.lastApiCallAt;if(Y<S8.API_CALL_GAP_MS)await new Promise((G)=>{let Q=xP(G,S8.API_CALL_GAP_MS-Y);if(typeof Q==="object"&&"unref"in Q)Q.unref()});return this.lastApiCallAt=this.now(),X()},$=this.apiGate.then(J,J);return this.apiGate=$.catch(()=>{}),$}async _fetchMain(X){let J=b6(X);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let $=await g0({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!$){let Y=this.main;if(Y&&this.now()<Y.refreshAfter)return Y.quota;throw Error("Quota refresh is already in progress")}try{let Y=this.now(),G=await this._fetchQuota(X),Q=this.now();if(this.mainTokenFp=b6(X),this.main={quota:G,refreshAfter:dZ(G,this.storage,Q),checkedAt:Q},bJ(G))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(G,Q,this.mainTokenFp,Y),G}catch(Y){throw this._handleMainFetchError(Y),Y}finally{await $.release()}}finally{if(this.inflightMainFp===J)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(X,J){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(X,J)){let Y=this.getFallback(X,J);if(Y)return Y.quota;throw Error("Quota API rate-limited — try again later")}let $=await g0({name:S8.quotaLockName(X),ttlMs:30000,path:this.configPath});if(!$){let Y=this.getFallback(X,J);if(Y&&this.now()<Y.refreshAfter)return Y.quota;throw Error("Quota refresh is already in progress")}try{let Y=await this._fetchQuota(J),G=this.now();return this.setFallback(X,{quota:Y,refreshAfter:G+J3(this.storage),checkedAt:G},J,!0),this.fallbackApiErrors.delete(X),this.fallbackErrorTokenFps.delete(X),Y}finally{await $.release()}}catch($){throw this._handleFallbackFetchError(X,J,$),$}finally{this.inflightFallbacks.delete(S8.fallbackInflightKey(X,J))}})}async _fetchQuota(X){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:X,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError(X){return X?.status===401}_handleMainFetchError(X){if(S8.isAuthError(X))return;this.mainLastApiError=u4({error:X,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(X,J,$){if(S8.isAuthError($))return;let Y=b6(J),G=this.fallbackErrorTokenFps.get(X)===Y?this.fallbackApiErrors.get(X):void 0;this.fallbackApiErrors.set(X,u4({error:$,now:this.now(),previous:G})),this.fallbackErrorTokenFps.set(X,Y)}}function iZ(X){return Boolean(X.primary||X.secondary)}function bJ(X){let{primary:J,secondary:$}=X;if(!J&&!$)return!1;if(J&&J.usedPercent>=100)return!1;if($&&$.usedPercent>=100)return!1;return!0}import{readFile as eP}from"node:fs/promises";var Y1=Z0("refresh"),V7=Z0("accounts"),cP=1e4,lP=15000,kJ=50;function v0(X){return X.type==="oauth"&&X.corrupt!==!0}function dP(X){let J=X?.trim();if(!J)return!1;try{let $=new URL(J);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}var o1="floors-v1";function YW(X){return X.costZeroing?.enabled!==!1}class U7 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(X){super(`Fallback account ${X} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var iP=[401,403,429],sZ={primary:0,secondary:0},nP=!1,A9={primary:5,secondary:10};function Q0(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}var sP=new Set(["__proto__","constructor","prototype"]);function I8(X){return X.length>0&&!sP.has(X)}function aP(X){return X instanceof U7||Q0(X)&&X.name==="AccountRemovedDuringRefreshError"&&X.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function H7(X){return{id:typeof X.id==="string"&&X.id.trim()?X.id.trim():uP(),label:typeof X.label==="string"?X.label:void 0,enabled:typeof X.enabled==="boolean"?X.enabled:void 0,addedAt:typeof X.addedAt==="number"?X.addedAt:void 0,lastUsed:typeof X.lastUsed==="number"?X.lastUsed:void 0,accountId:typeof X.accountId==="string"?X.accountId:void 0}}function aZ(X){if(!Q0(X))return;if(typeof X.message!=="string")return;let J=Number(X.checkedAt);if(!Number.isFinite(J))return;let $=Number(X.nextRetryAt),Y=Number(X.retryCount);return{message:X.message,checkedAt:J,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(Y)?Y:void 0,tokenHash:typeof X.tokenHash==="string"?X.tokenHash:void 0}}function oP(X){if(!Q0(X))return;let J={};for(let G of["primary","secondary"]){let Q=X[G];if(!Q0(Q))continue;let z=Number(Q.usedPercent),Z=Number(Q.remainingPercent),W=Number(Q.checkedAt);if(!Number.isFinite(z)||!Number.isFinite(Z)||!Number.isFinite(W))continue;let B=typeof Q.windowMinutes==="number"?Q.windowMinutes:Number.NaN;J[G]={usedPercent:z,remainingPercent:Z,checkedAt:W,resetsAt:typeof Q.resetsAt==="string"?Q.resetsAt:void 0,...Number.isFinite(B)&&B>0?{windowMinutes:B}:{}}}for(let G of["resetCreditsAvailable","resetCreditsApplicable"]){let Q=typeof X[G]==="number"?X[G]:Number.NaN;if(Number.isFinite(Q)&&Q>=0)J[G]=Q}let $=X.spendControl;if(Q0($)){let G=Number($.limit),Q=Number($.used),z=Number($.remaining),Z=Number($.usedPercent),W=Number($.remainingPercent);if(Number.isFinite(G)&&Number.isFinite(Q)&&Number.isFinite(z)&&Number.isFinite(Z)&&Number.isFinite(W)&&typeof $.reached==="boolean")J.spendControl={limit:G,used:Q,remaining:z,usedPercent:Z,remainingPercent:W,resetsAt:typeof $.resetsAt==="string"?$.resetsAt:void 0,unit:typeof $.unit==="string"?$.unit:void 0,source:typeof $.source==="string"?$.source:void 0,reached:$.reached}}let Y=X.credits;if(Q0(Y)&&typeof Y.hasCredits==="boolean"&&typeof Y.unlimited==="boolean"&&typeof Y.overageLimitReached==="boolean"){let G=Number(Y.balance);J.credits={hasCredits:Y.hasCredits,unlimited:Y.unlimited,overageLimitReached:Y.overageLimitReached,...Number.isFinite(G)?{balance:G}:{}}}return Object.keys(J).length?J:void 0}function rP(X){if(!Q0(X))return null;if(X.type==="api"){let J=typeof X.baseURL==="string"?X.baseURL.trim():"",$=typeof X.apiKey==="string"?X.apiKey.trim():"";if(!dP(J))return null;let Y=X.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...H7(X),type:"api",apiKey:$||void 0,baseURL:J,authHeader:Y}}if(X.type!=="oauth")return null;if(X.corrupt===!0){if(typeof X.id!=="string"||!X.id.trim())return null;return{...H7(X),type:"oauth",corrupt:!0}}if(typeof X.refresh!=="string"||!X.refresh.trim()){if(!Object.hasOwn(X,"refresh")||typeof X.id!=="string"||!X.id.trim())return null;return{...H7(X),type:"oauth",corrupt:!0}}return{...H7(X),type:"oauth",access:typeof X.access==="string"?X.access:void 0,refresh:X.refresh,expires:typeof X.expires==="number"?X.expires:void 0,lastRefreshedAt:typeof X.lastRefreshedAt==="number"?X.lastRefreshedAt:void 0,lastRefreshError:aZ(X.lastRefreshError),lastQuotaRefreshError:aZ(X.lastQuotaRefreshError),quota:oP(X.quota)}}function tP(X){if(!Q0(X))return;let J=Object.create(null);for(let[$,Y]of Object.entries(X)){if(!I8($)||!Q0(Y))continue;let G={};if(Q0(Y.inFlight))G.inFlight={...Y.inFlight};if(Q0(Y.lastOutcome)&&typeof Y.lastOutcome.code==="string"&&Y.lastOutcome.code.length>0&&typeof Y.lastOutcome.at==="number"&&Number.isFinite(Y.lastOutcome.at))G.lastOutcome={code:Y.lastOutcome.code,at:Y.lastOutcome.at,...Q0(Y.lastOutcome.previousOutcome)&&typeof Y.lastOutcome.previousOutcome.code==="string"&&Y.lastOutcome.previousOutcome.code.length>0&&typeof Y.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(Y.lastOutcome.previousOutcome.at)?{previousOutcome:{code:Y.lastOutcome.previousOutcome.code,at:Y.lastOutcome.previousOutcome.at}}:{}};if(typeof Y.cooldownUntil==="number"&&Number.isFinite(Y.cooldownUntil))G.cooldownUntil=Y.cooldownUntil;if(Object.keys(G).length>0)J[$]=G}return Object.keys(J).length>0?J:void 0}var oZ=new Set;function GW(X){if(X.length===0)return;let J=JSON.stringify([...X].sort());if(oZ.has(J))return;oZ.add(J),V7.warn("account load-dropped, preserved on disk",{droppedIds:X})}function QW(X){if(!Q0(X)||!Array.isArray(X.accounts))return null;let J=X.accounts,$=J.map(rP).filter((Y)=>Y!=null);if($.length<J.length){let Y=new Set;for(let z of J)if(Q0(z)&&typeof z.id==="string"&&z.id.trim())Y.add(z.id.trim());let G=new Set($.map((z)=>z.id)),Q=[];for(let z of Y)if(!G.has(z))Q.push(z);GW(Q)}return{version:1,main:{type:"opencode",provider:"openai"},routing:Q0(X.routing)?X.routing:void 0,fallbackOn:Array.isArray(X.fallbackOn)?X.fallbackOn.filter((Y)=>Number.isInteger(Y)):void 0,refresh:Q0(X.refresh)?X.refresh:void 0,quota:Q0(X.quota)?X.quota:void 0,reset:tP(X.reset),dump:Q0(X.dump)?X.dump:void 0,costZeroing:Q0(X.costZeroing)?X.costZeroing:void 0,killswitch:Q0(X.killswitch)?X.killswitch:void 0,logging:Q0(X.logging)?X.logging:void 0,cachekeep:Q0(X.cachekeep)?X.cachekeep:void 0,cacheKeep:Q0(X.cacheKeep)?X.cacheKeep:void 0,mainAccountId:typeof X.mainAccountId==="string"?X.mainAccountId:void 0,accounts:$}}function zW(X){if(!("claustrum"in X))return X;let{claustrum:J,...$}=X;return $}async function T9(X){try{return{exists:!0,value:JSON.parse(await eP(X,"utf8"))}}catch(J){if(J.code==="ENOENT")return{exists:!1,value:null};throw J}}function R9(X){return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0))}async function gJ(X){let J;try{J=(await T9(X)).value}catch{return null}return mJ(J)}function ZW(X,J){if(!Q0(X))return X;let $=Q0(J)?J:{},Y=Q0($.main)?$.main:void 0,G=Q0($.accounts)?$.accounts:{},Q=Q0(X.quota)?X.quota:{},z=Q0(X.refresh)?X.refresh:{},Z=Y??Q,W=Y??z,H=z.mainRefreshLeaseId!==void 0?{id:z.mainRefreshLeaseId,until:z.mainRefreshLeaseUntil,tokenHash:z.mainRefreshLeaseTokenHash}:{id:W.refreshLeaseId,until:W.refreshLeaseUntil,tokenHash:W.refreshLeaseTokenHash},j=Array.isArray(X.accounts)?X.accounts.map((q)=>{if(!Q0(q))return q;let K=typeof q.id==="string"&&Q0(G[q.id])?G[q.id]:{};return{...q,...K}}):void 0;return WW({...X,refresh:R9({...z,mainLastRefreshError:z.mainLastRefreshError??W.lastRefreshError,mainRefreshLeaseId:H.id,mainRefreshLeaseUntil:H.until,mainRefreshLeaseTokenHash:H.tokenHash}),quota:R9({...Q,mainQuota:Z.quota,mainQuotaCheckedAt:Z.quotaCheckedAt,mainQuotaToken:Z.quotaToken,mainLastQuotaApiError:Z.lastQuotaApiError}),accounts:j})}async function b0(X){let J=await T9(X.configPath);if(!J.exists)return null;let $=await T9(X.statePath);return QW(ZW(J.value,$.value))}function WW(X){return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0))}function XO(X){return R9({id:X.id,label:X.label,type:X.type,corrupt:X.type==="oauth"&&X.corrupt===!0?!0:void 0,enabled:X.enabled,addedAt:X.addedAt,accountId:X.accountId,baseURL:X.type==="api"?X.baseURL:void 0,authHeader:X.type==="api"?X.authHeader:void 0})}function BW(X){if(X.type==="api")return R9({apiKey:X.apiKey,lastUsed:X.lastUsed});if(X.corrupt)return{};return R9({access:X.access,refresh:X.refresh,expires:X.expires,lastUsed:X.lastUsed,lastRefreshedAt:X.lastRefreshedAt,lastRefreshError:X.lastRefreshError,lastQuotaRefreshError:X.lastQuotaRefreshError,quota:X.quota})}function K7(X){return Math.max(X?.primary?.checkedAt??0,X?.secondary?.checkedAt??0)}function $3(X,J,$){if($ in J)X[$]=J[$];else delete X[$]}function JO(X,J){return X.access===J.access&&X.refresh===J.refresh&&X.expires===J.expires&&X.lastRefreshedAt===J.lastRefreshedAt}function $O(X,J){if(!JO(X,J))return J;if(!("lastRefreshError"in J))return X;if(!("lastRefreshError"in X))return J;return(J.lastRefreshError?.checkedAt??0)>(X.lastRefreshError?.checkedAt??0)?J:X}var YO=300000;function rZ(X,J){if(X===void 0)return 0;return X>J+YO?0:X}function GO(X,J,$){let Y=Date.now(),G=rZ(J.lastRefreshedAt,Y),Q=rZ($.lastRefreshedAt,Y),z=J.expires??0,Z=$.expires??0,W=Q>G?$:G>Q?J:Z>z?$:z>Z?J:$O(J,$);$3(X,W,"access"),$3(X,W,"refresh"),$3(X,W,"expires"),$3(X,W,"lastRefreshedAt"),$3(X,W,"lastRefreshError")}function QO(X,J){if(!Q0(X))return J;let $=X,Y=K7($.quota),G=K7(J.quota),Q=Y>G,z=Q?{...$,...J,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...J};if(!Q&&!("lastQuotaRefreshError"in J))delete z.lastQuotaRefreshError;if(!("lastRefreshError"in J))delete z.lastRefreshError;if(typeof $.lastUsed==="number"&&(typeof J.lastUsed!=="number"||$.lastUsed>J.lastUsed))z.lastUsed=$.lastUsed;return GO(z,$,J),z}function HW(X){let J=X.refresh?R9({enabled:X.refresh.enabled,refreshBeforeExpiryMinutes:X.refresh.refreshBeforeExpiryMinutes}):void 0,$=X.quota?R9({enabled:X.quota.enabled,checkIntervalMinutes:X.quota.checkIntervalMinutes,refreshEveryNRequests:X.quota.refreshEveryNRequests,minimumRemaining:X.quota.minimumRemaining,failClosedOnUnknownQuota:X.quota.failClosedOnUnknownQuota}):void 0;return WW({version:1,main:X.main,routing:X.routing,fallbackOn:X.fallbackOn,refresh:J,quota:$,reset:X.reset,dump:X.dump,costZeroing:X.costZeroing,killswitch:X.killswitch,logging:X.logging,cachekeep:X.cachekeep,cacheKeep:X.cacheKeep,mainAccountId:X.mainAccountId,accounts:X.accounts.map(XO)})}async function G3(X,J=!1){let $=Date.now(),Y=$+lP,G=0;while(Date.now()<=Y){G++;let Z=await g0({name:"save",ttlMs:cP,path:X,renew:J});if(Z)return Z;let W=Y-Date.now();if(W<=0)break;await pP(Math.min(kJ+jW(kJ),W))}let Q=Date.now()-$,z=Math.round(Q/Math.max(1,G));throw Error(`Timed out after ${Q}ms waiting for the account store lock on ${X} (${G} attempts, ~${z}ms apart; retry interval is ${kJ}ms). A gap near the retry interval means lock contention; a much larger one means this process's event loop was saturated and the wait expired without getting scheduled.`)}function VW(X){let J=Object.fromEntries(X.accounts.map(($)=>[$.id,BW($)]));return{version:1,main:R9({quota:X.quota?.mainQuota,quotaCheckedAt:X.quota?.mainQuotaCheckedAt,quotaToken:X.quota?.mainQuotaToken,lastQuotaApiError:X.quota?.mainLastQuotaApiError,lastRefreshError:X.refresh?.mainLastRefreshError,refreshLeaseId:X.refresh?.mainRefreshLeaseId,refreshLeaseUntil:X.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:X.refresh?.mainRefreshLeaseTokenHash}),accounts:J}}function mJ(X){if(!Q0(X)||!Array.isArray(X.accounts))return null;let J=new Set;for(let $ of X.accounts){if(!Q0($))continue;if(typeof $.id!=="string")continue;let Y=$.id.trim();if(!Y)continue;J.add(Y)}return J}function zO(X,J,$,Y){if(!Q0(X)||!Array.isArray(X.accounts))return{preservedRawEntries:[],preservedIds:[]};let G=[],Q=[];for(let z of J){if($.has(z))continue;if(Y.has(z))continue;let Z=X.accounts.find((W)=>Q0(W)&&typeof W.id==="string"&&W.id.trim()===z);if(!Z)continue;G.push(Z),Q.push(z)}return{preservedRawEntries:G,preservedIds:Q}}function ZO(X){if(!Array.isArray(X))return[];let J=[];for(let $ of X){if(!Q0($))continue;if(typeof $.id!=="string")continue;J.push($.id)}return J}function WO(X,J,$){let Y=mJ(X);if(Y===null)return[];let{preservedRawEntries:G,preservedIds:Q}=zO(X,Y,J,$);return GW(Q),G}async function j7(X,J,$={}){let{configPath:Y,statePath:G}=J,Q=await G3(Y);try{let z=await G3(G);try{let Z=await T9(Y),W=await T9(G),B=(Z.exists?QW(ZW(Z.value,W.value)):null)??BO(),H=new Set(B.accounts.map((N)=>N.id)),U=mJ(Z.value)??new Set,j=X(B,{rawRosterIds:[...U],loadedRosterIds:[...H]})??B,q=new Set($.allowDrop??[]),K=WO(Z.value,H,q),L=HW(j),F=new Set((Array.isArray(L.accounts)?L.accounts:[]).map((N)=>Q0(N)&&typeof N.id==="string"?N.id.trim():"").filter(Boolean)),O=K.filter((N)=>{if(!Q0(N))return!1;if(typeof N.id!=="string")return!1;return!F.has(N.id.trim())}),_=Q0(Z.value)?Z.value:{},C={...zW(_),...L,accounts:[...Array.isArray(L.accounts)?L.accounts:[],...O]};if($.canWrite&&!$.canWrite())return B;if(await O6(Y,C),$.canWrite&&!$.canWrite())return B;return await O6(G,VW(j)),V7.debug("account config written",{accountCount:C.accounts.length,accountIds:ZO(C.accounts)}),j}finally{await z.release()}}finally{await Q.release()}}function BO(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function HO(X,J){X.main=X.main??{};let $=typeof X.main.quotaCheckedAt==="number"?X.main.quotaCheckedAt:K7(X.main.quota),Y=typeof J.quota?.mainQuotaCheckedAt==="number"?J.quota.mainQuotaCheckedAt:K7(J.quota?.mainQuota);if($>Y)return;X.main.quota=J.quota?.mainQuota,X.main.quotaCheckedAt=J.quota?.mainQuotaCheckedAt,X.main.quotaToken=J.quota?.mainQuotaToken,X.main.lastQuotaApiError=J.quota?.mainLastQuotaApiError}function VO(X,J){X.main=X.main??{},X.main.lastRefreshError=J.refresh?.mainLastRefreshError,X.main.refreshLeaseId=J.refresh?.mainRefreshLeaseId,X.main.refreshLeaseUntil=J.refresh?.mainRefreshLeaseUntil,X.main.refreshLeaseTokenHash=J.refresh?.mainRefreshLeaseTokenHash}function wJ(X){if(Array.isArray(X))return X.map(wJ);if(!Q0(X))return X;return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0).map(([J,$])=>[J,wJ($)]))}async function uJ(X,J,$={mainQuota:!0,mainRefresh:!0,accounts:!0},Y){let G=J.statePath,Q=await G3(G);try{let z=(await T9(G)).value,Z=Q0(z)?{...z,version:1}:{version:1};if($.mainQuota)HO(Z,X);if($.mainRefresh)VO(Z,X);if($.accounts){let W=$.accounts===!0?null:new Set($.accounts),B=await gJ(J.configPath);Z.accounts={...Q0(Z.accounts)?Z.accounts:{}};for(let H of X.accounts){if(W&&!W.has(H.id))continue;if(B&&!B.has(H.id))continue;Z.accounts[H.id]=QO(Z.accounts[H.id],BW(H))}if(W){for(let H of W)if(!X.accounts.some((U)=>U.id===H))delete Z.accounts[H]}if(B){for(let H of Object.keys(Z.accounts))if(!B.has(H))delete Z.accounts[H]}}if(Y&&!Y())return;await O6(G,wJ(Z))}finally{await Q.release()}}function pJ(X){return X?.fallbackOn?.length?X.fallbackOn:iP}function z3(X,J){return pJ(J).includes(X)}function UO(X){let J=X?.quota?.minimumRemaining||{};return{primary:J.primary??J["5h"]??sZ.primary,secondary:J.secondary??J["1w"]??sZ.secondary}}function vJ(X){return X?.quota?.enabled!==!1}function Q3(X){return X?.quota?.failClosedOnUnknownQuota??nP}function Z3(X,J,$=Date.now()){if(!vJ(J))return!0;if(!X)return!Q3(J);let Y=UO(J),G=Q3(J);for(let Q of["primary","secondary"]){let z=X[Q];if(!z)continue;if(B7(z,$)){if(G)return!1;continue}if(z.remainingPercent<Y[Q])return!1}return!0}function Y9(X){return X?.killswitch?.enabled===!0}function tZ(X){return{primary:X?.primary??X?.["5h"]??A9.primary,secondary:X?.secondary??X?.["1w"]??A9.secondary}}function q7(X){return X?.cacheKeep??X?.cachekeep}function eZ(X){return typeof X==="number"&&Number.isFinite(X)?X:0}function n6(X,J){if(!X?.killswitch)return A9;if(X.killswitch.schema===o1){let{accounts:$,defaults:Y}=X.killswitch,G=J??"main",Q=Q0($)&&Object.hasOwn($,G)&&Q0($[G])?$[G]:Q0(Y)?Y:void 0;return{primary:eZ(Q?.primary),secondary:eZ(Q?.secondary)}}if(J&&X.killswitch.accounts?.[J])return tZ(X.killswitch.accounts[J]);return tZ(X.killswitch.main)}function Q1(X,J,$,Y=Date.now()){if(!Y9(J))return!0;if(!X)return!Q3(J);let G=n6(J,$),Q=Q3(J);for(let z of["primary","secondary"]){let Z=X[z];if(!Z)continue;if(B7(Z,Y)){if(Q)return!1;continue}if(Z.remainingPercent<G[z])return!1}return!0}function UW(X,J,$,Y){if(!Y9(Y))return 300;let G=[],Q=[{accountId:void 0,quota:X},...J];for(let{accountId:Z,quota:W}of Q){if(!W)continue;let B=n6(Y,Z),H=[],U=!1;for(let j of["primary","secondary"]){let q=W[j];if(!q||B7(q,$))continue;if(q.remainingPercent>=B[j])continue;let K=q.resetsAt?Date.parse(q.resetsAt):NaN;if(!Number.isFinite(K)||K<=$){U=!0;break}H.push(K)}if(U||H.length===0)continue;G.push(Math.max(...H))}if(G.length===0)return 300;let z=Math.min(...G);return Math.max(1,Math.ceil((z-$)/1000))}function XW(X){return typeof X.version==="number"&&Array.isArray(X.accounts)}async function KW(X,J){let{configPath:$,statePath:Y}=J;if(!X)return;try{let Q=await T9($);if(Q.exists&&Q0(Q.value)&&XW(Q.value))return}catch{}let G=await G3($);try{let Q=await G3(Y);try{let z=await T9($);if(z.exists&&Q0(z.value)){if(XW(z.value))return}if(!X)return;let Z={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(X.access){let H=z8({id_token:"",access_token:X.access,refresh_token:X.refresh});if(H)Z.mainAccountId=H}let W=z.exists&&Q0(z.value)?z.value:{},B={...zW(W),...HW(Z)};await O6($,B),await O6(Y,VW(Z))}finally{await Q.release()}}finally{await G.release()}}function KO(X){return X?.refresh?.enabled!==!1}function cJ(X){return(X?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function jW(X){return Math.floor(Math.random()*(X+1))}function G1(X,J,$){return!X.access||!X.expires||X.expires-$<=cJ(J)}function jO(X,J){return Boolean(X.access&&typeof X.expires==="number"&&X.expires>J)}function $9(X,J){return Boolean(X?.mainAccountId&&J.accountId&&J.accountId===X.mainAccountId)}class qW extends Error{constructor(X){super(`Refusing to refresh account ${X}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}var NW="common-auth-placeholder:v1:openai",V8="main";function R6(X){return Q0(X)&&X.type==="oauth"&&(X.refresh===NW||X.refresh===cZ)}function G9(X){return X?.accounts.find((J)=>J.id===V8&&J.enabled!==!1&&v0(J))}function lJ(X){if(!X)return X;return{...X,accounts:X.accounts.filter((J)=>J.id!==V8)}}function k6(X,J){let $=X.accounts.findIndex((Y)=>Y.id===J.id);if($!==-1)X.accounts[$]=J}function Y3(X){return X instanceof Error?X.message:String(X)}function yJ(X,J,$){if(J instanceof $1)return;X.lastRefreshError=m1({error:J,now:$,refreshToken:X.refresh,previous:X.lastRefreshError})}function xJ(X,J,$){if(J instanceof $1)return;if(X.lastQuotaRefreshError=u4({error:J,now:$,previous:X.lastQuotaRefreshError}),J?.isRefreshError===!0)yJ(X,J,$)}function JW(X,J){if(!X)return!1;if(!X.resetsAt)return!0;let $=Date.parse(X.resetsAt);return Number.isFinite($)?$>J:!0}function qO(X,J){if(!X)return!1;return JW(X.primary,J)||JW(X.secondary,J)}function NO(X,J,$){if(!X)return!1;let Y=J?.quota?.checkIntervalMinutes??5,G=Math.max(1,Y)*60000,Q=Math.max(X.primary?.checkedAt??0,X.secondary?.checkedAt??0);return $-Q<G}function $W(X,J,$){return!NO(X.quota,J,$)}function LO(X,J,$,Y){return C5($)&&Z3(X.quota,J,Y)&&qO(X.quota,Y)}function DO(X){let J=X?.quota?.checkIntervalMinutes??5;return Math.max(1,J)*60000}var FO=60000,PO=60000,dJ=600000;function iJ(X){return`fallback-oauth-refresh-${mP("sha256").update(X).digest("base64url").slice(0,16)}`}var OO=1e4,MO=100,cy=globalThis.setTimeout.bind(globalThis),ly=globalThis.clearTimeout.bind(globalThis);class nJ{now;fetchImpl;paths;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor(X){this.options=X,this.now=X.now??Date.now,this.fetchImpl=X.fetchImpl??fetch,this.paths=X.paths,this.quotaManager=X.quotaManager??null,this.onFallbackStorageChanged=X.onFallbackStorageChanged}assertNotTombstoned(X){if(X)W7(X.refresh)}seedFallbackQuota(X,J){if(!this.quotaManager)return;if(!X.quota)return;let $=Math.max(X.quota.primary?.checkedAt??0,X.quota.secondary?.checkedAt??0);if($<=0)return;let Y=this.quotaManager.getFallback(X.id,X.access);if(Y&&Y.checkedAt>=$)return;this.quotaManager.setFallback(X.id,{quota:X.quota,refreshAfter:$+DO(J),checkedAt:$},X.access,!1,X.accountId)}async load(){return b0(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save(X,J){await uJ(X,this.paths,{accounts:J??!0},this.options.canWrite)}startBackgroundRefresh(){let X=async()=>{if(await this.options.backgroundRefreshPaused?.())return;if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if(X().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{X().catch(()=>{})},FO+jW(PO)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(X){let J=X!==void 0?X:await this.load();if(!J)return[];let $=[],Y=!1;for(let G of J.accounts){if(G.enabled===!1||!v0(G))continue;if($9(J,G))continue;if(T0(G))continue;let Q=!1,z=G;try{if(G1(z,J,this.now())){let Z=z.lastRefreshError;if(Z&&t0(Z,z.refresh,this.now()))throw Q=!0,Error(r8(Z,this.now()));try{z=await this.refreshAccount(z,J),Y=!0}catch(W){if(aP(W))continue;Q=!0;let B=J.accounts.find((H)=>H.id===G.id&&v0(H));if(B&&!t0(B.lastRefreshError,B.refresh,this.now()))yJ(B,W,this.now()),k6(J,B),Y=!0;throw W}}if(this.seedFallbackQuota(z,J),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(z),J))$.push(z)}catch(Z){let W=jO(z,this.now());if(Q){if(!W)continue}else if(!W)continue;if(LO(z,J,Z,this.now()))Y1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:z.id,error:Y3(Z)}),$.push(z);else if(!Q3(J))$.push(z)}}if(Y){let G=structuredClone(J);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(G)).catch((Q)=>{V7.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:Y3(Q)})})}return $}async markUsed(X){try{let J=await this.load();if(!J)return;let $=J.accounts.find((Y)=>Y.id===X.id);if(!$)return;$.lastUsed=this.now(),await this.save(J,[$.id])}catch(J){V7.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:X.id,error:Y3(J)})}}accountPassesQuotaPolicy(X,J){return Z3(X.quota,J,this.now())}quotaPolicyAccount(X){if(!this.quotaManager)return X;let J=this.quotaManager.getFallback(X.id,X.access)?.quota;return J?{...X,quota:J}:X}async refreshDueAccounts(){let X=await this.load();if(!X||!KO(X))return;let J=!1;for(let $ of X.accounts){if($.enabled===!1||!v0($))continue;if($9(X,$))continue;if(T0($))continue;if(!G1($,X,this.now()))continue;if(t0($.lastRefreshError,$.refresh,this.now()))continue;try{Y1.debug("fallback oauth background due",{pid:process.pid,accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,X),J=!0}catch(Y){Y1.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:Y3(Y)}),yJ($,Y,this.now()),k6(X,$),J=!0}}if(J)await this.save(X)}async refreshQuotaForDueAccounts(){let X=await this.load();if(!X||!vJ(X))return;if(!this.options.fetchQuotaFn)return;let J=!1;for(let $ of X.accounts){if($.enabled===!1||!v0($))continue;if($9(X,$))continue;if(T0($))continue;let Y=$;try{if(G1(Y,X,this.now())){if(t0(Y.lastRefreshError,Y.refresh,this.now()))continue;Y=await this.refreshAccount(Y,X),J=!0}if(u1(Y.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(Y,X),!(this.quotaManager?this.quotaManager.isFallbackStale(Y.id,Y.access):$W(Y,X,this.now())))continue;await this.refreshAccountQuota(Y,X),J=!0}catch(G){xJ($,G,this.now()),k6(X,$),J=!0}}if(J)await this.save(X),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(X={}){let J=await this.load(),$=[];if(!J||!vJ(J))return{storage:J,errors:$};if(!this.options.fetchQuotaFn)return{storage:J,errors:$};let Y=X.force??!1,G=!1;for(let Q of J.accounts){if(Q.enabled===!1||!v0(Q))continue;if($9(J,Q))continue;if(T0(Q))continue;let z=Q;try{if(G1(z,J,this.now())){let Z=z.lastRefreshError;if(Z&&t0(Z,z.refresh,this.now()))throw Error(r8(Z,this.now()));z=await this.refreshAccount(z,J),G=!0}if(!Y&&!$W(z,J,this.now())){if(z.lastQuotaRefreshError)z.lastQuotaRefreshError=void 0,k6(J,z),G=!0;continue}await this.refreshAccountQuota(z,J),G=!0}catch(Z){xJ(Q,Z,this.now()),k6(J,Q),G=!0,$.push({accountId:Q.id,message:Y3(Z)})}}if(G)await this.save(J);return{storage:J,errors:$}}async refreshAccount(X,J,$={}){let Y=this.refreshPromises.get(X.id);if(Y){let z=await Y;return k6(J,z),z}let G=this.refreshAccountNow(X,J,$).finally(()=>{this.refreshPromises.delete(X.id)});this.refreshPromises.set(X.id,G);let Q=await G;return k6(J,Q),Q}async waitForConcurrentFallbackRefresh(X,J,$,Y){let G=Date.now()+OO;while(Date.now()<G){await new Promise((B)=>setTimeout(B,MO));let Q=await this.load(),z=Q?.accounts.find((B)=>B.id===X.id&&v0(B));if(!z)continue;if(this.assertNotTombstoned(z),(z.access!==$.access||z.refresh!==$.refresh||(z.expires??0)>($.expires??0)+60000)&&(Y.force||!G1(z,Q,this.now())))return k6(J,z),Y1.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),z;let W=z.lastRefreshError;if(W&&t0(W,z.refresh,this.now()))throw k6(J,z),Error(r8(W,this.now()))}return null}assertNotShieldedMainRow(X,J,$){if($.asPoolMain||!J)return;if($9(X,J))throw new qW(J.id)}async refreshAccountNow(X,J,$){let Y=await this.load(),G=Y?.accounts.find((Z)=>Z.id===X.id&&v0(Z));if(this.assertNotTombstoned(G),this.assertNotShieldedMainRow(Y,G,$),G&&!$.force&&!G1(G,Y,this.now()))return k6(J,G),G;let Q=G??X,z=await g0({name:iJ(Q.id),ttlMs:dJ,path:this.paths.configPath,now:this.now,renew:!0});if(!z){Y1.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:Q.id});let Z=await this.waitForConcurrentFallbackRefresh(X,J,Q,$);if(Z)return Z;throw Error("Fallback OAuth refresh is already in progress")}try{if(Y=await this.load(),G=Y?.accounts.find((H)=>H.id===X.id&&v0(H)),this.assertNotTombstoned(G),this.assertNotShieldedMainRow(Y,G,$),G&&!$.force&&!G1(G,Y,this.now()))return k6(J,G),G;if(!G)throw new U7(X.id);Q=G;let Z=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});Y1.debug("fallback oauth refresh request start",{pid:process.pid,accountId:Q.id,force:$.force===!0,expiresInMs:Q.expires?Q.expires-this.now():void 0});let W=await Z({refreshToken:Q.refresh,fetchImpl:this.fetchImpl,now:this.now});if(Q.access=W.access,Q.refresh=W.refresh,Q.expires=W.expires,Q.lastRefreshedAt=W.expires-W.expiresIn*1000,Q.lastRefreshError=void 0,k6(J,Q),await this.save(J),!(await this.load())?.accounts.some((H)=>H.id===X.id))throw new U7(X.id);return Y1.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:Q.id,expiresInMs:Q.expires?Q.expires-this.now():void 0}),Q}finally{await z.release()}}async refreshAccountQuota(X,J){let $=X;if(this.assertNotTombstoned($),!$.access)throw Error(`Fallback account ${X.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let Y=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),G=(Q)=>this.quotaManager?this.quotaManager.refreshFallback($.id,Q):Y({accessToken:Q,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${X.id} has no access token`);let Q=await G($.access);$.quota=Q,$.lastQuotaRefreshError=void 0,k6(J,$),await this.save(J)}catch(Q){throw xJ(X,Q,this.now()),k6(J,X),Q}}}var sJ="/backend-api/wham/rate-limit-reset-credits",_O=`https://chatgpt.com${sJ}`,MW=`${sJ}/consume`,AO=`https://chatgpt.com${MW}`,TO=300000,RO=60000,CO=15000,EO=60000;function r1(X){return{configPath:X.configPath,statePath:X.statePath}}class s6 extends Error{kind;cooldownUntil;constructor(X,J,$){super(J);this.name="ResetRedemptionError",this.kind=X,this.cooldownUntil=$}}class z1 extends Error{kind;status;constructor(X,J,$){super(J);this.name="ResetCreditError",this.kind=X,this.status=$}}function _W(X,J,$){return{authorization:`Bearer ${X}`,...$?{"chatgpt-account-id":$}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":J}}function L7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function AW(X){if(!X)return;return{...X.inFlight?{inFlight:{...X.inFlight}}:{},...X.lastOutcome?{lastOutcome:{...X.lastOutcome}}:{},...X.cooldownUntil!==void 0?{cooldownUntil:X.cooldownUntil}:{}}}function D7(X){if(!L7(X)||typeof X.redeemRequestId!=="string"||X.redeemRequestId.length===0||typeof X.creditId!=="string"||X.creditId.length===0||typeof X.startedAt!=="number"||!Number.isFinite(X.startedAt)||X.chatgptAccountId!==void 0&&(typeof X.chatgptAccountId!=="string"||X.chatgptAccountId.length===0))return;return{redeemRequestId:X.redeemRequestId,creditId:X.creditId,startedAt:X.startedAt,...typeof X.chatgptAccountId==="string"?{chatgptAccountId:X.chatgptAccountId}:{},...TW(X.rejectedStatus)?{rejectedStatus:X.rejectedStatus}:{},...typeof X.unknownAnswers==="number"&&Number.isSafeInteger(X.unknownAnswers)&&X.unknownAnswers>0?{unknownAnswers:X.unknownAnswers}:{}}}function TW(X){return typeof X==="number"&&X>=400&&X<500&&X!==408&&X!==409&&X!==425&&X!==429}function N7(X){return X.kind==="http_error"&&TW(X.status)}function RW(X,J){return X.chatgptAccountId!==void 0&&X.chatgptAccountId!==J||X.rejectedStatus!==void 0}function SO(X,J){if(X.chatgptAccountId!==void 0&&X.chatgptAccountId!==J)throw new s6("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function CW(X){return Boolean(X&&Object.hasOwn(X,"inFlight"))}function EW(X,J){return J-X.startedAt<TO}function t1(X,J){if(!I8(J))return;return X.reset?.[J]}function SW(X){if(!X.reset)X.reset=Object.create(null);return X.reset}function IW(X,J,$){if(!I8(J))return;let Y=SW(X),G=Y[J]??{},Q=G.lastOutcome;delete G.inFlight,G.lastOutcome={code:"ambiguous_local",at:$,...Q?{previousOutcome:{code:Q.code,at:Q.at}}:{}},Y[J]=G}function bW(X,J){let $=AW(X),Y=D7(X?.inFlight);if(CW(X)&&!Y)return{kind:"corrupt",beforeState:$};if(X?.cooldownUntil!==void 0&&X.cooldownUntil>J)return{kind:"cooldown",beforeState:$,cooldownUntil:X.cooldownUntil};if(Y&&EW(Y,J))return{kind:"claim",beforeState:$,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}};if(Y)return{kind:"expired_unreconciled",beforeState:$,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}};return{kind:"fresh",beforeState:$}}async function IO(X,J){if(!I8(J))return{kind:"fresh",beforeState:void 0};let $=await X.loadAccountsFn(r1(X));return bW($?t1($,J):void 0,X.now())}async function bO(X,J){let $;if(await X.mutateAccountsFn((Y)=>{let G=X.now(),Q=t1(Y,J);if($=bW(Q,G),$.kind==="corrupt")IW(Y,J,G);return Y},r1(X)),!$)throw Error("corrupt reset state mutation did not run");return $}async function kO(X,J,$,Y){if(!I8(J))return{kind:"fresh",beforeState:void 0};let G;if(await X.mutateAccountsFn((Q)=>{let z=X.now(),Z=t1(Q,J),W=AW(Z),B=D7(Z?.inFlight);if(CW(Z)&&!B)return IW(Q,J,z),G={kind:"corrupt",beforeState:W},Q;if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>z)return G={kind:"cooldown",beforeState:W,cooldownUntil:Z.cooldownUntil},Q;if(B&&EW(B,z))return G={kind:"claim",beforeState:W,claim:{inFlight:B,selectedCredit:{id:B.creditId}}},Q;if(B&&!RW(B,Y))return G={kind:"expired_unreconciled",beforeState:W,claim:{inFlight:B,selectedCredit:{id:B.creditId}}},Q;let H=F7($);if(!H)return G={kind:"fresh",beforeState:W},Q;let U={redeemRequestId:X.randomUUID(),creditId:H.id,startedAt:z,...Y===void 0?{}:{chatgptAccountId:Y}},j=SW(Q);return j[J]={...Z,inFlight:U},G={kind:"claim",beforeState:W,claim:{inFlight:U,selectedCredit:H}},Q},r1(X)),!G)throw Error("reset claim mutation did not run");return G}async function xO(X,J,$,Y,G){if(!I8(J))return;if(!rJ(Y.kind))return wO(X,J,$,Y,G);await X.mutateAccountsFn((Q)=>{let z=t1(Q,J),Z=D7(z?.inFlight);if(!z||!Z||Z.redeemRequestId!==$.redeemRequestId||Z.creditId!==$.creditId)return Q;let W=X.now();if(delete z.inFlight,z.lastOutcome={code:Y.kind,at:W},Y.kind==="reset"||Y.kind==="already_redeemed")z.cooldownUntil=W+EO;else delete z.cooldownUntil;return Q},r1(X));return}function LW(X,J){let $=D7(X?.inFlight);return $&&$.redeemRequestId===J.redeemRequestId&&$.creditId===J.creditId?$:void 0}async function wO(X,J,$,Y,G){let Q=N7(Y)?Y.status:void 0;if(!($.chatgptAccountId===void 0&&G!==void 0)&&Q!==void 0&&Q===$.rejectedStatus){let W=await X.loadAccountsFn(r1(X));return LW(W?t1(W,J):void 0,$)}let Z;return await X.mutateAccountsFn((W)=>{Z=void 0;let B=t1(W,J),H=LW(B,$);if(!B||!H)return W;let U={...H};if(U.chatgptAccountId===void 0&&G!==void 0)U.chatgptAccountId=G;if(Q===void 0)delete U.rejectedStatus,U.unknownAnswers=(H.unknownAnswers??0)+1;else if((H.unknownAnswers??0)===($.unknownAnswers??0))U.rejectedStatus=Q;return B.inFlight=U,Z=U,W},r1(X)),Z}function W3(X,J){if(!X||X.usedPercent<100)return!1;if(!X.resetsAt)return!0;let $=Date.parse(X.resetsAt);return!Number.isFinite($)||$>J}function aJ(X,J,$){if(!(J||W3(X.primary,$)||W3(X.secondary,$)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function DW(X,J){let $=X[J];if($===void 0||$===null)return;return typeof $==="string"?$:null}function vO(X){if(!L7(X))return;let J=DW(X,"granted_at"),$=DW(X,"reset_type");if(typeof X.id!=="string"||typeof X.status!=="string"||typeof X.expires_at!=="string"||Number.isNaN(Date.parse(X.expires_at))||typeof X.is_supported_by_plan!=="boolean"||J===null||$===null)return;return{id:X.id,status:X.status,...J===void 0?{}:{grantedAt:J},expiresAt:X.expires_at,...$===void 0?{}:{resetType:$},isSupportedByPlan:X.is_supported_by_plan}}async function oJ(X,J,$){let Y;try{Y=await X(_O,{method:"GET",headers:_W(J,sJ,$),signal:AbortSignal.timeout(CO)})}catch{throw new z1("http_error","reset credit list request failed")}if(!Y.ok)throw new z1("http_error",`reset credit list request failed: ${Y.status}`,Y.status);let G;try{G=await Y.json()}catch{throw new z1("invalid_response","reset credit list response was not valid JSON",Y.status)}if(!L7(G))throw new z1("invalid_response","reset credit list response was not an object",Y.status);return{credits:(Array.isArray(G.credits)?G.credits:[]).flatMap((z)=>{let Z=vO(z);return Z===void 0?[]:[Z]}),availableCount:typeof G.available_count==="number"&&Number.isFinite(G.available_count)?G.available_count:void 0}}function F7(X){return[...X].filter(kW).sort((J,$)=>Date.parse(J.expiresAt)-Date.parse($.expiresAt))[0]}function kW(X){return X.status==="available"&&X.isSupportedByPlan&&X.resetType==="codex_rate_limits"}function xW(X){return X.filter(kW).length}function rJ(X){return X==="reset"||X==="already_redeemed"||X==="nothing_to_reset"||X==="no_credit"}async function yO(X,J,$,Y,G){let Q;try{Q=await X(AO,{method:"POST",headers:{..._W(J,MW,$),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:G,credit_id:Y}),signal:AbortSignal.timeout(RO)})}catch(B){return{kind:"ambiguous",raw:B}}let z;try{z=await Q.text()}catch(B){return Q.ok?{kind:"ambiguous",raw:B}:{kind:"http_error",raw:B,status:Q.status}}let Z=z,W=!1;try{Z=JSON.parse(z),W=!0}catch{}if(!Q.ok)return{kind:"http_error",raw:Z,status:Q.status};if(!W||!L7(Z)||!rJ(Z.code))return{kind:"ambiguous",raw:Z};return{kind:Z.code,raw:Z}}function FW(X){if(X.kind==="cooldown")throw new s6("cooldown_active","reset credit redemption is cooling down",X.cooldownUntil);throw Error(`unexpected reset state decision: ${X.kind}`)}function PW(){throw new s6("expired_unreconciled","the previous reset attempt outcome is unknown")}function OW(X,J){return{target:X,selectedCredit:void 0,beforeState:J,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function hO(X){if(X.kind==="reset"||X.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if(X.kind==="nothing_to_reset"||X.kind==="no_credit")return"The server returned a terminal no-op. No cooldown was set; a new attempt starts fresh and remains gated by fresh preconditions.";if(N7(X))return"The server refused the request. A retry within five minutes reuses the same request and credit identifiers; after that, a new attempt starts fresh and remains gated by fresh preconditions.";return"The outcome is uncertain. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing."}function fO(X,J){if(X)return"The server refused the request, but recording the refusal failed, so the saved redemption may still be treated as unknown and block a new attempt. A retry reuses the same request and credit identifiers; this does not prove the server did nothing.";if(J)return"The server refused the request, but another send of the same request had an unknown outcome, so the saved redemption still blocks a new attempt until a retry settles it. A retry reuses the same request and credit identifiers; this does not prove the server did nothing.";return"The server refused the request, and another attempt has already settled or replaced the saved redemption. A new attempt is gated by the current saved state and fresh preconditions."}async function wW(X,J){if(!I8(J.accountKey))throw new s6("invalid_account_key","the reset account key is reserved");let $=await X.resolveTarget(J.accountKey);if($.chatgptAccountId!==J.expectedChatgptAccountId)throw new s6("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Y=$.chatgptAccountId,G=$.accountKey==="main"?void 0:Y,Q=await IO(X,J.accountKey);if(Q.kind==="corrupt"){if(Q=await bO(X,J.accountKey),Q.kind==="corrupt")return OW($,Q.beforeState)}if(Q.kind==="cooldown")FW(Q);let z;if(Q.kind==="claim")z=Q.claim;else if(Q.kind==="expired_unreconciled"&&(J.retry||!RW(Q.claim.inFlight,Y))){if(!J.retry)PW();z=Q.claim}else{if(J.retry)throw new s6("retry_without_inflight","there is no active reset credit redemption to retry");let[j,q]=await Promise.all([X.fetchUsage($),oJ(X.fetchImpl,$.accessToken,G)]),K=aJ(j,X.hasActiveRateLimitMark(J.accountKey),X.now());if(!K.ok)throw new s6("not_exhausted",K.reason);if(!F7(q.credits))throw new s6("no_eligible_credit","no eligible reset credit was returned");let L=await kO(X,J.accountKey,q.credits,Y);if(L.kind==="corrupt")return OW($,L.beforeState);if(L.kind==="cooldown")FW(L);if(L.kind==="expired_unreconciled")PW();if(L.kind!=="claim")throw new s6("no_eligible_credit","no eligible reset credit was available while claiming");z=L.claim}SO(z.inFlight,Y);let Z=await yO(X.fetchImpl,$.accessToken,G,z.inFlight.creditId,z.inFlight.redeemRequestId),W,B=!1;try{W=await xO(X,J.accountKey,z.inFlight,Z,Y)}catch{B=!0}let H=B&&rJ(Z.kind),U=N7(Z)&&!B&&W?.rejectedStatus!==void 0;return{target:$,selectedCredit:z.selectedCredit,beforeState:Q.beforeState,outcome:Z,retrySafety:H?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":N7(Z)&&!U?fO(B,W):hO(Z),...U?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}function s(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}import{statSync as uO}from"node:fs";import{rm as yW}from"node:fs/promises";import{dirname as pO,join as hW}from"node:path";var vW=["primary","secondary"];function tJ(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}function B3(X){return typeof X==="number"&&Number.isFinite(X)}function gO(X,J){if(!tJ(J))return;let $=J.usedPercent;if(!B3($)||$<0||$>100)return;return{label:X,usedPercent:$,...typeof J.resetsAt==="string"?{resetsAt:J.resetsAt}:{},...B3(J.windowMinutes)&&J.windowMinutes>0?{windowMinutes:J.windowMinutes}:{}}}function mO(X){let J=X.spendControl;if(tJ(J)&&typeof J.reached==="boolean"){let $=(Y)=>B3(J[Y])?{[Y]:J[Y]}:{};return{kind:"reading",reached:J.reached,...$("remainingPercent"),...$("usedPercent"),...$("limit"),...$("used"),...$("remaining"),...typeof J.resetsAt==="string"?{resetsAt:J.resetsAt}:{},...typeof J.unit==="string"?{unit:J.unit}:{}}}if(X.spendControlCleared===!0)return{kind:"cleared"};return}function C9(X,J,$){if(!tJ(X)||!B3(J))return;let Y=[],G=[];for(let z of vW){let Z=gO(z,X[z]);if(Z)Y.push(Z);else if($)G.push({label:z})}let Q=mO(X);if(Y.length===0&&G.length===0&&!Q)return;return{checkedAt:J,...Y.length>0?{readings:Y}:{},...G.length>0?{coverage:G}:{},...Q?{budget:Q}:{}}}function b8(X){if(!Y6(X))return;let J=f0(X),$={};for(let Y of vW){let G=J.limits.find((z)=>z.label===Y&&z.kind==="reading");if(!G||!B3(G.usedPercent))continue;let Q={usedPercent:G.usedPercent,remainingPercent:100-G.usedPercent,checkedAt:G.checkedAt,...G.resetsAt!==void 0?{resetsAt:G.resetsAt}:{},...G.windowMinutes!==void 0?{windowMinutes:G.windowMinutes}:{}};$[Y]=Q}return $.primary||$.secondary?$:void 0}var Q9=Z0("vault"),cO="openai-auth",fW={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},lO={opencode:"OpenCode",pi:"Pi"};function dO(X){return VJ(cO,X)}function gW(X){return hW(pO(X),"openai-auth-vault")}function iO(X,J){return{...KJ({stateDir:X,host:J}),rosterPath:hW(X,`${J}-roster.json`)}}var mW=2000,eJ={"vault-unreachable":"Request refused locally: this host is connected to the credential vault, which could not be reached, and local accounts are not used while it is connected. Start the vault and connect accounts in it, or disconnect this host from the vault.","vault-empty":"Request refused locally: this host is connected to the credential vault, which serves it no usable OpenAI account, and local accounts are not used while it is connected. Connect accounts in the vault, or disconnect this host from the vault.","vault-refused":"Request refused locally: the credential vault did not authorize an account, and local accounts are not used while this host is connected to it. Check the accounts in the vault, or disconnect this host from the vault."};function uW(X){return X.snapshot()===void 0?"vault-unreachable":"vault-empty"}function nO(X){let J=H6(X);return J?V6(J):void 0}class X${host;name;paths;#X;#J;#z=new Map;#$;#W;#G;#Y=!1;#Z=!1;#H=Promise.withResolvers();#Q;#B="unknown";#V;constructor(X){this.#X=X,this.host=X.host,this.name=dO(X.host),this.paths=iO(X.stateDir,X.host),this.#J=new Z7({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:fW,connect:()=>this.#L(),isCustodyActive:()=>this.enrolled(),...X.reservedRouteIds?{reservedRouteIds:X.reservedRouteIds}:{},parseIdentity:nO,...X.now?{now:X.now}:{},onRoster:()=>{this.#$=void 0},onError:(J)=>this.#K("vault roster refresh failed",J),logger:Q9})}#U(){return(this.#X.connectionFile??r9)()}#q(){return{connectionFile:this.#U(),projectRoot:this.#X.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(X)=>Q9.debug("vault transport error",{errorClass:X})}}#L(){return this.#X.connectScoped?.()??pZ(this.#q())}#D(){return this.#X.connectEnrollment?.()??UJ(this.#q())}#K(X,J){this.#$=n0(J),Q9.warn(X,{host:this.host,error:this.#$})}#j(){return[this.paths.tokenPath,this.paths.statePath].map((X)=>{try{let J=uO(X);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let X=this.#j(),J=await r4(this.paths,this.name);if(X===this.#j())return this.#B=J,this.#V=X,J;return"unreadable"}enrolled(){return this.#V!==this.#j()||this.#B!=="local"}start(){if(this.#Y||this.#Z)return;this.#Y=!0;let X=async()=>{try{await this.authority(),await this.#N()}catch($){if(!this.#Z)this.#K("vault roster refresh failed",$)}if(this.#Z)return;let J=this.#X.pollIntervalMs??5000;if(J<=0)return;this.#Q=setTimeout(()=>{this.#Q=void 0,X()},J),this.#Q.unref?.()};X()}#N(){return this.#G??=this.#J.refresh().finally(()=>{this.#G=void 0,this.#H.resolve()}),this.#G}firstRoster(){return this.#H.promise}async refresh(){try{await this.authority();let X=this.#G;if(X)await X.catch(()=>{return});let J=await this.#N();return this.#$=void 0,J}catch(X){return this.#K("vault roster refresh failed",X),this.#J.snapshot()}}snapshot(){return this.#J.snapshot()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap((X)=>X.accountIdentity!==void 0?[X.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let X=new Map((this.snapshot()?.rows??[]).map((J)=>[J.routeId,J]));return this.#J.routingRows().map((J)=>{let $=X.get(J.id)?.accountIdentity;return{id:J.id,kind:J.kind==="api-key"?"api-key":"oauth",...$!==void 0?{identity:$}:{},...J.quota!==void 0?{quota:J.quota}:{}}})}owns(X){return(this.snapshot()?.rows??[]).some((J)=>J.routeId===X)}async send(X,J,$){let Y=!1;try{return await this.#J.send(X,(G)=>{return Y=!0,J(G.accessToken,G)},{site:$.site,...$.signal?{signal:$.signal}:{}})}catch(G){if(Y)throw G;this.#K("vault refused to serve an account",G);return}}async authorize(X,J={}){try{return await this.#J.authorize(X,J.signal)}catch($){this.#K("vault refused to serve an account",$);return}}async reportFailure(X,J){if(J!==401)return;try{await this.#J.reportFailure(X,401,"direct")}catch($){this.#K("vault failure report failed",$)}await this.refresh()}recordSnapshot(X,J,$,Y){let G=C9(J,(this.#X.now??Date.now)(),$);if(!G)return Promise.resolve();return this.#J.recordQuota(X,G,Y).then(()=>{},(Q)=>this.#K("vault quota write failed",Q))}async pollQuota(X){let J,$=this.#X.fetchImpl?.()??globalThis.fetch,Y=await this.send(X,async(G,Q)=>{try{let z=await E8({accessToken:G,fetchImpl:$,now:this.#X.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:X,logger:Q9});return await this.recordSnapshot(X,z,!0,Q),J=void 0,new Response(null,{status:200})}catch(z){J=n0(z);let Z=z?.status;if(typeof Z==="number")return new Response(null,{status:Z});throw z}},{site:"quota"}).catch((G)=>{J=n0(G);return});if(!Y)return{ok:!1,error:J??"vault refused"};return Y.ok?{ok:!0}:{ok:!1,error:J??`status ${Y.status}`}}requestReading(X){if(this.#z.has(X))return;let J=this.pollQuota(X).catch(($)=>{Q9.warn("vault quota poll failed",{routeId:X,error:n0($)})}).finally(()=>{this.#z.delete(X)});this.#z.set(X,J)}async pollStale(X){let J=(this.#X.now??Date.now)(),$=[];for(let Y of this.routes()){let G=sO(Y.quota);if(G!==void 0&&J-G<X)continue;$.push({id:Y.id,...await this.pollQuota(Y.id)})}return $}async decline(X){await this.#J.decline(X),Q9.info("vault account declined",{routeId:X})}async accept(X){await this.#J.accept(X),Q9.info("vault account accepted",{routeId:X})}async status(){await this.authority();let X;try{X=await o4(this.paths,this.name)}catch(J){this.#K("vault enrollment state unreadable",J),X={state:"blocked",proposedName:this.name,code:J instanceof $0?J.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:X,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#$?{lastError:this.#$}:{}}}async connectStep(){let X=await this.#D().catch((J)=>{throw new I6("vault-unreachable",`Could not reach the Claustrum vault (${this.#U()}): ${n0(J)}. Is the vault running?`)});try{let J=new J7({client:X,paths:this.paths,proposedName:this.name,...this.#X.now?{now:this.#X.now}:{}}),$=await J.status();if($.state==="denied"||$.state==="blocked")await J.resetTerminal();let Y=await J.reconcile();if(Q9.info("vault enrollment step",{host:this.host,state:Y.state}),Y.state==="approved")this.#$=void 0,await this.refresh();return Y}finally{X.close()}}waitForApproval(X={}){return this.#W??=(async()=>{let J=X.sleep??((Q)=>new Promise((z)=>setTimeout(z,Q))),$=X.pollIntervalMs??2000,Y=Date.now()+(X.timeoutMs??600000),G=await this.connectStep();while(G.state==="pending"||G.state==="busy"){if(X.onPending?.(G),Date.now()>=Y)return G;await J($),G=await this.connectStep()}return G})().finally(()=>{this.#W=void 0}),this.#W}async disconnect(){await yW(this.paths.tokenPath,{force:!0}),await yW(this.paths.statePath,{force:!0}),await this.authority(),this.#$=void 0,Q9.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(X){if(this.serves())LJ({mode:"custody",auth:X,provider:"openai"})}close(){if(this.#Z=!0,this.#H.resolve(),this.#Q)clearTimeout(this.#Q);this.#Q=void 0,this.#J.close()}}function sO(X){if(!X)return;let J=f0(X).limits.map(($)=>$.checkedAt);return J.length>0?Math.max(...J):void 0}function e1(X,J){if(J.state!=="pending")return[];if(!J.requestId)return[`The vault did not take the enrollment request yet${J.retryCode?` (${J.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${J.requestId} for ${X} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${J.requestId}`,"and let it read your OpenAI accounts with:",` ck auth grant --principal enrolled:${X} --selector-kind category --selector ${fW.category} --operation read`]}function H3(X,J,$){let Y=`${lO[X]} (${J})`;switch($.state){case"approved":return`${Y}: connected to the Claustrum vault.`;case"idle":return`${Y}: not connected to the Claustrum vault.`;case"pending":return $.requestId?`${Y}: waiting for approval of request ${$.requestId}.`:`${Y}: enrollment request not taken yet${$.retryCode?` (${$.retryCode})`:""}.`;case"denied":return`${Y}: the vault denied the enrollment request.`;case"blocked":return`${Y}: enrollment stopped (${$.code}).`;case"unavailable":return`${Y}: the vault is unavailable (${$.code}).`;case"busy":return`${Y}: another process is enrolling right now.`}}function V3(X,J){switch(J.state){case"approved":{let $=X.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${X.name}. It serves ${$} OpenAI account${$===1?"":"s"} to this host${$===0?" (grant it the openai-native category with `ck auth grant` to add some)":""}.`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${J.code}). Run Connect again to send a new request.`};case"pending":case"busy":return{ok:!1,text:[...e1(X.name,J),"Still waiting. The request stays open: run Connect again after approving it."].join(`
92
- `)};default:return{ok:!1,text:`Enrollment is ${J.state}.`}}}async function pW(X){let J=[];for(let $ of X)try{J.push(...await $.run())}catch(Y){J.push({code:"doctor-check-failed",message:`Check ${$.id} failed: ${Y instanceof Error?Y.message:String(Y)}`})}return{findings:J}}function cW(X,J){let $=[X];if(J.findings.length===0)return $.push("No problems found."),$;for(let Y of J.findings){let G=Y.repair?" (repair available)":"";$.push(`- ${Y.message}${G}`)}return $}async function lW(X,J){let $={applied:[],declined:[],failed:[]};for(let Y of J.findings){let G=Y.repair;if(!G)continue;if(!await X.confirm(`Apply repair: ${G.label}?`)){$.declined.push(Y);continue}try{await G.apply(),$.applied.push(Y)}catch(Q){$.failed.push({finding:Y,error:Q}),X.print(`Repair failed: ${G.label}: ${Q instanceof Error?Q.message:String(Q)}`)}}return $}function U3(X){let J=X.title??"Auth doctor";return{id:"doctor",label:X.label??"Auth doctor",hint:"check accounts and offer repairs",async run($){let Y=await pW(X.checks);for(let z of cW(J,Y))$.print(z);let G=Y.findings.filter((z)=>z.repair);if(G.length===0){if(Y.findings.length>0)$.print("No repairs are available.");return}let Q=await lW($,Y);$.print(`Applied ${Q.applied.length} of ${G.length} repair(s).`)}}}import{execFileSync as aO,spawn as oO}from"node:child_process";function iW(X,J=process.platform,$=aO,Y=oO){try{if(J==="win32"){let G=`Start-Process '${X.replaceAll("'","''")}'`,Q=Y("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(G,"utf16le").toString("base64")],{stdio:"ignore",windowsHide:!0});return Q.on("error",()=>{}),Q.unref(),Q.pid!==void 0}else $(J==="darwin"?"open":"xdg-open",[X],{stdio:"ignore",timeout:3000});return!0}catch{return!1}}function dW(X,J){if(X.print(""),X.print("Open this URL in your browser and complete sign-in:"),X.print(""),X.print(J.url),X.print(""),J.instructions)X.print(J.instructions),X.print("")}async function P7(X,J){let $=new AbortController,Y=await X.begin({headless:!1,signal:$.signal});Y.completion.catch(()=>{}),dW(J,Y);let G=!1;try{G=await(X.openBrowser??iW)(Y.url)!==!1}catch{G=!1}if(!G)$.abort(),J.print("Could not open a browser. Switching to device authorization."),J.print(""),Y=await X.begin({headless:!0}),dW(J,Y);return Y.completion}var B0={hide:"\x1B[?25l",show:"\x1B[?25h",up:(X=1)=>`\x1B[${X}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:(X,J)=>`\x1B[${X};${J}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function J$(X){let J=X.toString(),$=[];for(let Y=0;Y<J.length;){let G=J[Y];if(G==="\x1B"){let Q=J.slice(Y,Y+3),z=Q[1]==="["||Q[1]==="O"?Q[2]:void 0;if(z&&"ABCD".includes(z)){let W={A:"up",B:"down",C:"right",D:"left"}[z];if(W)$.push(W);Y+=3}else if(Y+1===J.length){if(Y===0)$.push("escape-start");Y+=1}else if((J[Y+1]==="["||J[Y+1]==="O")&&Y+2>=J.length)break;else Y+=1;continue}if(G==="\r"||G===`
93
- `)$.push("enter");else if(G==="\x03")$.push("escape");else if(G&&G>=" ")$.push("char");Y+=1}return $}var nW=`${String.fromCharCode(27)}\\[[0-9;]*m`,rO=new RegExp(nW,"g"),tO=new RegExp(`^${nW}`);function sW(X){return X.replace(rO,"")}function Z1(X,J){if(J<=0)return"";if(sW(X).length<=J)return X;let $=J>=3?"...":".".repeat(J),Y=Math.max(0,J-$.length),G="",Q=0,z=0;while(Q<X.length&&z<Y){if(X[Q]==="\x1B"){let Z=X.slice(Q).match(tO);if(Z){G+=Z[0],Q+=Z[0].length;continue}}G+=X[Q],Q+=1,z+=1}return G.includes("\x1B[")?`${G}${B0.reset}${$}`:G+$}function $$(){return{input:process.stdin,output:process.stdout,signals:process}}function W1(X){return X.input.isTTY===!0}function Y$(X,J=""){X.output.write(`${J}
94
- `)}var eO=50;function XM(X){if(X==="red")return B0.red;if(X==="cyan")return B0.cyan;return""}async function X4(X,J,$){if(!W1(X))throw Error("Interactive select requires a TTY terminal");if(J.length===0)throw Error("No menu items provided");let{input:Y,output:G,signals:Q}=X,z=0,Z=null,W=!1,B=0,H=()=>{let U=G.columns??80,j=G.rows??24,q=B;if($.clearScreen)G.write(B0.clearScreen+B0.moveTo(1,1));else if(q>0)G.write(B0.up(q));let K=0,L=(A)=>{G.write(`${B0.clearLine}${A}
95
- `),K+=1},F=$.lines??[],O=1+($.subtitle?3:0)+F.length+(F.length?1:0),_=Math.max(1,Math.min(J.length,j-O-2-1)),C=Math.max(0,Math.min(z-Math.floor(_/2),Math.max(0,J.length-_))),N=J.slice(C,C+_);if(L(`${B0.dim}┌ ${B0.reset}${Z1($.message,Math.max(1,U-4))}`),$.subtitle)L(`${B0.dim}│${B0.reset}`),L(`${B0.cyan}◆${B0.reset} ${Z1($.subtitle,Math.max(1,U-4))}`),L("");for(let A of F)L(`${B0.cyan}│${B0.reset} ${Z1(A,Math.max(1,U-4))}`);if(F.length)L(`${B0.cyan}│${B0.reset}`);for(let A=0;A<N.length;A++){let T=N[A];if(!T)continue;let b=C+A===z,p=XM(T.color),i=p?`${b?"":B0.dim}${p}${T.label}${B0.reset}`:b?T.label:`${B0.dim}${T.label}${B0.reset}`;if(T.hint)i+=` ${B0.dim}${T.hint}${B0.reset}`;i=Z1(i,Math.max(1,U-8)),L(b?`${B0.cyan}│${B0.reset} ${B0.green}●${B0.reset} ${i}`:`${B0.cyan}│${B0.reset} ${B0.dim}○${B0.reset} ${i}`)}let P=N.length<J.length?` (${C+1}-${C+N.length}/${J.length})`:"";L(`${B0.cyan}│${B0.reset} ${B0.dim}${Z1(`Up/Down to select | Enter: confirm | Esc: back${P}`,Math.max(1,U-6))}${B0.reset}`),L(`${B0.cyan}└${B0.reset}`);for(let A=K;A<q;A++)L("");B=K};return new Promise((U)=>{let j=Y.isRaw??!1,q=()=>{if(W)return;if(W=!0,Z)clearTimeout(Z);Y.removeListener("data",F);try{Y.setRawMode(j),Y.pause(),G.write(B0.show)}catch{}Q?.removeListener("SIGINT",L),Q?.removeListener("SIGTERM",L)},K=(O)=>{q(),U(O)},L=()=>K(null),F=(O)=>{for(let _ of J$(O)){if(W)break;if(Z)clearTimeout(Z),Z=null;switch(_){case"up":z=(z-1+J.length)%J.length,H();break;case"down":z=(z+1)%J.length,H();break;case"enter":K(J[z]?.value??null);break;case"escape":K(null);break;case"escape-start":Z=setTimeout(()=>K(null),eO);break;default:break}}};Q?.once("SIGINT",L),Q?.once("SIGTERM",L);try{Y.setRawMode(!0)}catch{q(),U(null);return}Y.resume(),G.write(B0.hide),H(),Y.on("data",F)})}async function G$(X,J,$=!1){if(!W1(X))return!1;return await X4(X,$?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:J})??!1}function aW(X){let J=W1(X);return{terminal:X,interactive:J,print:($)=>Y$(X,$),confirm:($,Y)=>G$(X,$,Y),select:async($,Y)=>J&&$.length>0?X4(X,$,Y):null}}function JM(X,J){if(X.print(J.title),J.subtitle)X.print(J.subtitle);for(let $ of J.status??[])X.print(` ${$}`);X.print(""),X.print("Actions:");for(let $ of J.actions)X.print($.hint?` - ${$.label} (${$.hint})`:` - ${$.label}`);return X.print(""),X.print("This menu needs an interactive terminal to choose an action; nothing was changed."),{status:"not-interactive"}}async function B1(X){let J=X.terminal??$$(),$=aW(J);if(!$.interactive)return JM($,X);if(X.actions.length===0)return $.print("No actions are available."),{status:"cancelled"};let Y=await X4(J,X.actions.map((G)=>({label:G.label,value:G,color:G.destructive?"red":"cyan",...G.hint?{hint:G.hint}:{}})),{message:X.title,subtitle:X.subtitle??"Select an account action",...X.status?{lines:X.status}:{},clearScreen:!0});if(!Y)return{status:"cancelled"};if(Y.destructive&&!await $.confirm(Y.confirm??`${Y.label}?`))return $.print("Cancelled; nothing was changed."),{status:"declined",action:Y.id};try{return await Y.run($),{status:"ran",action:Y.id}}catch(G){return $.print(`${Y.label} failed: ${G instanceof Error?G.message:String(G)}`),{status:"failed",action:Y.id,error:G}}}var rW="disabled from the auth menu",oW=8;async function k8(X){let J=await X.read();if(J.status==="ready")return{rows:J.rows};if(J.status==="pending-migration")return{rows:[],problem:"The account store has not been migrated yet."};return{rows:[],problem:`The account store could not be read (${J.file}: ${J.reason}).`}}async function Z$(X){let{rows:J}=await k8(X);return J.some(($)=>$.credential!==void 0)}function W$(X){let J=[];if(X.label)J.push(X.label);if(X.invalid)J.push(`invalid ${X.invalid}`);else if(!X.enabled)J.push(X.disabledReason?`disabled: ${X.disabledReason}`:"disabled");else J.push("enabled");if(!X.credential&&!X.invalid)J.push("no credential");return J.join(", ")}function $M(X){if(X.problem)return[X.problem];if(X.rows.length===0)return["No accounts yet."];let J=X.rows.slice(0,oW).map((Y)=>`${Y.id}: ${W$(Y)}`),$=X.rows.length-oW;if($>0)J.push(`... and ${$} more`);return J}function YM(X){return X instanceof Error?X.message:String(X)}async function B$(X,J,$){if(J.length===0)return X.print("There are no accounts."),null;return X.select(J.map((Y)=>({label:Y.id,value:Y,hint:W$(Y)})),{message:$})}function GM(X,J){let $=new Set(J.map((Y)=>Y.id));if(X.id&&!$.has(X.id))return X.id;for(let Y=1;;Y++){let G=`account-${Y}`;if(!$.has(G))return G}}function tW(X,J=Date.now()){let $=Y6(X.quota)?f0(X.quota):void 0,Y=O7($,{now:J,form:"full"});return(Y.length>0?Y:[_8($,{now:J})]).map((G)=>` ${G}`)}function eW(X){return{id:"add-account",label:"Add account",hint:"sign in to another account",async run(J){let $=X.login;if(!$)throw Error("No login is configured");let Y=await P7($,J),{rows:G}=await k8(X.store),Q=(X.newAccountId??GM)(Y,G),z=await X.store.add({id:Q,credential:Y.credential,...Y.identity!==void 0?{identity:Y.identity}:{},...Y.label!==void 0?{label:Y.label}:{}},X.extraLocks?{extraLocks:X.extraLocks}:{});if(z.outcome==="rotated")J.print(`That sign-in is already account ${z.id}; its credential was updated.`);else if(z.outcome==="added-disabled")J.print(`Added account ${z.id}, disabled: another enabled account is the same provider account.`);else if(z.outcome==="completed")J.print(`Finished adding account ${z.id}.`);else J.print(`Added account ${z.id}.`)}}}function XB(X){return{id:"reauthenticate",label:"Re-authenticate account",hint:"sign an account in again",async run(J){let $=X.login;if(!$)throw Error("No login is configured");let{rows:Y}=await k8(X.store),G=await B$(J,Y,"Re-authenticate which account?");if(!G)return;let Q=await P7($,J);if(Q.identity!==void 0&&G.identity!==void 0&&Q.identity!==G.identity){J.print(`That sign-in is a different account from ${G.id}; nothing was changed. Use Add account to add it.`);return}let z=Q.identity??G.identity;await X.store.replace(G.id,Q.credential,z!==void 0?{identity:z}:{},X.extraLocks?{extraLocks:X.extraLocks}:{}),J.print(`Updated the sign-in of account ${G.id}.`)}}}function JB(X){return{...X.protect?{protect:X.protect}:{},...X.extraLocks?{extraLocks:X.extraLocks}:{}}}function $B(X){return X instanceof K0&&X.kind==="row-protected"?X.message:void 0}function YB(X){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run(J){let{rows:$}=await k8(X.store),Y=await B$(J,$,"Remove which account?");if(!Y)return;if(!await J.confirm(`Remove account ${Y.id}?`)){J.print("Cancelled; nothing was changed.");return}try{await X.store.remove(Y.id,JB(X))}catch(G){let Q=$B(G);if(Q===void 0)throw G;J.print(`Account ${Y.id} was kept: ${Q}`);return}J.print(`Removed account ${Y.id}.`)}}}function Q$(X){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run(J){let{rows:$}=await k8(X.store),Y=await B$(J,$,"Enable or disable which account?");if(!Y)return;let G=X.extraLocks?{extraLocks:X.extraLocks}:{};if(Y.enabled){await X.store.disable(Y.id,X.disableReason??rW,G),J.print(`Disabled account ${Y.id}.`);return}try{await X.store.enable(Y.id,G)}catch(Q){if(Q instanceof K0&&Q.kind==="duplicate-identity"){J.print(`Account ${Y.id} stays disabled: another enabled account is the same provider account.`);return}throw Q}J.print(`Enabled account ${Y.id}.`)}}}function GB(X){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run(J){let $=await k8(X.store);if($.problem){J.print($.problem);return}if($.rows.length===0)J.print("No accounts yet.");for(let Y of $.rows)J.print(`${Y.id}: ${W$(Y)}`)}}}function z$(X){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run(J){let $=await k8(X.store);if($.problem){J.print($.problem);return}let Y=new Map,G=X.pollQuota;if(G)for(let z of $.rows){if(z.invalid||!z.credential||z.credentialEpoch===void 0){Y.set(z.id,"no usable credential");continue}try{let Z=await G(z);await X.store.recordQuota(z.id,{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},Z)}catch(Z){Y.set(z.id,YM(Z))}}let Q=await k8(X.store);if(Q.rows.length===0)J.print("No accounts yet.");for(let z of Q.rows){J.print(`${z.id}:`);let Z=Y.get(z.id);if(Z)J.print(` quota check failed: ${Z}`);for(let W of tW(z,(X.now??Date.now)()))J.print(W)}}}}function QB(X){return{id:"delete-all",label:"Delete all accounts",destructive:!0,confirm:"Delete every account? Accounts the plugin keeps are not deleted.",async run(J){let $=await k8(X.store);if($.problem){J.print($.problem);return}let Y=[],G=[];for(let Q of $.rows)try{await X.store.remove(Q.id,JB(X)),Y.push(Q.id)}catch(z){let Z=$B(z);if(Z===void 0)throw z;G.push(`${Q.id} (${Z})`)}if(J.print(`Deleted ${Y.length} account(s).`),G.length>0)J.print(`Kept: ${G.join(", ")}.`)}}}async function H$(X){return zB(X,await X.custody?.()===!0)}function zB(X,J){let $=X.doctor?.length?[U3({checks:X.doctor})]:[],Y=[...X.extraActions??[]];if(J)return[GB(X),Q$(X),z$(X),...$,...Y];return[...X.login?[eW(X),XB(X)]:[],YB(X),Q$(X),z$(X),...$,...Y,QB(X)]}async function V$(X){let J=await X.custody?.()===!0,$=zB(X,J),[Y,G]=await Promise.all([k8(X.store),X.status?.()??[]]);return B1({title:X.title,subtitle:J?"Accounts come from the vault; select an action":"Select an account action",status:[...G,...$M(Y)],actions:$,...X.terminal?{terminal:X.terminal}:{}})}function U$(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function ZB(X){return X!==void 0}function K$(X){return async(J)=>{if(!ZB(J))return X.login();if(!await X.hasCredential())return X.login(J);return await X.openMenu(J),U$()}}function x8(X){return X.authority!=="local"}async function a6(X){return{authority:await X.authority(),status:await X.status(),identities:X.identities(),routes:new Set(X.routes().map((J)=>J.id))}}async function M7(X){let J;try{return await Promise.race([Promise.resolve().then(()=>X.refresh()).then(()=>{return},($)=>$ instanceof Error?$.message:String($)),new Promise(($)=>{J=setTimeout(()=>$("Vault roster refresh did not finish within the roster wait budget."),mW)})])}finally{clearTimeout(J)}}function w8(X){return X.email||X.label||X.routeId}function WB(X,J){let $=f0(Y6(X.quota)?X.quota:void 0),Y=O7($,{now:J});return(Y.length>0?Y:[_8($,{now:J})]).map((G)=>` ${G}`)}var K3="Accounts are managed in the vault with ck. Disconnect to use local accounts.",v8="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function BB(X){let J=[...X.label?[X.label]:[],X.invalid?`invalid ${X.invalid}`:X.enabled?"enabled":`disabled${X.disabledReason?`: ${X.disabledReason}`:""}`];return`${X.id}: ${J.join(", ")}`}async function j3(X,J){let $=await M7(J),Y=await a6(J),{status:G}=Y,Q=x8(Y)?void 0:await X.store.read(),z=await H$(X),Z=new Set(["check-quotas",...(X.extraActions??[]).map((H)=>H.id)]),W=z.filter((H)=>!x8(Y)||Z.has(H.id)).map((H)=>({...H,run:async(U)=>{if(!Z.has(H.id)&&x8(await a6(J))){U.print(v8);return}await J.authority(),await H.run(U)}})),B=W.find((H)=>H.id==="check-quotas");if(B)B.run=async(H)=>{await M7(J);let U=await a6(J),j=x8(U)?void 0:await X.store.read();if(!j)H.print(K3);else if(j.status!=="ready")H.print("The local account store could not be read.");else for(let L of j.rows){H.print(BB(L));try{if(X.pollQuota&&L.credentialEpoch!==void 0){let _=await X.pollQuota(L);await X.store.recordQuota(L.id,{credentialEpoch:L.credentialEpoch,...L.identity!==void 0?{identity:L.identity}:{}},_)}}catch(_){H.print(` quota check failed: ${_ instanceof Error?_.message:String(_)}`)}let F=await X.store.read(),O=F.status==="ready"?F.rows.find((_)=>_.id===L.id):void 0;for(let _ of WB(O??L,(X.now??Date.now)()))H.print(_)}let q=U.routes;for(let L of J.snapshot()?.rows??[]){if(H.print(`Vault ${w8(L)}: ${L.enabled?L.state:"declined"}`),!q.has(L.routeId)){H.print(" quota check skipped: account is not enabled and active");continue}let F=await J.pollQuota(L.routeId);if(!F.ok)H.print(` quota check failed: ${F.error??"vault unavailable"}`);let O=J.snapshot()?.rows.find((_)=>_.routeId===L.routeId);for(let _ of WB({quota:O?.quota},(X.now??Date.now)()))H.print(_)}let K=await J.status();if(K.lastError)H.print(`Claustrum vault unreachable: ${K.lastError}`)};return B1({title:X.title,subtitle:"Select an account action",status:[...await X.status?.()??[],...$?[`Last error: ${$}`]:[],...G.lastError?[`Claustrum vault unreachable: ${G.lastError}`]:[],...G.accounts.map((H)=>`Vault ${w8(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!Q?[K3]:Q.status==="ready"?Q.rows.map((H)=>BB(H)):["The local account store could not be read."]],actions:W,...X.terminal?{terminal:X.terminal}:{}})}function HB(X){return s(X)?{...X}:{}}function _7(X,J,$,Y){let G=$.confirm?.irreversible?{irreversible:!0,confirm:$.confirm.message}:{...$.confirm?{confirm:$.confirm.message}:{}};return{id:$.id,label:$.label,...$.description?{description:$.description}:{},...$.group?{group:$.group}:{},knobs:$.knobs,...G,run:async({values:Q,invocation:z})=>{let Z=await X.apply({command:X.command,sectionId:J,...Y?{itemId:Y}:{},actionId:$.id,values:Q,confirmed:!0},z);return{ok:Z.ok,text:Z.text,...Z.code?{code:Z.code}:{}}}}}function j$(X,J){return new Proxy(X,{get($,Y){if(Y==="read")return async()=>{let Q=await $.read();if(Q.status!=="ready")return Q;let z={...Q,rows:Q.rows.map((B)=>({...B,label:B.label??B.id}))};if(!J)return z;let Z=await a6(J);if(!x8(Z))return z;let W=[...Z.status.accounts.map((B)=>({id:B.routeId,label:w8(B),type:"oauth",enabled:B.enabled,identity:B.accountIdentity,quota:B.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...Q,rows:W}};if(Y==="readSettings")return async()=>{let Q=await $.readSettings();if(Q.status==="error"||!J)return Q;let z=await a6(J),Z=HB(Q.settings.killswitch);if(!x8(z)||!Q.settings.killswitch)return Q;let W=HB(Z.accounts);for(let B of z.status.accounts)W[B.routeId]=n6({version:1,accounts:[],...Q.settings},B.routeId);return{...Q,settings:{...Q.settings,killswitch:{...Z,accounts:W}}}};let G=Reflect.get($,Y);return typeof G==="function"?G.bind($):G}})}function VB(X,J){let $=l9(X),Y=l9({command:X.command,title:X.title,store:j$(X.store,J),accounts:X.accounts,quota:X.quota,limits:X.limits,routing:X.routing,...X.extraLocks?{extraLocks:X.extraLocks}:{},...X.now?{now:X.now}:{}}),G=async(W,B)=>{let H=await a6(J),U=x8(H),j=U?Y:$,K=(await j.open(B)).menu.sections.find((N)=>N.id===W);if(!K)throw new I6("unavailable","The account menu is unavailable.");if(!U)return{lines:K.lines,items:K.items.map((N)=>({...N,actions:N.actions.map((P)=>_7(j,W,P,N.id))})),actions:K.actions.map((N)=>_7(j,W,N))};let L=new Map(H.status.accounts.map((N)=>[N.routeId,N])),F=(X.now??Date.now)(),O=(N)=>({id:"check",label:N?"Check this account":"Check now",group:"Actions",run:async()=>{let A=[...(await a6(J)).routes].filter((T)=>!N||T===N);if(N&&A.length===0)throw new I6("unavailable","This vault account cannot be checked right now.");for(let T of A){let b=await J.pollQuota(T);if(!b.ok)throw new I6("quota-check-failed",`${T}: ${b.error??"vault unavailable"}`)}return`Checked quota for ${A.length} account${A.length===1?"":"s"}.`}});if(W==="quota"){let N=(P,A)=>_8(f0(P.quota,X.quota?.scope),{now:F,form:A});return{lines:H.status.accounts.filter((P)=>!H.routes.has(P.routeId)).map((P)=>`${w8(P)} (${P.enabled?P.state:"disabled"}): ${N(P,"compact")}`),items:H.status.accounts.filter((P)=>H.routes.has(P.routeId)).map((P)=>({id:P.routeId,label:w8(P),group:"Accounts",status:N(P,"compact"),detail:N(P,"full"),actions:[O(P.routeId)]})),actions:H.routes.size>0?[O()]:[]}}let _=K.items.map((N)=>{let P=L.get(N.id),A=P&&W==="accounts"?`Vault · ${P.credentialType==="oauth"?"login":"API key"} · ${P.state} · ${P.enabled?"enabled":"declined"}`:N.detail;return{id:N.id,label:N.label,detail:A,group:N.group,status:P&&W==="accounts"?P.enabled?P.state:"disabled":N.status,...N.facts?{facts:N.facts}:{},actions:P&&W!=="limits"?[]:N.actions.map((T)=>_7(j,W,T,N.id))}}),C=K.actions.filter((N)=>W==="limits"||W==="routing"&&N.id==="mode").map((N)=>_7(j,W,N));return{lines:W==="accounts"?[`${H.status.accounts.length} vault account${H.status.accounts.length===1?"":"s"}`,`${H.routes.size} can route`,K3]:K.lines,items:_,actions:C}},Q=l9({...X,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(W)=>G("accounts",W)},quota:{title:"Quota",build:(W)=>G("quota",W)},routing:{title:"Routing",build:(W)=>G("routing",W)},limits:{title:"Limits",build:(W)=>G("limits",W)}},extras:X.extras?.map((W)=>W.id!=="reset"?W:{...W,build:async(B)=>{let H=await a6(J);if(x8(H))return{lines:[K3]};return W.build(B)}})}),z=async()=>{if(!x8(await a6(J)))return{menu:$,error:void 0};let W=await M7(J);return{menu:Q,error:W}},Z=async(W,B)=>{let H=await W.menu.open(B);if(W.error)H.menu.sections.find((j)=>j.id==="vault")?.lines.push(`Last error: ${W.error}`);return H};return{command:X.command,open:async(W)=>Z(await z(),W),apply:async(W,B)=>{let H=await z(),{menu:U}=H;if(U===Q&&(W.sectionId==="accounts"||W.sectionId==="routing"&&W.actionId==="order"||W.sectionId==="reset"||W.sectionId==="quota"&&(await a6(J)).routes.size===0||W.sectionId==="limits"&&W.itemId!==void 0&&!(await a6(J)).status.accounts.some((j)=>j.routeId===W.itemId)))return{...await Z(H,B),ok:!1,code:"vault-local-action",text:v8};return U.apply(W,B)}}}var m6="openai",L$="OpenAI accounts",H1="main",jB="that account is already your main account, so it was not added again",r6=Z0("commands"),qB=new Set(["__proto__","constructor","prototype"]);function NB(X,J){let $={version:1,accounts:[],killswitch:X},Y=s(X.accounts)?Object.keys(X.accounts):[],G={};for(let Z of new Set([H1,...J,...Y])){if(qB.has(Z))continue;let W=n6($,Z===H1?void 0:Z);G[Z]={primary:W.primary,secondary:W.secondary}}let Q=n6($,void 0),z={...X};return delete z.main,z.accounts=G,z.defaults={primary:Q.primary,secondary:Q.secondary},z.schema=o1,z}function LB(X,J){let $=s(X.accounts)?{...X.accounts}:{};for(let G of new Set([H1,...J])){if(qB.has(G)||Object.hasOwn($,G))continue;$[G]={primary:A9.primary,secondary:A9.secondary}}let Y=s(X.defaults)?X.defaults:{primary:A9.primary,secondary:A9.secondary};return{...X,accounts:$,defaults:Y,schema:o1}}function q$(X,J){let $=!1;if(s(X.cachekeep))X.cacheKeep={...X.cachekeep,...s(X.cacheKeep)?X.cacheKeep:{}},delete X.cachekeep,$=!0;let Y=X.killswitch;if(s(Y)&&Y.schema!==o1)X.killswitch=NB(Y,J),$=!0;return $}async function UB(X){let J=await X.read();return J.status==="ready"?J.rows.map(($)=>$.id):[]}function T7(X){let J=async()=>{let Y=await X.readSettings();if(Y.status==="error")return Y;let G=structuredClone(Y.settings);return q$(G,await UB(X)),{...Y,settings:G}},$=async(Y,G)=>{let Q=await UB(X);return X.updateSettings(async(z)=>{q$(z,Q);let Z=await Y(z)??z;if(s(Z.killswitch)&&Z.killswitch.schema!==o1)Z.killswitch=LB(Z.killswitch,Q);return Z},G)};return new Proxy(X,{get(Y,G){if(G==="readSettings")return J;if(G==="updateSettings")return $;let Q=Reflect.get(Y,G,Y);return typeof Q==="function"?Q.bind(Y):Q}})}function R7(X,J){let $=(W,B)=>J.rowLocks?J.rowLocks(W):B,Y=(W,B)=>{let H=$(W,B?.extraLocks);return{...B??{},...H?{extraLocks:H}:{}}},G=(W,B,H,U)=>X.replace(W,B,H,Y(W,U)),Z={add:async(W,B)=>{let H=await X.read(),j=(H.status==="ready"?H.rows:[]).filter((F)=>F.type==="oauth"&&!F.invalid),q=W.identity?j.find((F)=>F.identity===W.identity):void 0;if(q?.id===H1)throw new I6("main-account",jB);let K=q??j.find((F)=>F.id===W.id&&F.id!==H1);if(!K||W.credential.type!=="oauth")return X.add(W,B);let L=await G(K.id,W.credential,W.identity!==void 0?{identity:W.identity}:{},B?.extraLocks?{extraLocks:B.extraLocks}:void 0);return r6.info("account signed in again",{id:K.id}),{id:L.id,outcome:"rotated",credential:L.credential,credentialEpoch:L.credentialEpoch}},replace:G,enable:(W,B)=>X.enable(W,Y(W,B)),disable:(W,B,H)=>X.disable(W,B,Y(W,H)),remove:(W,B)=>X.remove(W,Y(W,B))};return new Proxy(X,{get(W,B){if(Object.hasOwn(Z,B))return Z[B];let H=Reflect.get(W,B,W);return typeof H==="function"?H.bind(W):H}})}async function V1(X,J,$){await T7(X).updateSettings((Y)=>{$(Y);return},J?{extraLocks:J}:{})}var QM=["version","accounts","commonAuthPool"];function D$(X,J){return async($)=>{let Y;if(await T7(X).updateSettings((G)=>{let Q={...G,version:1,accounts:[]},z=$(Q)??Q;Y=z;let Z={...z};for(let W of QM)delete Z[W];return Z},J?{extraLocks:J}:{}),!Y)throw Error("the settings write did not run");return Y}}var DB="migration";function N$(X){let J=["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. This menu works on that layout, so it opens after the move.",X.length>0?"These processes still hold the move back:":"No running process holds the move back."],$={command:m6,title:L$,sections:[{id:DB,slot:"extra",title:"Accounts are moving",lines:J,items:X.map((Y,G)=>({id:`blocker-${G}`,label:Y.pid==="unknown"?"processes that could not be read":`pid ${Y.pid}`,detail:`version ${Y.version}`,actions:[]})),actions:[]}]};return WM($)}var zM=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function ZM(X){let J=X.toLowerCase().replace(/[-_]/g,"");if(zM.has(J))return!0;return J.endsWith("token")||J.endsWith("key")||J.endsWith("secret")}function A7(X,J,$){if(Array.isArray(X))return X.map((G,Q)=>A7(G,`${J}[${Q}]`,$));if(!s(X))return X;let Y={};for(let[G,Q]of Object.entries(X)){if(ZM(G)){$.push(`${J}.${G}`);continue}Y[G]=A7(Q,`${J}.${G}`,$)}return Y}function WM(X){let J=[],$=A7(X,"menu",J);if(J.length>0)r6.warn("credential-shaped field stripped before RPC",{fields:J});return $}function FB(X){return{id:X.id,credential:{type:"oauth",refresh:X.refresh,...X.access!==void 0?{access:X.access}:{},...X.expires!==void 0?{expires:X.expires}:{}},...X.accountId!==void 0?{identity:X.accountId}:{},...X.label!==void 0?{label:X.label}:{}}}function PB(X){return{label:"Add account",knobs:[{kind:"text",id:"label",label:"Label (optional)"},{kind:"toggle",id:"headless",label:"Sign in with a device code (no browser on this machine)",value:!1}],run:async(J)=>{let $=typeof J.label==="string"&&J.label.trim().length>0?J.label.trim():void 0,Y=J.headless===!0,G=await X.begin({...$!==void 0?{label:$}:{},headless:Y}),Q=Y?`Open this verification URL:
96
-
97
- ${G.url}
98
-
99
- Then enter the code: ${G.instructions.match(/Enter code: (.+)/)?.[1]??G.instructions}
100
-
101
- The account is added when you finish.`:`Open this URL and complete sign-in:
102
-
103
- ${G.url}
104
-
105
- ${G.instructions}
106
-
107
- The account is added when you finish.`,z=G.completion.then(async(Z)=>{let W=await X.mainIdentity?.();if(Z.accountId&&W&&Z.accountId===W)throw r6.warn("account add rejected (main identity)",{id:Z.id}),new I6("main-account",jB);return r6.info("account added",{id:Z.id}),FB(Z)});return{status:"pending",message:Q,completion:z}}}}function F$(X){return{id:"session",title:"This session",build:async(J)=>{let $=J.sessionId;if(!$)return{lines:["No current session"]};let Y=await X.getPin?.($);return{lines:[Y?`Pinned to ${Y}`:"No sticky pin"],actions:X.clearPin?[{id:"clear-pin",label:"Clear this session's pin",description:"The next request may still choose the same account.",run:async({invocation:G})=>{if(!G.sessionId)return"No current session.";return await X.clearPin?.(G.sessionId),r6.info("routing session pin cleared"),"This session's pin was cleared. The next request may choose the same account if it remains the best selection."}}]:[]}}}}function P$(X){let{vault:J}=X;return{id:"vault",title:"Vault",build:async()=>{let $=await J.status(),Y=await J.authority()!=="local",G=J.routes().length;return{lines:[Y?`Connected · ${$.accounts.length} account${$.accounts.length===1?"":"s"}`:$.enrollment.state==="idle"?"Not connected":`Enrollment ${$.enrollment.state}`,H3($.host,$.name,$.enrollment),...e1($.name,$.enrollment),...Y?[$.accounts.length===0?"The vault serves no OpenAI account to this host yet.":`The vault serves ${$.accounts.length} OpenAI account${$.accounts.length===1?"":"s"}; ${G} can route now.`]:[],...Y&&J.snapshot()?.complete===!1?["The vault's last list had records this host could not read; accounts it did not list are kept as they were until a complete list arrives."]:[],...$.lastError?[`Last error: ${$.lastError}`]:[]],items:$.accounts.map((Q)=>({id:Q.routeId,label:w8(Q),group:"Accounts",status:Q.enabled?Q.state:"disabled",detail:[Q.credentialType==="api_key"?"API key":"login",Q.state==="active"?"active":`vault state ${Q.state}`,Q.enabled?"enabled":"disabled here"].join(", "),actions:[Q.enabled?{id:"disable",label:"Disable on this host",description:"It stays in the vault and in this list, and is never sent from this host until enabled again.",run:async()=>{return await J.decline(Q.routeId),await X.changed?.(),`${w8(Q)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await J.accept(Q.routeId),await X.changed?.(),`${w8(Q)} is enabled on this host.`}}]})),actions:Y?[{id:"disconnect",label:"Disconnect",description:"Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",confirm:"Disconnect from the vault? Connecting again needs a new approval with `ck`.",run:async()=>{return await J.disconnect(),await X.changed?.(),`Disconnected: ${J.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${J.name}\` to revoke it in the vault too.`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:Q})=>{let z=await J.connectStep();if(z.state!=="pending"&&z.state!=="busy")return await X.changed?.(),V3(J,z);return J.waitForApproval(X.wait).then(async(Z)=>{await X.changed?.();let W=V3(J,Z);Q.notify(W.text,W.ok?"info":"warning")}).catch((Z)=>{Q.notify(`Connecting to the vault failed: ${Z instanceof Error?Z.message:String(Z)}`,"error")}),{ok:!0,text:[...e1(J.name,z),"Waiting for the approval; you are told here when it lands."].join(`
108
- `)}}}]}}}}async function KB(X,J,$){if(!I8(J))return o6(J,"invalid_account_key","That account cannot take a reset credit.");let Y;try{let G=(await X.loadAccounts({configPath:X.configPath,statePath:X.statePath}))?.reset?.[J];if($||G&&Object.hasOwn(G,"inFlight"))Y=(await X.resolveResetTarget(J)).chatgptAccountId;else{let z=await AB(J,X);if(!z.eligible)return o6(J,"not_eligible",TB(z));Y=z.chatgptAccountId}if(!Y)return o6(J,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");r6.info("reset redemption decision",{accountKey:J,retry:$});let Q=await wW({configPath:X.configPath,statePath:X.statePath,mutateAccountsFn:X.mutateAccounts,loadAccountsFn:X.loadAccounts,now:X.now,randomUUID:X.randomUUID,fetchImpl:X.fetchImpl,resolveTarget:X.resolveResetTarget,fetchUsage:(z)=>E8({accessToken:z.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:z.chatgptAccountId}),hasActiveRateLimitMark:(z)=>X.quotaManager.isRateLimited(z)},{accountKey:J,expectedChatgptAccountId:Y,retry:$});return r6.info("reset redemption outcome",{accountKey:J,code:Q.outcome.kind}),RB(Q,X,Y)}catch(G){let Q=UM(J,G,Y);return r6.info("reset redemption outcome",{accountKey:J,code:Q.code}),Q}}function O$(X){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await X.accountKeys()).map((J)=>({id:J,group:"Accounts",label:J===H1?"Main account":J,actions:[{id:"preview",label:"Preview",description:"Fetch the account's current quota and reset credits before spending a credit.",run:async()=>{let $=await AB(J,X);return{ok:$.eligible,text:`${VM($)}
109
-
110
- ${TB($)}`}}},{id:"spend",label:"Spend a reset credit",irreversible:!0,confirm:"Spend one reset credit on this account? Its eligibility is checked again first, and nothing is spent when it is not eligible.",run:async()=>{let{ok:$,text:Y}=await KB(X,J,!1);return{ok:$,text:Y}}},{id:"retry",label:"Retry the last redemption",irreversible:!0,confirm:"Retry the last redemption? A retry within five minutes reuses the same request and credit identifiers.",run:async()=>{let{ok:$,text:Y}=await KB(X,J,!0);return{ok:$,text:Y}}}]}))})}}var OB=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],MB=["primary","secondary"];function M$(X){let J={command:m6,title:L$,store:j$(T7(R7(X.store,{...X.rowLocks?{rowLocks:X.rowLocks}:{}}))),...X.extraLocks?{extraLocks:X.extraLocks}:{},accounts:{...X.login?{login:PB(X.login)}:{},...X.protect?{protect:X.protect}:{},...X.describeIdentity?{describeIdentity:X.describeIdentity}:{}},quota:X.quotaCheck?{check:X.quotaCheck}:{},routing:{orderedVariants:OB,formerMainId:H1},limits:{labels:MB},...X.cache?{cache:X.cache}:{},...X.diagnostics?{diagnostics:X.diagnostics}:{},...X.extras?{extras:X.extras}:{},...X.logger?{logger:X.logger}:{},...X.now?{now:X.now}:{}},$=X.vault?VB(J,X.vault):l9(J),Y=(G)=>{let{sessionId:Q}=G,z=G.notify.bind(G);return{...Q!==void 0?{sessionId:Q}:{},notify:z}};return{command:m6,async open(G){let Q=Y(G),z=X.vault&&await X.vault.authority()!=="local"?void 0:await X.migration?.();if(z&&!z.migrated)return{command:m6,menu:N$(z.blockers)};return $.open(Q)},async apply(G,Q){let z=Y(Q),Z=X.vault&&await X.vault.authority()!=="local"?void 0:await X.migration?.();if(Z&&!Z.migrated)return{command:m6,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:N$(Z.blockers)};let W=await $.apply(G,z);if(W.ok)await X.afterApply?.();return W}}}function _B(X){let J=[X.primary?.usedPercent,X.secondary?.usedPercent].filter(($)=>$!==void 0);return J.length>0?Math.max(...J):void 0}function BM(X,J){let $=[X.primary,X.secondary].filter((G)=>G!==void 0),Y=$.filter((G)=>W3(G,J));return(Y.length>0?Y:$).sort((G,Q)=>Q.usedPercent-G.usedPercent)[0]?.resetsAt}function HM(X,J){if(!X)return!1;let $=[X.primary,X.secondary].filter((Y)=>Y!==void 0);if($.length===0)return!1;return $.every((Y)=>!W3(Y,J))}async function AB(X,J){let $;try{$=await J.resolveResetTarget(X);let Y=$.accountKey==="main"?void 0:$.chatgptAccountId,[G,Q]=await Promise.all([E8({accessToken:$.accessToken,fetchImpl:J.fetchImpl,now:J.now,accountId:$.chatgptAccountId}),oJ(J.fetchImpl,$.accessToken,Y)]),z=F7(Q.credits),Z=xW(Q.credits),W=Q.availableCount??G.resetCreditsAvailable??(Z>0?Z:void 0),B=G.resetCreditsApplicable,H=aJ(G,J.quotaManager.isRateLimited(X),J.now()),U;if(!$.chatgptAccountId)U="stable ChatGPT account identity unavailable";else if(!H.ok)U=H.reason;else if(!z)U="no eligible credit";return{accountKey:$.accountKey,label:$.label,chatgptAccountId:$.chatgptAccountId,usedPercent:_B(G),resetTime:BM(G,J.now()),availableCount:W,applicableAvailableCount:B,eligible:U===void 0,reason:U,selectedCreditId:z?.id,selectedCreditExpiresAt:z?.expiresAt}}catch(Y){if(Y?.status===401)await $?.onAuthFailure?.(401);return r6.warn("reset preview row failed",{accountKey:X,error:Y?.message??String(Y)}),{accountKey:X,label:X==="main"?"Main account":X,eligible:!1,reason:Y?.message??String(Y)}}}function VM(X){let J=X.usedPercent===void 0?"quota unavailable":`${X.usedPercent}% used`,$=X.availableCount===void 0?"credits unavailable":`${X.applicableAvailableCount===void 0?"?":X.applicableAvailableCount}/${X.availableCount} applicable/available`,Y=X.eligible?`eligible · credit ${X.selectedCreditId} expires ${X.selectedCreditExpiresAt}`:X.reason;return`${J}; ${$}; ${Y}`}function TB(X){let J=["## Confirm reset credit","",`Account: **${X.label}** (\`${X.accountKey}\`)`,`Current quota: **${X.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${X.availableCount??"unknown"}**`,`Credit expires: **${X.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${X.resetTime??"unavailable"}**`,""];if((X.availableCount??0)>0&&X.applicableAvailableCount===0)J.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),J.push("");if(X.eligible&&X.chatgptAccountId)J.push('Eligible: choose "Spend a reset credit" to redeem one.');else J.push(`Cannot reset: **${X.reason??"not eligible"}**`);return J.join(`
111
- `)}function o6(X,J,$,Y={}){if(Object.keys(Y).length>0)r6.debug("reset step details",{accountKey:X,code:J,...Y});return{ok:J==="reset"||J==="already_redeemed",code:J,text:$}}function UM(X,J,$){if(J instanceof s6){let G={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",pair_identity_mismatch:"Nothing was sent: the saved redemption was started while this account was signed in as a different ChatGPT account. Sign this account back in as that ChatGPT account and retry, or wait until five minutes after the saved redemption started and spend a new credit.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return o6(X,J.kind,`## Reset credit
112
-
113
- ${G[J.kind]}
114
-
115
- Code: \`${J.kind}\``,{cooldownUntil:J.cooldownUntil,...J.kind==="expired_unreconciled"?{chatgptAccountId:$,retryGuidance:"Retry replays the same request and credit identifiers from the previous attempt."}:{}})}let Y=J?.code;if(Y==="unknown_account"||Y==="disabled_account"||Y==="non_oauth_account"||Y==="token_unavailable")return o6(X,Y,`## Reset credit
116
-
117
- ${{unknown_account:"Account unavailable: the selected account no longer exists. Reopen the reset account list.",disabled_account:"Account unavailable: the selected account is disabled. Reopen the reset account list.",non_oauth_account:"Account unavailable: the selected account is not authenticated with OAuth. Reopen the reset account list.",token_unavailable:"Authentication problem: the selected account token is unavailable. Reauthenticate the account before retrying."}[Y]}
118
-
119
- Code: \`${Y}\``);if(J instanceof z1)return o6(X,J.kind,`## Reset credit
120
-
121
- No redemption was attempted: reset credit availability could not be loaded.
122
-
123
- Code: \`${J.kind}\``);return r6.warn("reset command failed before a known result",{accountKey:X,error:J?.message??String(J)}),o6(X,"error",`## Reset credit
124
-
125
- The reset request failed before a known result: internal command failure — see plugin log.`)}async function RB(X,J,$){let{accountKey:Y}=X.target,G=X.outcome.kind;if(X.finalizeStateWriteFailed)return o6(Y,G,`## Reset credit result
126
-
127
- Account: **${X.target.label}** (\`${Y}\`)
128
-
129
- The server outcome recorded as \`${G}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:X.retrySafety,chatgptAccountId:$});if(G==="reset"||G==="already_redeemed"){let z={account:Y,ok:!1,error:"targeted quota refresh did not complete"};try{z=await J.refreshResetTargetQuota(Y)}catch(q){z.error=q?.message??String(q)}let Z=!z.ok&&z.error!==void 0;if(Z)r6.warn("reset quota re-check failed",{accountKey:Y,error:z.error});let W=Y==="main"?J.quotaManager.getMain():J.quotaManager.getFallback(Y),B=z.ok&&HM(W?.quota,J.now()),H=W?.quota.resetCreditsApplicable,U=B?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${G}\`).`,j=Z?`
130
-
131
- quota re-check failed — see log.`:"";return o6(Y,G,`## Reset credit result
132
-
133
- Account: **${X.target.label}** (\`${Y}\`)
134
-
135
- Code: \`${G}\`
136
-
137
- ${U}${j}${H===void 0?"":`
138
-
139
- Remaining applicable credits: **${H}**`}`,{verifiedFresh:B,afterUsedPercent:_B(W?.quota??{}),remainingCredits:H})}if(G==="ambiguous_local")return o6(Y,G,`## Reset credit result
140
-
141
- Account: **${X.target.label}** (\`${Y}\`)
142
-
143
- Code: \`${G}\`
144
-
145
- ${X.retrySafety}`,{retryGuidance:X.retrySafety});if(G==="ambiguous"||G==="http_error"){let z=X.refused?' The server refused the request; five minutes after the redemption started, "Spend a reset credit" starts a new one instead.':"";return o6(Y,G,`## Reset credit result
146
-
147
- Account: **${X.target.label}** (\`${Y}\`)
148
-
149
- The redemption outcome is unknown (\`${G}\`).
150
-
151
- Retry with "Retry the last redemption" on this account. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.${z}`,{retryGuidance:X.retrySafety,chatgptAccountId:$})}let Q={nothing_to_reset:"The server found no exhausted quota window to reset. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions.",no_credit:"The server found no usable reset credit. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions."};return o6(Y,G,`## Reset credit result
152
-
153
- Account: **${X.target.label}** (\`${Y}\`)
154
-
155
- Code: \`${G}\`
156
-
157
- ${Q[G]??"The server returned a no-op result. No reset was confirmed."}`)}var _$=Z0("quota"),CB="the account holds a tombstone from the removed vault custody, not a credential";function KM(X){return X?.status===401}async function J4(X,J={}){let $=X.whamFn;if(!$)throw Error("whamFn is required for refreshAllQuota");let Y=[],G=X.logger??_$,Q=(K)=>{Y.push(K);let L={pid:process.pid,accountId:K.account,status:K.ok?"ok":"error",...K.error?{error:K.error}:{}};if(K.ok)G.debug("quota refresh succeeded",L);else G.warn("quota refresh failed",L)},z=X.skipFresherThanMs,Z=!1,W;if(z!==void 0)try{W=await X.readSidebarState()}catch{}let B=new Map(W?.fallbacks.map((K)=>[K.id,K])??[]),H=(...K)=>z!==void 0&&K.some((L)=>typeof L==="number"&&Number.isFinite(L)&&L<=X.now()&&X.now()-L<z),U=await X.loadAccounts(X.paths).catch(()=>{return}),j=U?.mainAccountId??X.storageMainAccountId,q;if(!J.accountKey||J.accountKey==="main")try{let K=await X.getAuth();if(R6(K)){if(q=G9(U),!q)Q({account:"main",ok:!1,error:T0(K)?CB:"main account row is missing from the account pool"})}else if(K.type==="oauth"){let L=W&&j!==void 0&&W.main.mainAccountId===j?W.main.quota:void 0;if(H(X.quotaManager.peekMainForPolicy(j)?.checkedAt,L?.primary?.checkedAt,L?.secondary?.checkedAt,L?.checkedAt))Q({account:"main",ok:!0});else{if(!K.access||(K.expires??0)<X.now()){let O=await X.refreshMainWithLease();K={...K,access:O.access,expires:O.expires}}if(K.access)if(X.respectBackoff&&X.quotaManager.isBackedOff())Q({account:"main",ok:!0});else{let O=await $({accessToken:K.access,fetchImpl:X.fetchImpl,now:X.now,accountId:j,accountKey:"main"});X.quotaManager.setMain(K.access,{quota:O,refreshAfter:X.now()+300000,checkedAt:X.now()},j,!0),Z=!0,Q({account:"main",ok:!0})}else if(!Y.some((O)=>O.account==="main"))Q({account:"main",ok:!1,error:"no access token"})}}else Q({account:"main",ok:!1,error:"auth type is not oauth"})}catch(K){Q({account:"main",ok:!1,error:n0(K)})}if(U)for(let K of U.accounts){let L=q!==void 0&&K===q;if(!L&&J.accountKey&&(J.accountKey==="main"||K.id!==J.accountKey))continue;if(!L&&X.isOAuthAccountFn(K)&&$9(U,K)){if(J.accountKey)Q({account:K.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let F=L?K.accountId??j:void 0,O=(_,C,N)=>{if(L)X.quotaManager.setMain(C,_,F,!0);else X.quotaManager.setFallback(K.id,_,C,!0,N)};if(K.enabled===!1||!X.isOAuthAccountFn(K)){if(J.accountKey)Q({account:K.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let _=B.get(K.id),C=K.accountId,N=L?W&&F!==void 0&&W.main.mainAccountId===F?W.main.quota:void 0:_&&C!==void 0&&_.accountId===C?_.quota:void 0;if(H(L?X.quotaManager.peekMainForPolicy(F)?.checkedAt:X.quotaManager.peekFallbackForPolicy(K.id,C)?.checkedAt,N?.primary?.checkedAt,N?.secondary?.checkedAt,N?.checkedAt)){Q({account:K.id,ok:!0});continue}if(X.respectBackoff&&(L?X.quotaManager.isBackedOff():X.quotaManager.isFallbackBackedOff(K.id,K.access))){Q({account:K.id,ok:!0});continue}let P=K.lastRefreshError;if(t0(P,K.refresh,X.now())){Q({account:K.id,ok:!1,error:r8(P,X.now()),permanent:!0});continue}if(T0(K)){Q({account:K.id,ok:!1,error:CB});continue}let A;try{A=L?await X.fallbackManager.refreshAccount(K,U,{asPoolMain:!0}):await X.fallbackManager.refreshAccount(K,U)}catch(b){_$.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:K.id,error:n0(b)}),A=K}if(!A.access||(A.expires??0)<X.now()){Q({account:K.id,ok:!1,error:"no usable access token"});continue}let T;try{T=await $({accessToken:A.access,fetchImpl:X.fetchImpl,now:X.now,accountId:A.accountId,accountKey:K.id})}catch(b){if(!KM(b))throw b;if(_$.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:K.id}),A=await X.fallbackManager.refreshAccount(K,U,L?{force:!0,asPoolMain:!0}:{force:!0}),!A.access){Q({account:K.id,ok:!1,error:"no usable access token after forced refresh"});continue}T=await $({accessToken:A.access,fetchImpl:X.fetchImpl,now:X.now,accountId:A.accountId,accountKey:K.id})}O({quota:T,refreshAfter:X.now()+300000,checkedAt:X.now()},A.access,A.accountId),Z=!0,Q({account:K.id,ok:!0})}catch(_){Q({account:K.id,ok:!1,error:n0(_)})}}if(J.accountKey&&J.accountKey!=="main"&&!Y.some((K)=>K.account===J.accountKey))Y.push({account:J.accountKey,ok:!1,error:"account not found"});if(z===void 0||Z){let K=await X.loadAccounts(X.paths);await X.writeSidebarState(X.quotaManager,K)}return Y}function $4(X,J){let $=J?X.split(J).join("[credential]"):X;return EB($).replaceAll("***REDACTED***","[credential]")}function U1(X,J){let $=$4(X instanceof DOMException?X.message:n0(X),J),Y=(G,Q=new WeakSet)=>{if(typeof G==="string")return $4(G,J);if(!G||typeof G!=="object")return G;if(Q.has(G))return"[Circular]";if(Q.add(G),Array.isArray(G))return G.map((z)=>Y(z,Q));return Object.fromEntries(Object.entries(G).filter(([z])=>z!=="cause").map(([z,Z])=>[z,Y(Z,Q)]))};if(X instanceof Error||X instanceof DOMException)try{if(Object.defineProperty(X,"message",{value:$,configurable:!0,writable:!0}),typeof X.stack==="string")X.stack=$4(X.stack,J);if("cause"in X)delete X.cause;for(let G of Object.keys(X)){let Q=Object.getOwnPropertyDescriptor(X,G);if(Q&&"value"in Q)Object.defineProperty(X,G,{...Q,value:Y(Q.value)})}return X}catch{}return Error($)}function jM(X,J){if(!X.includes('"error"'))return X;try{let $=JSON.parse(X);if($?.type==="error"||$?.error||$?.response?.error)return $4(X,J)}catch{}return X}async function q3(X,J){let $={status:X.status,statusText:$4(X.statusText,J),headers:new Headers(X.headers)};if(!X.ok)return $.headers.delete("content-length"),new Response($4(await X.text(),J),$);if(!X.body||!X.headers.get("content-type")?.includes("text/event-stream"))return X;$.headers.delete("content-length");let Y=X.body.getReader(),G=new TextDecoder,Q=new TextEncoder,z="";function Z(W){return W.replace(/^data: ?([^\r\n]*)/gm,(B,H)=>B.slice(0,B.length-H.length)+jM(H,J))}return new Response(new ReadableStream({async pull(W){try{for(;;){let B=await Y.read();z+=G.decode(B.value,{stream:!B.done});let H=!1;for(;;){let U=/\r?\n\r?\n/.exec(z);if(!U)break;let j=U.index+U[0].length;W.enqueue(Q.encode(Z(z.slice(0,j)))),z=z.slice(j),H=!0}if(B.done){if(z)W.enqueue(Q.encode(Z(z)));W.close();return}if(H)return}}catch(B){W.error(U1(B,J))}},cancel(W){return Y.cancel(W)}}),$)}import{readFile as M_}from"node:fs/promises";import{readFileSync as qM}from"node:fs";import{homedir as NM,tmpdir as LM}from"node:os";import{join as S7}from"node:path";var DM="https://chatgpt.com/backend-api/codex/responses",FM="openai-auth.json",E9={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function I7(){let X=process.env[E9.configDir]?.trim();if(X)return X;return S7(process.env.XDG_CONFIG_HOME||S7(NM(),".config"),"opencode")}function V0(){return process.env[E9.configFile]?.trim()||S7(I7(),FM)}function PM(){try{let X=JSON.parse(qM(V0(),"utf8"));return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:{}}catch{return{}}}function OM(X){let J=process.env[X];if(J===void 0)return;let $=J.trim().toLowerCase();if($==="1"||$==="true"||$==="yes"||$==="on")return!0;if($===""||$==="0"||$==="false"||$==="no"||$==="off")return!1;return}function C7(X,J,$){let Y=OM(X);if(Y!==void 0)return Y;if(typeof J==="boolean")return J;return $}function MM(){let X=PM(),J;if(X.dump!==void 0&&X.dump!==null){if(typeof X.dump==="object")J=X.dump.enabled;else if(typeof X.dump==="boolean")J=X.dump}return{webSockets:C7(E9.webSockets,X.webSockets,!1),rawWebSocket:C7(E9.rawWebSocket,X.rawWebSocket,!1),responsesLite:C7(E9.responsesLite,X.responsesLite,!1),dump:C7(E9.dump,J,!1),dumpDir:process.env[E9.dumpDir]?.trim()||(typeof X.dumpDir==="string"&&X.dumpDir.trim()?X.dumpDir.trim():S7(LM(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[E9.codexApiEndpoint]?.trim()||(typeof X.codexApiEndpoint==="string"&&X.codexApiEndpoint.trim()?X.codexApiEndpoint.trim():DM)}}var E7;function u6(){if(!E7)E7=MM();return E7}function SB(){return E7=void 0,u6()}import{realpathSync as IB}from"node:fs";import{homedir as _M}from"node:os";import{basename as AM,dirname as TM,join as k7,resolve as kB}from"node:path";function RM(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return k7(process.env.XDG_CONFIG_HOME||k7(_M(),".config"),"opencode")}function xB(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||k7(RM(),hJ)}function b7(X,J){let $=kB(X);return J==="win32"||J==="darwin"?$.toLowerCase():$}function bB(X){try{return IB.native(X)}catch{try{return k7(IB.native(TM(X)),AM(X))}catch{return}}}function CM(X,J,$=process.platform){if(b7(X,$)===b7(J,$))return!0;let Y=bB(X),G=bB(J);return Y!==void 0&&G!==void 0&&b7(Y,$)===b7(G,$)}function A$(X=xB()){let J=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(J){if(CM(X,J))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${kB(X)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return J}return fJ(X)}function M0(X=xB()){return{configPath:X,statePath:A$(X)}}import{createHash as X_}from"node:crypto";import{readFile as J_}from"node:fs/promises";import{homedir as $_}from"node:os";import{join as rB,resolve as Y_}from"node:path";import{createHash as EM}from"node:crypto";import{readFileSync as SM}from"node:fs";import{readFile as IM}from"node:fs/promises";import{resolve as bM}from"node:path";var Y4="openai",kM="common-auth-placeholder:v1:openai",K1=Object.freeze({type:"oauth",access:"",refresh:kM,expires:0});function D3(X){if(!t6(X))return!1;return X.type===K1.type&&X.access===K1.access&&X.refresh===K1.refresh&&X.expires===K1.expires}var x7="openaiAuthPool",xM=120000,hB="pool-migration",R$="slot-transfer-origin-unknown",C$="Sign in again with `opencode auth login`, or re-enable the row only if this config root is the only one using that auth.json.",v7=Object.freeze({mainRefreshTtlMs:xM,fallbackTtlMs:dJ,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function w7(X,J,$){return X.kind==="placeholder"&&!J&&!$.pending}class N3 extends Error{constructor(X){super(`timed out waiting for the legacy ${X} lock`);this.name="LegacyLockContention"}}function t6(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}function wM(X){let J=X.now??Date.now;return{paths:X.paths,slot:X.slot,now:J,sleep:X.sleep??(($)=>new Promise((Y)=>setTimeout(Y,$))),newId:X.newId??(()=>crypto.randomUUID()),log:X.log??Z0("pool-migration"),...X.vaultServes?{vaultServes:X.vaultServes}:{},locks:{...v7,...X.legacyLocks},leaseWait:X.leaseWait??{timeoutMs:4000,pollMs:50},store:G8({provider:Y4,configPath:X.paths.configPath,statePath:X.paths.statePath,quota:f8,now:J,...X.store}),onStep:async($)=>{await X.onStep?.($)}}}async function Q4(X){let J;try{J=await IM(X,"utf8")}catch(Y){if(Y.code==="ENOENT")return{};throw Y}let $=JSON.parse(J);if(!t6($))throw Error("config root is not an object");return $}async function L3(X,J,$,Y){let G=performance.now();for(;;){let Q=await g0({name:J,path:$,ttlMs:Y,now:X.now,renew:X.locks.renew,...X.locks.renewIntervalMs!==void 0?{renewIntervalMs:X.locks.renewIntervalMs}:{}});if(Q)return Q;if(performance.now()-G>=X.locks.timeoutMs)throw new N3(J);await X.sleep(X.locks.retryMs)}}async function fB(X,J,$={}){let Y={...v7,...$},G=performance.now();for(;;){let Q=await g0({name:h8,path:X,ttlMs:Y.mainRefreshTtlMs,renew:Y.renew,...Y.renewIntervalMs!==void 0?{renewIntervalMs:Y.renewIntervalMs}:{}});if(Q)try{return await J()}finally{await Q.release().catch(()=>{})}if(performance.now()-G>=Y.timeoutMs)throw new N3(h8);await new Promise((z)=>setTimeout(z,Y.retryMs))}}async function F3(X,J){let $=X.locks.saveTtlMs,Y=await L3(X,"save",X.paths.configPath,$);try{let G=await L3(X,"save",X.paths.statePath,$);try{let Q=await Q4(X.paths.configPath);if(!await J(Q))return;await O6(X.paths.configPath,Q,{beforeRename:async()=>{await Y.assertOwned(),await G.assertOwned()}})}finally{await G.release().catch(()=>{})}}finally{await Y.release().catch(()=>{})}}function vM(X){if(!t6(X))return;let{rowId:J,operation:$,rowFingerprint:Y,slotFingerprint:G}=X,{credentialFingerprint:Q,carryLegacyMain:z,recordedAt:Z,identity:W}=X;if(typeof J!=="string"||!J)return;if($!=="add"&&$!=="rotate"&&$!=="replace")return;if(Y!==null&&typeof Y!=="string")return;if(typeof G!=="string")return;if(typeof Q!=="string")return;return{rowId:J,operation:$,rowFingerprint:Y,slotFingerprint:G,credentialFingerprint:Q,...typeof W==="string"&&W?{identity:W}:{},carryLegacyMain:z===!0,recordedAt:typeof Z==="number"?Z:0}}function gB(X,J){if(!t6(X)||!J)return!1;return j6(X).pending?.credentialFingerprint===J8({type:"oauth",refresh:J})}function mB(X,J){let $;try{$=JSON.parse(SM(X,"utf8"))}catch{return!1}return gB($,J)}class y7 extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var yM=600000;async function uB(X,J,$={}){let Y=$.now??Date.now,G=(W)=>{let B=j6(W).pending;return B&&gB(W,J)&&Y()-B.recordedAt>=yM?B:void 0},Q=G(await Q4(X.configPath));if(!Q)return!1;let z={...v7,...$.legacyLocks},Z=await g0({name:hB,path:X.configPath,ttlMs:z.mainRefreshTtlMs,now:Y});if(!Z)return!1;try{let W=await Q4(X.configPath),B=j6(W).migratedAt!==void 0,H=await G8({provider:Y4,configPath:X.configPath,statePath:X.statePath,quota:f8,now:Y}).read();if(B&&H.status!=="ready")return!1;let U;if(H.status==="ready"){let q=H.rows.find((L)=>L.id===Q.rowId&&!L.invalid),K=q?.fingerprint??null;if(B&&q&&K===Q.credentialFingerprint)return!1;if(q&&K!==Q.credentialFingerprint&&K!==Q.rowFingerprint)U=$.slotAccess!==void 0?I$({type:"oauth",access:$.slotAccess,refresh:J}):Q.slotFingerprint}let j=!1;if(await F3({paths:X,now:Y,locks:z,sleep:(q)=>new Promise((K)=>setTimeout(K,q))},(q)=>{let K=j6(q),L=G(q);if(!L||L.recordedAt!==Q.recordedAt)return!1;let{pending:F,...O}=K;return h7(q,U!==void 0?{...O,declinedSlotFingerprint:U}:O),j=!0,!0}),j)($.log??Z0("pool-migration")).warn(U!==void 0?"dropped an expired account-pool transfer record whose row was rotated since; the slot login is not adopted unless its refresh renews it":"dropped an expired account-pool transfer record so the slot refresh can resume",{rowId:Q.rowId,recordedAt:Q.recordedAt});return j}finally{await Z.release().catch(()=>{})}}function j6(X){let J=X[x7];if(!t6(J))return{};let $=vM(J.pending);return{...typeof J.migratedAt==="number"?{migratedAt:J.migratedAt}:{},...$?{pending:$}:{},...typeof J.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:J.declinedSlotFingerprint}:{}}}function h7(X,J){let Y={...t6(X[x7])?X[x7]:{}};for(let G of["migratedAt","pending","declinedSlotFingerprint"])delete Y[G];Object.assign(Y,J),X[x7]=Y}function hM(X){let J=X?H6(X):void 0;return J?V6(J):void 0}function fM(X){let J=I$({type:"oauth",...X}),$=hM(X.access);return{kind:"real",credential:X,fingerprint:J,credentialFingerprint:J8({type:"oauth",refresh:X.refresh}),...$?{identity:$}:{}}}function pB(X){if(D3(X))return{kind:"placeholder",...t6(X)&&typeof X.accountId==="string"?{origin:X.accountId}:{}};let J=aB(X);if(!J?.refresh.trim())return{kind:"empty"};return fM(J)}async function P3(X){let J=await oB({client:{auth:{get:($)=>X.slot.get($),all:()=>X.slot.all()}},now:X.now,sleep:X.sleep});if(J.kind==="real")return pB(J.oauth);return J.kind==="slot-absent"||J.kind==="indeterminate"?{kind:J.kind}:{kind:J.kind}}async function f7(X,J){if(!D3(J))return!1;let $=await Q4(X.configPath),Y=await G8({provider:Y4,configPath:X.configPath,statePath:X.statePath,quota:f8}).read();if(Y.status==="error")return!1;let G=Y.status==="ready"?Y.rows.some((Q)=>Q.id==="main"):Y.roster.some((Q)=>t6(Q)&&Q.id==="main");return w7({kind:"placeholder"},G,j6($))}async function gM(X){let J=X.now()+X.leaseWait.timeoutMs;for(;;){let $=await P3(X);if($.kind!=="real")return $;if(!await cB(X,$.credential.refresh))return $;if(X.now()>=J)return{kind:"retry"};await X.sleep(X.leaseWait.pollMs)}}async function cB(X,J){let $=await b0(X.paths),Y=$?.refresh?.mainRefreshLeaseUntil;return Boolean(Y&&Y>X.now()&&$?.refresh?.mainRefreshLeaseTokenHash===Q8(J))}function mM(X){return X.length>0&&X.trim()===X&&!["__proto__","constructor","prototype","main"].includes(X)}function uM(X,J,$,Y,G){let Q=$.identity?{identity:$.identity}:{},z=J.find((H)=>!H.invalid&&H.fingerprint===$.credentialFingerprint);if(z)return{rowId:z.id,operation:"rotate",rowFingerprint:z.fingerprint??null,...Q,carryLegacyMain:X==="migrate"&&z.id==="main"};let Z=J.find((H)=>H.id==="main");if(!Z||!Z.invalid&&!Z.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...Q,carryLegacyMain:X==="migrate"};if($.identity){let H=J.find((U)=>!U.invalid&&U.type==="oauth"&&U.enabled&&U.identity===$.identity);if(H)return{rowId:H.id,operation:"replace",rowFingerprint:H.fingerprint??null,...Q,carryLegacyMain:X==="migrate"&&H.id==="main"}}let W=new Set(J.map((H)=>H.id));return{rowId:Y??($.identity&&mM($.identity)&&!W.has($.identity)?$.identity:G()),operation:"add",rowFingerprint:null,...Q,carryLegacyMain:!1}}function pM(X,J,$,Y,G,Q,z){let Z=J.pending;if(Z){let W=$.find((U)=>U.id===Z.rowId&&!U.invalid),B=W?.fingerprint??null,H=Y.kind==="real"&&Y.fingerprint===Z.slotFingerprint;if(W&&B===Z.credentialFingerprint)return{kind:"finish",record:Z};if((W||Z.rowFingerprint===null)&&B===Z.rowFingerprint)return H&&Y.kind==="real"?{kind:"transfer",record:Z,credential:Y.credential,fresh:!1}:{kind:"drop-record"};if(!W)return{kind:"drop-record"};return H?{kind:"ambiguous",record:Z}:{kind:"drop-record"}}if(Y.kind==="indeterminate")return{kind:"drop-record"};if(Y.kind!=="real")return{kind:"nothing",slot:Y.kind};if(J.declinedSlotFingerprint===Y.fingerprint)return{kind:"nothing",slot:"declined"};return{kind:"transfer",record:{...uM(X,$,Y,G,z),slotFingerprint:Y.fingerprint,credentialFingerprint:Y.credentialFingerprint,recordedAt:Q},credential:Y.credential,fresh:!0}}async function cM(X,J,$){let Y={type:"oauth",access:$.access,refresh:$.refresh,...$.expires!==void 0?{expires:$.expires}:{}},G=J.identity?{identity:J.identity}:{},Q={extraLocks:y8(X.paths,J.rowId,X.locks)};if(J.operation==="add")await X.store.add({id:J.rowId,credential:Y,...G},Q);else if(J.operation==="replace")await X.store.replace(J.rowId,Y,G,Q);else{let z=await X.store.read(),Z=z.status==="ready"?z.rows.find((W)=>W.id===J.rowId):void 0;await X.store.rotate(J.rowId,Y,Z?.identity===void 0?G:{},Q)}}async function lM(X,J){let $=await X.store.read();if($.status!=="ready")return;let Y=$.rows.find((G)=>G.id===J.rowId&&!G.invalid);return Y?.fingerprint===J.credentialFingerprint?Y:void 0}function dM(X,J){let $=[],Y=[["primary",X.primary],["secondary",X.secondary]],G=0;for(let[Z,W]of Y){if(!W||!Number.isFinite(W.checkedAt)||!Number.isFinite(W.usedPercent))continue;G=Math.max(G,W.checkedAt),$.push({checkedAt:W.checkedAt,readings:[{label:Z,usedPercent:W.usedPercent,...typeof W.resetsAt==="string"?{resetsAt:W.resetsAt}:{},...Number.isFinite(W.windowMinutes)?{windowMinutes:W.windowMinutes}:{}}]})}let Q=J??(G||void 0),z=X.spendControl;if(Q!==void 0&&z)$.push({checkedAt:Q,budget:{kind:"reading",reached:z.reached,remainingPercent:z.remainingPercent,usedPercent:z.usedPercent,limit:z.limit,used:z.used,remaining:z.remaining,...z.resetsAt!==void 0?{resetsAt:z.resetsAt}:{},...z.unit!==void 0?{unit:z.unit}:{}}});else if(Q!==void 0&&X.spendControlCleared)$.push({checkedAt:Q,budget:{kind:"cleared"}});return $.sort((Z,W)=>Z.checkedAt-W.checkedAt)}async function iM(X,J){let $=await b0(X.paths);if(!$)return;let Y=$.quota?.mainQuotaToken,G=J.credential?.type==="oauth"?J.credential.access:void 0,z=!Y||G!==void 0&&Y===b6(G)?$.quota?.mainQuota:void 0;if(z&&J.credentialEpoch!==void 0){let H={credentialEpoch:J.credentialEpoch,...J.identity!==void 0?{identity:J.identity}:{}};for(let U of dM(z,$.quota?.mainQuotaCheckedAt))try{await X.store.recordQuota(J.id,H,U)}catch(j){X.log.warn("legacy main quota not carried to the pool row",{rowId:J.id,error:j instanceof Error?j.message:String(j)})}}let Z=$.refresh?.mainLastRefreshError,W=$.accounts.find((H)=>H.id===J.id);if(!W||!v0(W)||W.corrupt)return;if(!Z&&!z)return;let B={...$,accounts:[{...W,...W.lastRefreshError||!Z?{}:{lastRefreshError:Z},...W.quota||!z?{}:{quota:z}}]};try{await uJ(B,X.paths,{accounts:[J.id]})}catch(H){X.log.warn("legacy main backoff not carried to the pool row",{rowId:J.id,error:H instanceof Error?H.message:String(H)})}}async function G4(X,J,$={}){await F3(X,(Y)=>{let G=j6(Y);if(delete Y.mainAccountId,J==="migrate"&&G.migratedAt===void 0)nM(Y);return h7(Y,{...G.migratedAt!==void 0||J==="migrate"?{migratedAt:G.migratedAt??X.now()}:{},...$.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:$.declinedSlotFingerprint}:G.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:G.declinedSlotFingerprint}:{}}),!0})}function nM(X){let J=X.routing;if(J===void 0)X.routing={mode:"main-first"};else if(t6(J)&&J.mode===void 0)X.routing={...J,mode:"main-first"}}async function E$(X){await F3(X,(J)=>{let $=j6(J);if(!$.pending)return!1;let{pending:Y,...G}=$;return h7(J,G),!0})}async function sM(X,J){await F3(X,($)=>{let Y=j6($);if(J.identity)$.mainAccountId=J.identity;return h7($,{...Y,pending:J}),!0})}async function aM(X,J,$,Y){let G=await L3(X,h8,X.paths.configPath,X.locks.mainRefreshTtlMs);try{return await oM(X,J,$,Y)}finally{await G.release().catch(()=>{})}}async function oM(X,J,$,Y){let G=(B)=>({status:"completed",rowId:$.rowId,operation:Y,placeholder:B}),Q=await P3(X);if(Q.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(Q.kind==="placeholder"){if(Q.origin===void 0)return{status:"untagged-placeholder"};if(Q.origin!==T$(X))return{status:"foreign-placeholder"};return await G4(X,J),await X.onStep("after-record-clear"),G("already-present")}if(Object.keys(await X.slot.all()).length===0)return{status:"retry",reason:"torn-read"};if(Q.kind==="real"&&Q.fingerprint!==$.slotFingerprint&&$.identity!==void 0&&Q.identity===$.identity)return await E$(X),await X.onStep("after-record-clear"),{status:"restart"};if(Q.kind!=="real"||Q.fingerprint!==$.slotFingerprint)return await G4(X,J),await X.onStep("after-record-clear"),G("slot-moved-on");await X.onStep("before-placeholder-write");let z=await X.slot.get({path:{id:Y4}}),Z=z===void 0||z===null?void 0:pB(z);if(Z?.kind!=="real"||Z.fingerprint!==$.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await X.slot.set({path:{id:Y4},body:{...K1,accountId:T$(X)}})}catch(B){if(B instanceof u7)return{status:"retry",reason:"slot-changed"};throw B}await X.onStep("after-placeholder-write");let W=await X.slot.get({path:{id:Y4}});if(!D3(W))return{status:"retry",reason:"placeholder-overwritten"};if(t6(W)&&W.accountId===void 0)return{status:"untagged-placeholder"};if(t6(W)&&W.accountId!==T$(X))return{status:"foreign-placeholder"};return await G4(X,J),await X.onStep("after-record-clear"),G("written")}async function rM(X,J,$){let{record:Y}=$;if($.fresh)await sM(X,Y),await X.onStep("after-record-write");if(await cB(X,$.credential.refresh))return{status:"restart"};let G=await P3(X);if(G.kind!=="real"||G.fingerprint!==Y.slotFingerprint)return{status:"restart"};return await cM(X,Y,$.credential),await X.onStep("after-row-write"),lB(X,J,Y,$.fresh?Y.operation:"resumed")}async function lB(X,J,$,Y){let G=await lM(X,$);if(!G)return{status:"retry",reason:"verify-failed"};if(await X.onStep("after-verify"),$.carryLegacyMain)await iM(X,G),await X.onStep("after-carry-over");let Q=await aM(X,J,$,Y);if(Q.status==="untagged-placeholder"){await X.store.disable($.rowId,R$,{extraLocks:y8(X.paths,$.rowId,X.locks),attribution:{credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}}}),await G4(X,J);let z=`${X.paths.configPath}\x00${$.rowId}`;if(!yB.has(z))yB.add(z),X.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${C$}`,{rowId:$.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(Q.status!=="foreign-placeholder")return Q;return await X.store.remove($.rowId,{extraLocks:y8(X.paths,$.rowId,X.locks),protect:(z,Z)=>Z.row?.fingerprint!==$.credentialFingerprint?"the transfer row changed before rollback":void 0}),await E$(X),await S$(X),{status:"refused",reason:"placeholder-without-main"}}var wB=new Set,vB=new Set,yB=new Set;function T$(X){return`openai-auth-pool:${EM("sha256").update(bM(X.paths.configPath)).digest("hex")}`}async function tM(X){try{let J=await X();return J.open?[]:J.blockers}catch(J){return[{pid:"unknown",version:"unknown",detail:J instanceof Error?J.message:String(J)}]}}async function dB(X,J,$){let Y=wM(X),G=Y.slot.migrationDisabledReason?.();if(G){let B=Y.slot.path??z4();if(!vB.has(B))vB.add(B),Y.log.info("account pool migration is off: the host login slot is read-only",{reason:G});return{status:"slot-read-only",reason:G}}let Q;try{Q=await Q4(Y.paths.configPath)}catch(B){return{status:"error",reason:B instanceof Error?B.message:String(B)}}let z=await iB(Y,J,Q);if(z){if(z.status==="already-migrated"&&"mainAccountId"in Q)await S$(Y);return z}if($){let B=await tM($);if(B.length>0){let H=`${Y.paths.configPath}\x00${B.map((U)=>`${U.pid}@${U.version}`).join(",")}`;if(!wB.has(H))wB.add(H),Y.log.info("account pool migration deferred: an older openai-auth version is running",{blockers:B});return{status:"deferred",reason:"older-version-running",blockers:B}}}let Z,W;try{W=await L3(Y,"pool-slot-transfer",Y.slot.path??z4(),Y.locks.mainRefreshTtlMs),Z=await L3(Y,hB,Y.paths.configPath,Y.locks.mainRefreshTtlMs)}catch(B){if(await W?.release().catch(()=>{}),B instanceof N3)return{status:"retry",reason:"lock-contention"};throw B}try{return await eM(Y,J)}catch(B){if(B instanceof N3)return{status:"retry",reason:"lock-contention"};if(B instanceof K0)return{status:"retry",reason:B.kind==="lock-contention"?"lock-contention":`store-${B.kind}`};throw B}finally{await Z?.release().catch(()=>{}),await W?.release().catch(()=>{})}}async function iB(X,J,$){let Y=j6($);if(Y.pending)return;if(J==="migrate"&&Y.migratedAt!==void 0){let G=await X.store.read();if(G.status==="ready"&&!G.rows.some((Q)=>Q.id==="main")&&!Y.pending&&w7(await P3(X),G.rows.some((Q)=>Q.id==="main"),Y))return{status:"refused",reason:"placeholder-without-main"};return{status:"already-migrated"}}if(J==="adopt"&&Y.migratedAt===void 0)return{status:"not-migrated"};return}async function eM(X,J){let $;for(let Y=0;Y<4;Y++){let G=await Q4(X.paths.configPath),Q=await iB(X,J,G);if(Q){if(Q.status==="already-migrated")await S$(X);return Q}let z=await X.store.read(),Z=j6(G);if(z.status==="pending-migration"){if(w7(await P3(X),z.roster.some((U)=>t6(U)&&U.id==="main"),Z))return{status:"refused",reason:"placeholder-without-main"};await X.store.initialize(),await X.onStep("after-pool-key-write"),z=await X.store.read()}if(z.status!=="ready")return{status:"error",reason:z.status==="error"?`${z.file}: ${z.reason}`:"pool still pending migration"};let W=await gM(X);if(W.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(W.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(w7(W,z.rows.some((U)=>U.id==="main"),Z))return{status:"refused",reason:"placeholder-without-main"};let B=pM(J,Z,z.rows,W,$,X.now(),X.newId);if(B.kind==="nothing"){if(J==="migrate")await G4(X,J),await X.onStep("after-marker-write");return{status:"nothing-to-import",slot:B.slot}}if(B.kind==="drop-record"){await E$(X),await X.onStep("after-record-clear");continue}if(B.kind==="ambiguous")return await G4(X,J,{declinedSlotFingerprint:B.record.slotFingerprint}),await X.onStep("after-record-clear"),X.log.warn("interrupted slot transfer left alone: the row was rotated since, so the slot copy may be stale; the next login resolves it",{rowId:B.record.rowId}),{status:"ambiguous",rowId:B.record.rowId};if(B.kind==="transfer"&&B.fresh)$=B.record.rowId;let H=B.kind==="finish"?await lB(X,J,B.record,"resumed"):await rM(X,J,B);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function S$(X){await F3(X,(J)=>{if(!("mainAccountId"in J))return!1;if(j6(J).pending)return!1;return delete J.mainAccountId,!0})}function g7(X){return dB(X,"migrate",X.fence)}function m7(X){return dB(X,"adopt")}class nB extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function y8(X,J,$={}){let Y={...v7,...$},G={renew:Y.renew,timeoutMs:Y.timeoutMs,retryMs:Y.retryMs,...Y.renewIntervalMs!==void 0?{renewIntervalMs:Y.renewIntervalMs}:{}};return[{name:h8,path:X.configPath,ttlMs:Y.mainRefreshTtlMs,...G},{name:iJ(J),path:X.configPath,ttlMs:Y.fallbackTtlMs,...G}]}async function sB(X,J,$,Y={}){let G=X.now??Date.now,Q=X.sleep??((W)=>new Promise((B)=>setTimeout(B,W))),z=X.leaseWait??{timeoutMs:4000,pollMs:50},Z=async(W,B)=>{let H=Q8(W.refresh),U=async()=>{let j=await b0(X.paths),q=j?.refresh?.mainRefreshLeaseUntil;return Boolean(q&&q>G()&&j?.refresh?.mainRefreshLeaseTokenHash===H)};if(await U()){let j=G()+z.timeoutMs;while(G()<j&&await U())await Q(z.pollMs);throw new nB}return $(W,B)};return X.store.refresh(J,Z,{...Y,extraLocks:y8(X.paths,J,X.legacyLocks)})}var G_="openai",tB=250,h8="main-refresh";function I$(X){if(typeof X.access!=="string"||typeof X.refresh!=="string")return;let J=Buffer.from(X.access),$=Buffer.from(X.refresh),Y=(G)=>{let Q=Buffer.alloc(4);return Q.writeUInt32BE(G.length),Q};return X_("sha256").update(Y(J)).update(J).update(Y($)).update($).digest("hex")}function YH(X){if(!X||typeof X!=="object")return;let J=X;if(J.type!=="oauth")return;return{type:"oauth",...typeof J.access==="string"?{access:J.access}:{},...typeof J.refresh==="string"?{refresh:J.refresh}:{},...typeof J.expires==="number"?{expires:J.expires}:{},...typeof J.accountId==="string"?{accountId:J.accountId}:{}}}function aB(X){let J=YH(X);if(typeof J?.access!=="string"||typeof J.refresh!=="string")return;return{access:J.access,refresh:J.refresh,...typeof J.expires==="number"?{expires:J.expires}:{}}}function O3(X){if(j1(X)&&X.type==="api"&&typeof X.key==="string")return{kind:"api"};let J=YH(X);if(!J)return{kind:"indeterminate"};return T0(J)?{kind:"tombstone",oauth:J}:{kind:"real",oauth:J}}async function eB(X){return X.auth.get({path:{id:G_}})}async function XH(X){return Object.keys(await X.auth.all()).length>0}async function oB(X){let J=await eB(X.client);if(J!==void 0)return O3(J);let $=await XH(X.client),Y=X.now();if(await X.sleep(tB),X.now()-Y<tB)return{kind:"indeterminate"};let G=await eB(X.client);if(G!==void 0)return O3(G);let Q=await XH(X.client);return $&&Q?{kind:"slot-absent"}:{kind:"indeterminate"}}function z4(X=process.env,J=$_()){let $=X.XDG_DATA_HOME||rB(J,".local","share");return rB($,"opencode","auth.json")}function j1(X){return!!X&&typeof X==="object"&&!Array.isArray(X)}var JH=(X)=>X===void 0||typeof X==="string";function Q_(X){if(!j1(X))return!1;switch(X.type){case"oauth":return typeof X.refresh==="string"&&typeof X.access==="string"&&typeof X.expires==="number"&&Number.isSafeInteger(X.expires)&&X.expires>=0&&JH(X.accountId)&&JH(X.enterpriseUrl);case"api":return typeof X.key==="string"&&(X.metadata===void 0||j1(X.metadata)&&Object.values(X.metadata).every((J)=>typeof J==="string"));case"wellknown":return typeof X.key==="string"&&typeof X.token==="string";default:return!1}}async function b$(X,J=process.env){let $=J.OPENCODE_AUTH_CONTENT;if($)try{let G=JSON.parse($);return j1(G)?G:{}}catch{}let Y;try{Y=JSON.parse(await J_(X,"utf8"))}catch{return{}}if(!j1(Y))return{};return Object.fromEntries(Object.entries(Y).filter(([,G])=>Q_(G)))}function $H(X){if(!X.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(X.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class u7 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function z_(X){let J=X.env??process.env,$=X.path??z4(J),Y=new Map;return{path:Y_($),migrationDisabledReason:()=>$H(J)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(G){let Q=(await b$($,J))[G.path.id];return Y.set(G.path.id,JSON.stringify(Q)),Q},async all(){return b$($,J)},async set(G){if($H(J))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let Q=(await b$($,J))[G.path.id];if(D3(G.body)&&(!Y.has(G.path.id)||Y.get(G.path.id)!==JSON.stringify(Q)))throw new u7;let z=await X.set(G);if(j1(z)&&"error"in z&&z.error!==void 0)throw Error(`OpenCode refused the write of its ${G.path.id} login: ${JSON.stringify(z.error)}`);return z}}}function GH(X,J={}){let $=j1(X)?X.auth:void 0,Y=$&&typeof $==="object"?$.set:void 0;if(typeof Y!=="function")return{reason:"the OpenCode client has no auth.set to write its login slot with"};return{slot:z_({...J,set:(G)=>Y.call($,G)})}}import{readFileSync as Z_}from"node:fs";var W_="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function B_(X){return`The account-pool migration is moving OpenCode's login into \`${X}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function Z4(X,J={}){return G8({provider:"openai",configPath:X.configPath,statePath:X.statePath,quota:f8,...J})}function k$(X){try{let J=JSON.parse(Z_(X,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return j6(J).migratedAt!==void 0}catch{return!1}}async function p7(X,J){if(!k$(X.configPath))return;let $=await J.read();return $.status==="ready"?$.rows:void 0}function c7(X,J){if(X===V8)return W_;if(j6(J.config).pending?.rowId===X)return B_(X);return}function H_(X,J){return y8(X,V8,J.legacyLocks).filter(($)=>$.name===h8)}function z9(X,J={}){return H_(X,J)}var W4="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class q1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function QH(X){let J=X.storage,$=G9(J);if(!J||!$||T0($))return;let Y=$,G=X.now(),Q=(J.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Y.access||!Y.expires||Y.expires-G<=Q)&&!t0(Y.lastRefreshError,Y.refresh,G))try{Y=await X.refreshAccount(Y,J)}catch(W){X.warn?.("pool main row refresh failed",{error:W instanceof Error?W.message:String(W)})}let Z=Y.access?.trim();if(!Z)return;if(typeof Y.expires!=="number"||Y.expires<=X.now())return;return{account:Y,token:Z}}import{readdir as V_,readFile as U_}from"node:fs/promises";import{homedir as K_}from"node:os";import{join as B4}from"node:path";function ZH(){return process.env.XDG_STATE_HOME||B4(K_(),".local","state")}function j_(X=ZH()){return B4(X,"cortexkit","openai-auth","processes")}function q_(X=ZH()){return B4(X,"cortexkit","openai-auth","rpc")}function N_(X){try{return process.kill(X,0),!0}catch(J){return J.code==="EPERM"}}function zH(X){let J=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(X.trim());if(!J)return;return{core:[Number(J[1]),Number(J[2]),Number(J[3])],pre:J[4]?J[4].split("."):[]}}function L_(X,J){let $=zH(X),Y=zH(J);if(!$||!Y)return;for(let G=0;G<3;G++){let Q=$.core[G]-Y.core[G];if(Q!==0)return Math.sign(Q)}if($.pre.length===0||Y.pre.length===0)return Math.sign(Y.pre.length-$.pre.length);for(let G=0;G<Math.max($.pre.length,Y.pre.length);G++){let Q=$.pre[G],z=Y.pre[G];if(Q===void 0)return-1;if(z===void 0)return 1;let Z=/^\d+$/.test(Q),W=/^\d+$/.test(z);if(Z&&W){let B=Number(Q)-Number(z);if(B!==0)return Math.sign(B)}else if(Z!==W)return Z?-1:1;else if(Q!==z)return Q<z?-1:1}return 0}async function x$(X){try{return{ok:!0,names:await V_(X)}}catch(J){let $=J.code;if($==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:$,error:`${X}: ${String(J)}`}}}async function D_(X,J){let $;try{$=await U_(X,"utf8")}catch(Y){if(Y.code==="ENOENT")return{kind:"gone"};return{kind:"unreadable"}}try{let Y=JSON.parse($);if(Y!==null&&typeof Y==="object"&&Y.pid===J&&typeof Y.version==="string")return{kind:"ok",version:Y.version}}catch{}return{kind:"unreadable"}}async function H4(X){let J=X.isAlive??N_,$=X.selfPid??process.pid,Y=new Map,G=(q)=>{let K=q.pid==="unknown"?`dir:${q.detail}`:q.pid;if(!Y.has(K))Y.set(K,q)},Q=(q)=>{try{return J(q)}catch{return!0}},z=(q,K)=>{let L=K.exec(q),F=L?Number(L[1]):Number.NaN;return Number.isSafeInteger(F)&&F>=1?F:void 0},Z=j_(X.stateHome),W=new Set,B=await x$(Z);if(!B.ok)G({pid:"unknown",version:"unknown",detail:B.error});for(let q of B.ok?B.names:[]){let K=z(q,/^(\d+)\.json$/);if(K===void 0||K===$)continue;let L=B4(Z,q),F=await D_(L,K);if(F.kind==="gone")continue;if(W.add(K),!Q(K))continue;if(F.kind==="unreadable"){G({pid:K,version:"unknown",detail:L});continue}let O=L_(F.version,X.currentVersion);if(O===void 0||O<0)G({pid:K,version:F.version,detail:L})}let H=X.rpcDir??q_(X.stateHome),U=await x$(H);if(!U.ok)G({pid:"unknown",version:"unknown",detail:U.error});for(let q of U.ok?U.names:[]){if(!l7(q))continue;let K=B4(H,q),L=await x$(K);if(!L.ok){if(L.code==="ENOTDIR")continue;G({pid:"unknown",version:"unknown",detail:L.error});continue}for(let F of L.names){let O=z(F,/^port-(\d+)\.json$/);if(O===void 0||O===$||W.has(O))continue;if(Q(O))G({pid:O,version:"unknown",detail:B4(K,F)})}}let j=(q)=>q.pid==="unknown"?Number.POSITIVE_INFINITY:q.pid;return Y.size===0?{open:!0}:{open:!1,blockers:[...Y.values()].sort((q,K)=>j(q)-j(K))}}var S9="1.0.0";import{readFile as BH}from"node:fs/promises";function d7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}async function HH(X){let J=await gJ(X.configPath),$=[];try{let G=JSON.parse(await BH(X.statePath,"utf8"));if(d7(G)){let Q=G.accounts;if(d7(Q))$=Object.keys(Q)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:J?[...J]:[],stateIds:$,orphanStateIds:J?$.filter((G)=>!J.has(G)):[]}}async function F_(X){try{let J=JSON.parse(await BH(X.configPath,"utf8"));return d7(J)&&d7(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var WH="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function VH(X){if(!X)return;let J=X.accounts.find(($)=>$.id==="main"&&v0($));if(J)return J;if(!X.mainAccountId)return;return X.accounts.find(($)=>v0($)&&$.accountId===X.mainAccountId)}function P_(X,J){let $=X.lastRefreshError;return t0($,X.refresh,J)&&$!==void 0&&$.nextRetryAt!==void 0&&$.nextRetryAt-$.checkedAt>=A5}function O_(X){let J=[],$=[],Y=X.now??Date.now(),G=VH(X.storage),Q=!1;if(T0(X.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${WH}`});else if(R6(X.auth)){if(!G9(X.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!X.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),Q=!0;else if(X.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),Q=!0;else if(G&&(!X.auth.refresh||G.refresh!==X.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),Q=!0;if(Q&&G){let W={type:"restore-main-credential"};$.push(W);let B=J.find((H)=>H.code==="auth-slot-missing"||H.code==="auth-slot-not-oauth"||H.code==="main-refresh-not-in-store");if(B)B.repair=W}let z=X.storage?.accounts??[];if(z.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!z.some((W)=>W.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let W of z){if(!v0(W)||!T0(W))continue;J.push({code:"tombstoned-account",accountId:W.id,message:`Account ${W.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${WH}`})}if(X.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let W of z){if(!v0(W))continue;if(!P_(W,Y))continue;let B={type:"clear-refresh-backoff",accountId:W.id};$.push(B),J.push({code:"armed-non-transient-refresh-backoff",accountId:W.id,message:`Account ${W.id} has an armed non-transient refresh backoff.`,repair:B})}let Z=[...X.orphanStateIds??[]];if(Z.length>0){let W={type:"prune-orphan-state-ids",ids:Z};$.push(W),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${Z.join(", ")}.`,repair:W})}return{findings:J,repairs:$}}function UH(X){let J=($)=>{if($.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(R6(await X.readAuth()))return;let Y=VH(await X.loadAccounts(X.paths));if(!Y)return;await X.setMainAuth({refresh:Y.refresh,access:Y.access??"",expires:Y.expires??0})}};if(X.migrated)return;if($.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${$.ids.join(", ")}`,apply:async()=>{await X.mutateAccounts((Y)=>Y,X.paths)}};return{label:`Clear the refresh backoff of ${$.accountId}`,apply:async()=>{await X.mutateAccounts((Y)=>{let G=Y.accounts.find((Q)=>Q.id===$.accountId&&v0(Q));if(G)G.lastRefreshError=void 0;return Y},X.paths)}}};return[{id:"openai-auth",run:async()=>{let[$,Y,G,Q]=await Promise.all([X.loadAccounts(X.paths),X.readStoreIds(X.paths),X.readAuth(),F_(X.paths)]),z=O_({auth:G.type==="missing"?void 0:G,storage:$,orphanStateIds:Y.orphanStateIds,retiredCustodyMode:Q,now:X.now()}),Z=await G8({provider:"openai",quota:f8,configPath:X.paths.configPath,statePath:X.paths.statePath}).read();if(Z.status==="ready")for(let W of Z.rows){if(W.disabledReason!==R$)continue;z.findings.push({code:"slot-transfer-origin-unknown",accountId:W.id,message:`Account ${W.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${C$}`})}return z.findings.map((W)=>{let B=W.repair?J(W.repair):void 0;return{code:W.code,message:W.message,...W.accountId!==void 0?{accountId:W.accountId}:{},...B?{repair:B}:{}}})}}]}var __=jH,KH="OpenAI accounts",A_="ChatGPT accounts in the vault",T_="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function R_(){let{redirectUri:X}=await k5(),J=await I5(),$=S2(crypto.getRandomValues(new Uint8Array(32)).buffer),Y=b5(X,J,$),G=x5(J,$);return{url:Y,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let Q=await G;return{type:"success",refresh:Q.refresh_token,access:Q.access_token,expires:Date.now()+(Q.expires_in??3600)*1000,accountId:z8(Q)}}finally{e8($)}}}}async function C_(X){let{deviceData:J,url:$,instructions:Y}=await w5(X);return{url:$,instructions:Y,method:"auto",async callback(){try{let G=await v5(J,X);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:z8(G)}}catch{return{type:"failed"}}}}}function qH({client:X,getAuth:J,getPaths:$=()=>M0(V0()),fetchImpl:Y=fetch,packageVersion:G=S9,dependencies:Q,onMainSlotWritten:z,vault:Z}){let W={authorizeBrowser:Q?.authorizeBrowser??R_,authorizeHeadless:Q?.authorizeHeadless??(()=>C_(G)),beginAccountLogin:Q?.beginAccountLogin??I2,loadAccounts:Q?.loadAccounts??b0,mutateAccounts:Q?.mutateAccounts??j7,readStoreIds:Q?.readStoreIds??HH,openBrowser:Q?.openBrowser??__,now:Q?.now??Date.now,openAccountPool:Q?.openAccountPool??Z4,migrationBlockers:Q?.migrationBlockers??(async()=>{let N=await H4({currentVersion:G});return N.open?[]:N.blockers.map((P)=>({pid:P.pid,version:P.version}))}),...Q?.terminal?{terminal:Q.terminal}:{},...Q?.vaultWait?{vaultWait:Q.vaultWait}:{}},B=async()=>await J?.().catch(()=>{return})??{type:"missing"},H=async()=>{if(Z&&await Z.authority()!=="local")return!0;if((await B()).type!=="missing")return!0;let N=$(),P=W.openAccountPool(N);if((await P.read()).status==="ready")return Z$(P);return((await W.loadAccounts(N))?.accounts.length??0)>0},U=async(N)=>{if(await fB($().configPath,async()=>{if(Z&&await Z.authority()!=="local")return!1;if(R6(await B()))return!1;return await X.auth.set({path:{id:"openai"},body:{type:"oauth",...N}}),!0}))await z?.().catch(()=>{})},j=(N)=>({begin:async({headless:P,signal:A})=>{if(Z&&await Z.authority()!=="local")throw Error(v8);let T=await W.beginAccountLogin({version:G,headless:P,...A?{signal:A}:{}});return{url:T.url,instructions:T.instructions,completion:T.completion.then(async(b)=>{if(Z&&await Z.authority()!=="local")throw Error(v8);let p=await N.read(),i=p.status==="ready"?p.rows.find((w)=>w.id===V8)?.identity:void 0;if(b.accountId&&i&&b.accountId===i)throw Error("that account is already the OpenCode main credential");return{id:b.id,credential:{type:"oauth",refresh:b.refresh,...b.access!==void 0?{access:b.access}:{},...b.expires!==void 0?{expires:b.expires}:{}},...b.accountId!==void 0?{identity:b.accountId}:{},...b.label!==void 0?{label:b.label}:{}}})}},openBrowser:(P)=>W.openBrowser(P)}),q=async(N)=>{if(Z&&await Z.authority()!=="local")throw Error(v8);let P=N.credential;if(P?.type!=="oauth"||!P.access)throw Error("no usable access token for a quota check");let A=await E8({accessToken:P.access,fetchImpl:Y,now:W.now,...N.identity?{accountId:N.identity}:{},accountKey:N.id});return C9(A,W.now(),!0)},K=(N)=>UH({paths:$(),migrated:N,readAuth:B,loadAccounts:W.loadAccounts,readStoreIds:W.readStoreIds,mutateAccounts:W.mutateAccounts,setMainAuth:U,now:W.now}),L=(N,P)=>({title:KH,store:R7(P,{rowLocks:(A)=>y8(N,A)}),...W.terminal?{terminal:W.terminal}:{},login:j(P),protect:(A,T)=>c7(A,T),extraLocks:z9(N),pollQuota:q,doctor:K(!0),status:async()=>{let A=await Z?.status();if(Z&&await Z.authority()!=="local"&&A)return[H3(Z.host,Z.name,A.enrollment)];return[`Routing: ${(await W.loadAccounts(N))?.routing?.mode??"main-first"}`,...Z?[H3(Z.host,Z.name,(await Z.status()).enrollment)]:[]]},...Z?{extraActions:[F(Z)]}:{}}),F=(N)=>{let P=N.enrolled();return{id:P?"vault-disconnect":"vault-connect",label:P?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(A)=>{let T=await N.authority();if(P){if(T!=="local")await N.disconnect();A.print("Disconnected from the Claustrum vault.");return}if(T!=="local"){A.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}A.print(`Asking the Claustrum vault to enroll ${N.name}…`);let b,p=await N.waitForApproval({...W.vaultWait,onPending:(i)=>{let X0=i.state==="pending"?i.requestId??i.retryCode??"":i.state;if(X0===b)return;b=X0;for(let w of e1(N.name,i))A.print(w);A.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});A.print(V3(N,p).text)}}},O=async()=>{let N=await W.migrationBlockers();return B1({title:KH,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...N.length>0?["These processes still hold the move back:",...N.map((P)=>` ${P.pid==="unknown"?"processes that could not be read":`pid ${P.pid}`}: version ${P.version}`)]:[]],actions:[U3({checks:K(!1)})],...W.terminal?{terminal:W.terminal}:{}})},_=async(N)=>{let P=$(),A=W.openAccountPool(P);if(Z&&await Z.authority()!=="local")return j3(L(P,A),Z);if(await p7(P,A)===void 0)return O();let T=L(P,A);return Z?j3(T,Z):V$(T)},C=(N)=>async()=>{if(Z&&await Z.authority()!=="local")throw Error(v8);let P=await N();if(P.method!=="auto")return P;return{...P,callback:async()=>{let A=await P.callback();if(Z&&await Z.authority()!=="local")return{type:"failed"};return A}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:K$({hasCredential:H,openMenu:_,login:C(()=>W.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:C(()=>W.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...Z?.enrolled()?[{label:A_,type:"oauth",authorize:async()=>({url:"",instructions:T_,method:"auto",callback:async()=>{if(await r4(Z.paths,Z.name)!=="vault")return{type:"failed"};try{let N=JSON.parse(await M_(z4(),"utf8"));if(!N||typeof N!=="object"||Array.isArray(N)||Object.hasOwn(N,"openai"))return{type:"failed"}}catch(N){if(N.code!=="ENOENT")return{type:"failed"}}return{...K1,type:"success"}}})}]:[]]}var w$={rpcRoot:"openai-auth",directoryPrefix:FH,registrationSessionId:"process"};function i7(X,J){NH(w$,X,J)}function PH(X=0,J){return LH(w$,X,J)}function OH(X){return DH(w$,X)}var n7=Z0("commands");function V4(X){return{configPath:X.accountStoragePath,statePath:X.accountStatePath}}function v$(X){return`${String(X.startHour).padStart(2,"0")}-${String(X.endHour).padStart(2,"0")}`}function E_(X){let J=/^(\d{1,2})-(\d{1,2})$/.exec(X.trim());if(!J)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let $=Number(J[1]),Y=Number(J[2]);if($>23||Y>23||$===Y)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:$,endHour:Y}}var S_="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore enabling sustain with Magic Context, set a non-expiring `cache_ttl` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.";function I_(X){let J=($)=>V1(X.store(),z9(V4(X)),(Y)=>{let G={...Y.cacheKeep??{}};$(G),Y.cacheKeep=G});return{title:"Cache",build:async()=>{let $=X.cacheKeepManager;if(!$)return{lines:["Keep-warm unavailable"]};let Y=q7(await X.loadAccounts(V4(X))),G=Y?.enabled===!0,Q=Y?.subagents===!0,z=$.status(),Z=z.window?v$(z.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${z.tracked===0?"no sessions":`${z.tracked} session${z.tracked===1?"":"s"}`}`,`Timer ${z.running?"armed":"idle"} · subagents ${Q?"on":"off"} · sustain ${z.sustain?"on":"off"}`,`Window ${Z}`,`TTL ${Math.round(z.ttlMs/1000)}s · lead ${Math.round(z.leadMs/1000)}s · idle cap ${Math.round(z.maxIdleWarmMs/60000)}min (subagents ${Math.round(z.maxSubagentIdleMs/60000)}min)`],items:z.targets.map((W)=>({id:W.sessionKey,label:W.sessionKey,group:"Sessions",detail:[W.accountId??"main",`expires in ${Math.ceil((W.cacheExpiresAt-z.generatedAt)/1000)}s`,...W.lastWarmedAt?[`last warm ${Math.ceil((z.generatedAt-W.lastWarmedAt)/1000)}s ago`]:[],...W.backoffUntil&&W.backoffUntil>z.generatedAt?[`backoff ${Math.ceil((W.backoffUntil-z.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:W})=>{let B=W.enabled===!0;if(await J((H)=>{H.enabled=B}),X.setCacheKeepEnabled?.(B),B)$.start();else $.stop();return n7.info(B?"cachekeep enabled":"cachekeep disabled"),B?`Keep-warm is on. TTL ${Math.round(z.ttlMs/1000)}s, idle cap ${Math.round(z.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:Q?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!Q}],run:async({values:W})=>{let B=W.subagents===!0;return await J((H)=>{H.subagents=B}),X.setCacheKeepSubagents?.(B),`Subagent warming is ${B?"on":"off"}.`}},{id:"sustain",label:z.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!z.sustain}],run:async({values:W})=>{let B=W.sustain===!0;return await J((H)=>{H.sustain=B}),X.setCacheKeepSustain?.(B),B?S_:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...z.window?{value:v$(z.window)}:{}}],run:async({values:W})=>{let B=W.window;if(typeof B!=="string"||B.trim()==="")return await J((q)=>{delete q.startHour,delete q.endHour}),X.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let H=E_(B);if(!H.ok)return{ok:!1,text:`Invalid window: ${H.reason}`};let{startHour:U,endHour:j}=H;return await J((q)=>{q.startHour=U,q.endHour=j}),X.setCacheKeepWindow?.({startHour:U,endHour:j}),`Warming limited to ${v$(H)} local hours.`}}]}}}}var MH=["error","warn","info","debug","trace"];function b_(X){return{title:"Diagnostics",build:async()=>{let J=u6(),Y=(await X.loadAccounts(V4(X)))?.logging?.level??"info";return{lines:[`Dumps ${J.dump?"on":"off"}`,`Dump directory: ${J.dumpDir}`,`Log level: ${Y}`],actions:[{id:"dump",label:J.dump?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!J.dump}],run:async({values:G})=>{let Q=G.enabled===!0;await V1(X.store(),z9(V4(X)),(Z)=>{Z.dump={...Z.dump??{},enabled:Q}});let z=SB();return n7.info(Q?"request dump enabled":"request dump disabled"),Q?`Request dumps are on, written to ${z.dumpDir}.
158
-
159
- Body dumps may contain prompt and session content. Turn this off after debugging.`:"Request dumps are off."}},{id:"logging",label:"Set the log level",knobs:[{kind:"choice",id:"level",label:"Level",choices:MH.map((G)=>({value:G,label:G})),value:MH.includes(Y)?Y:"info"}],run:async({values:G})=>{let Q=String(G.level);return await V1(X.store(),z9(V4(X)),(z)=>{z.logging={...z.logging??{},level:Q}}),s7(Q),n7.info("log level changed",{level:Q}),`Log level set to ${Q}.`}}]}}}}async function k_(X){let J=await X.store().read(),$=J.status==="ready"?J.rows:[];return[...new Set(["main",...$.filter((Y)=>Y.enabled&&Y.type==="oauth").map((Y)=>Y.id)])]}function _H(X){let J=V4(X),$=z9(J),Y=X.resolveResetTarget&&X.refreshResetTargetQuota&&X.fetchImpl&&X.now&&X.randomUUID?O$({configPath:J.configPath,statePath:J.statePath,quotaManager:X.quotaManager,loadAccounts:X.loadAccounts,mutateAccounts:D$(X.store(),$),resolveResetTarget:X.resolveResetTarget,refreshResetTargetQuota:X.refreshResetTargetQuota,fetchImpl:X.fetchImpl,now:X.now,randomUUID:X.randomUUID,accountKeys:()=>k_(X)}):void 0,G=X.beginAccountLogin;return M$({store:X.store(),...X.vault?{vault:X.vault}:{},...X.now?{now:X.now}:{},extraLocks:$,rowLocks:(Q)=>y8(J,Q),migration:X.migration,...G?{login:{begin:(Q)=>G({...Q,version:X.packageVersion}),mainIdentity:async()=>{let Q=await X.store().read();if(Q.status!=="ready")return;return Q.rows.find((z)=>z.id==="main")?.identity}}}:{},protect:(Q,z)=>c7(Q,z),...X.refreshAllQuota?{quotaCheck:async(Q)=>{if(Q.length===1){let W=X.store();for(let B of Q)await W.requestReading(B);await W.pullsSettled();return}let Z=(await X.refreshAllQuota?.()??[]).filter((W)=>!W.ok);if(Z.length>0)throw new I6("quota-check-failed",Z.map((W)=>W.permanent?`${W.account}: sign-in no longer accepted — remove and add this account again`:`${W.account}: fetch failed — check again to retry`).join(`
160
- `))}}:{},cache:I_(X),diagnostics:b_(X),extras:[...Y?[Y]:[],F$({...X.getStickyRouting?{getPin:X.getStickyRouting}:{},...X.clearStickyRouting?{clearPin:X.clearStickyRouting}:{}}),...X.vault?[P$({vault:X.vault,changed:X.afterWrite})]:[]],afterApply:async()=>{await X.afterWrite?.(),await X.refreshSidebar?.().catch(()=>{})}})}function AH(X){return(J,$="info")=>{n7.info("menu notification",{sessionId:X,kind:$}),i7({command:m6,notify:{message:J,kind:$}},X)}}function TH(X,J){return _H(X).open({...J!==void 0?{sessionId:J}:{},notify:AH(J)})}function RH(X,J){return _H(X).apply(J,{...J.sessionId!==void 0?{sessionId:J.sessionId}:{},notify:AH(J.sessionId)})}function CH(X){let J=[`## ${X.title}`];for(let $ of X.sections){J.push("",`### ${$.title}`);for(let Y of $.lines)J.push(Y);for(let Y of $.items){let G=Y.detail??Y.status;J.push(`- ${Y.label}${G?`: ${G}`:""}`)}}return J.push("","Open the OpenCode TUI to change these settings."),J.join(`
161
- `)}var x_=300000,w_=30000,EH=240000,v_="bg-quota-refresh",y_=120000;function y$(X,J){return g0({name:v_,ttlMs:y_,path:X,renew:!0,...J})}function SH(X,J=J4,$=()=>y$(X.paths.configPath)){return h_(X,J,$)}function h_(X,J,$){return IH(async()=>J({...X,respectBackoff:!0,skipFresherThanMs:EH}),$,[])}async function IH(X,J,$){let Y;try{Y=await J()}catch{Y=void 0}if(Y===null)return $;try{return await X()}finally{await Y?.release().catch(()=>{})}}function bH(X,J,$){return IH(async()=>{return await X.refreshDueTokens(J),X.pollRows(J,{skipReadWithinMs:EH})},$,[])}class h${setIntervalFn;clearIntervalFn;random;onError;run;timer;tickPromise;stopped=!1;constructor(X={}){this.setIntervalFn=X.setIntervalFn??setInterval,this.clearIntervalFn=X.clearIntervalFn??clearInterval,this.random=X.random??Math.random,this.onError=X.onError}start(X,J=this.onError){if(this.run=X,this.onError=J,this.stopped=!1,this.timer)return;let $=Math.round((this.random()*2-1)*w_);if(this.timer=this.setIntervalFn(()=>{let Y=this.run;if(this.stopped||!Y||this.tickPromise)return;let G=Y().catch((Q)=>{try{this.onError?.(Q)}catch{}}).finally(()=>{if(this.tickPromise===G)this.tickPromise=void 0});this.tickPromise=G},x_+$),"unref"in this.timer)this.timer.unref()}stop(){if(this.stopped=!0,this.run=void 0,!this.timer)return;this.clearIntervalFn(this.timer),this.timer=void 0}isStopped(){return this.stopped}}function f$(X){if(!X||typeof X!=="object")return;let J=X,$=Number(J.startHour),Y=Number(J.endHour);if(!Number.isInteger($)||!Number.isInteger(Y)||$<0||$>23||Y<0||Y>23||$===Y)return;return{startHour:$,endHour:Y}}function M3(X,J=new Date){if(!X)return!1;let $=J.getHours();if(X.startHour<X.endHour)return $>=X.startHour&&$<X.endHour;return $>=X.startHour||$<X.endHour}var f_=300000,g_=3600000,m_=1800000,u_=60000,p_=32,c_=8388608,l_=30000,d_=600000;function g8(X,J){return typeof X==="number"&&Number.isFinite(X)&&X>0?X:J}function a7(X){return X instanceof Error?X.message:String(X)}class _3{targets=new Map;adapter;now;log;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;warmTimeoutMs;backoff;getWindow;getSustain;setIntervalImpl;clearIntervalImpl;timer=null;startedAt=null;totalBytes=0;tickPromise=null;disposed=!1;abortController=new AbortController;constructor(X){this.adapter=X.adapter,this.now=X.now,this.log=X.logger,this.ttlMs=g8(X.ttlMs,f_),this.tickIntervalMs=g8(X.tickIntervalMs,u_),this.leadMs=g8(X.leadMs,this.tickIntervalMs+15000),this.maxIdleWarmMs=g8(X.maxIdleWarmMs,g_),this.maxSubagentIdleMs=g8(X.maxSubagentIdleMs,m_),this.maxTargets=g8(X.maxTargets,p_),this.maxBytes=g8(X.maxBytes,c_),this.warmTimeoutMs=g8(X.warmTimeoutMs,l_),this.backoff=X.backoffMs??d_,this.getWindow=X.getWindow,this.getSustain=X.getSustain,this.setIntervalImpl=X.setIntervalImpl??globalThis.setInterval,this.clearIntervalImpl=X.clearIntervalImpl??globalThis.clearInterval}track(X){let{sessionKey:J,bodyText:$}=X;this.pruneStale();let Y=Buffer.byteLength($,"utf8");if(Y>this.maxBytes)return this.log?.debug("cachekeep track skipped (body exceeds maxBytes)",{sessionKey:J,bodyBytes:Y,maxBytes:this.maxBytes}),{tracked:!1,reason:"body-exceeds-max-bytes"};let G=this.getWindow?.();if(G&&!M3(G,new Date(this.now())))return this.log?.debug("cachekeep track skipped (outside window)",{sessionKey:J,startHour:G.startHour,endHour:G.endHour}),{tracked:!1,reason:"outside-window"};this.drop(J);while(this.targets.size>=this.maxTargets||this.totalBytes+Y>this.maxBytes&&this.targets.size>0){let H=this.leastRecentlyTouched();if(H===void 0)break;this.log?.debug("cachekeep evicted least recently used target",{sessionKey:H}),this.drop(H)}let Q=X.isSubagent===!0,z=X.accountId||void 0,Z=this.adapter.profile?.({bodyText:$,isSubagent:Q,accountId:z,meta:X.meta}),W=g8(Z?.ttlMs,this.ttlMs),B=this.now();return this.targets.set(J,{bodyText:$,bodyBytes:Y,accountId:z,isSubagent:Q,meta:X.meta,ttlMs:W,maxWarms:Z?.maxWarms!==void 0&&Z.maxWarms>0?Math.floor(Z.maxWarms):void 0,maxIdleMs:Z?.maxIdleMs!==void 0?g8(Z.maxIdleMs,this.idleDefault(Q)):void 0,cacheExpiresAt:B+W,lastRealRequestAt:B,failures:0,warmCount:0}),this.totalBytes+=Y,this.log?.debug("cachekeep captured target",{sessionKey:J,accountId:z}),this.start(),{tracked:!0}}remove(X){if(this.drop(X))this.log?.debug("cachekeep removed target",{sessionKey:X})}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.timer=this.setIntervalImpl(()=>{this.tick().catch((X)=>{this.log?.warn("cachekeep tick failed",{error:a7(X)})})},this.tickIntervalMs),typeof this.timer==="object"&&"unref"in this.timer)this.timer.unref();this.log?.debug("cachekeep started",{ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)this.clearIntervalImpl(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log?.debug("cachekeep stopped")}status(){let X=this.getWindow?.();return{running:this.timer!==null,tracked:this.targets.size,totalBytes:this.totalBytes,generatedAt:this.now(),startedAt:this.startedAt,ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,sustain:this.getSustain?.()===!0,...X?{window:X}:{},targets:[...this.targets].map(([J,$])=>({sessionKey:J,accountId:$.accountId,isSubagent:$.isSubagent,cacheExpiresAt:$.cacheExpiresAt,lastRealRequestAt:$.lastRealRequestAt,...$.lastWarmedAt!==void 0?{lastWarmedAt:$.lastWarmedAt}:{},...$.backoffUntil!==void 0?{backoffUntil:$.backoffUntil}:{},failures:$.failures,warmCount:$.warmCount,ttlMs:$.ttlMs,bodyBytes:$.bodyBytes}))}}tick(){if(this.tickPromise)return this.tickPromise;let X=this.runTick().finally(()=>{if(this.tickPromise===X)this.tickPromise=null});return this.tickPromise=X,X}async runTick(){this.pruneStale();let X=this.getWindow?.();if(X&&!M3(X,new Date(this.now())))return;let J=this.now(),$=J+this.leadMs;for(let[Y,G]of[...this.targets]){if(this.disposed)return;if(this.targets.get(Y)!==G)continue;if(G.backoffUntil!==void 0&&J<G.backoffUntil)continue;if(G.cacheExpiresAt>$)continue;await this.warm(Y,G)}}retireIfExpired(X,J){if(this.now()<J.cacheExpiresAt)return!1;return this.log?.debug("cachekeep retired target (cache lifetime ended)",{sessionKey:X,accountId:J.accountId,cacheExpiresAt:J.cacheExpiresAt,failures:J.failures}),this.drop(X),!0}isCurrent(X,J){return!this.disposed&&this.targets.get(X)===J}view(X,J){return{sessionKey:X,accountId:J.accountId,bodyText:J.bodyText,isSubagent:J.isSubagent,meta:J.meta,warmCount:J.warmCount,ttlMs:J.ttlMs}}fail(X,J,$,Y={}){if(!this.isCurrent(X,J))return;J.failures+=1;let G=typeof this.backoff==="function"?this.backoff({sessionKey:X,failures:J.failures}):this.backoff;J.backoffUntil=this.now()+(Number.isFinite(G)&&G>0?G:0),this.log?.warn($,{sessionKey:X,accountId:J.accountId,failures:J.failures,backoffUntil:J.backoffUntil,...Y})}async warm(X,J){if(this.retireIfExpired(X,J))return;let $=this.view(X,J);if(this.adapter.activeAccount){let H;try{H=await this.adapter.activeAccount(X,$)}catch(U){this.fail(X,J,"cachekeep skip (active account unknown)",{error:a7(U)});return}if(!this.isCurrent(X,J))return;if(H!==void 0&&H!==J.accountId){this.log?.debug("cachekeep dropped target (session changed account)",{sessionKey:X,accountId:J.accountId,activeAccountId:H}),this.drop(X);return}}let Y;try{Y=await this.adapter.buildBody($)}catch(H){this.fail(X,J,"cachekeep skip (replay body unbuildable)",{error:a7(H)});return}if(!this.isCurrent(X,J))return;if(this.retireIfExpired(X,J))return;let G=s4([AbortSignal.timeout(this.warmTimeoutMs),this.abortController.signal]),Q=G.signal,z,Z="";try{z=await this.adapter.send({target:$,body:Y,signal:Q}),Z=await z.text().catch(()=>"")}catch(H){this.fail(X,J,"cachekeep failed",{error:a7(H)});return}finally{G.dispose()}if(!this.isCurrent(X,J))return;if(!z.ok){this.fail(X,J,"cachekeep failed",{status:z.status,responseBody:Z.slice(0,600)});return}let W;try{W=this.adapter.readUsage?.({target:$,response:z,text:Z})}catch{}let B=this.now();if(J.cacheExpiresAt=B+J.ttlMs,J.lastWarmedAt=B,J.backoffUntil=void 0,J.failures=0,J.warmCount+=1,this.log?.debug("cachekeep fired",{sessionKey:X,accountId:J.accountId,warmCount:J.warmCount,...W}),J.maxWarms!==void 0&&J.warmCount>=J.maxWarms)this.log?.debug("cachekeep retired target (warm cap reached)",{sessionKey:X,warmCount:J.warmCount}),this.drop(X)}idleDefault(X){return X?this.maxSubagentIdleMs:this.maxIdleWarmMs}pruneStale(){let X=this.now(),J=this.getSustain?.()===!0;for(let[$,Y]of[...this.targets]){if(this.retireIfExpired($,Y))continue;if(J&&!Y.isSubagent)continue;let G=Y.maxIdleMs??this.idleDefault(Y.isSubagent);if(Y.lastRealRequestAt>=X-G)continue;this.log?.debug("cachekeep pruned idle target",{sessionKey:$,accountId:Y.accountId,lastRealRequestAt:Y.lastRealRequestAt,maxIdleMs:G}),this.drop($)}}leastRecentlyTouched(){let X,J=Number.POSITIVE_INFINITY;for(let[$,Y]of this.targets){let G=Math.max(Y.lastRealRequestAt,Y.lastWarmedAt??0);if(G<J)X=$,J=G}return X}drop(X){let J=this.targets.get(X);if(!J)return!1;return this.totalBytes-=J.bodyBytes,this.targets.delete(X),!0}}function g$(X){if(typeof X!=="string")return!1;try{let J=JSON.parse(X);return s(J)&&s(J.client_metadata)&&J.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function m$(X){if(typeof X!=="string")return X;try{let J=JSON.parse(X);if(!s(J)||!s(J.client_metadata))return X;if(!(("x-codex-turn-metadata"in J.client_metadata)||("x-codex-ws-stream-request-start-ms"in J.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in J.client_metadata)))return X;let $={...J.client_metadata};return delete $["x-codex-turn-metadata"],delete $["x-codex-ws-stream-request-start-ms"],delete $.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...J,client_metadata:$})}catch{return X}}function o7(X){if(X?.method?.toUpperCase()!=="POST")return X;let J=new Headers(X.headers);if(J.set("accept","text/event-stream"),J.set("content-type","application/json"),g$(X.body))J.set("x-openai-internal-codex-responses-lite","true");return{...X,headers:J,body:m$(X.body)}}function xH(X){if(!X.enabled||typeof X.body!=="string")return;let J=X.headers.has("x-parent-session-id");if(J&&!X.includeSubagents)return;let $=X.headers.get("session-id")??X.headers.get("x-opencode-session")??X.headers.get("x-session-affinity")??void 0;if(!$)return;let Y={};for(let G of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let Q=X.headers.get(G);if(Q)Y[G]=Q}return{sessionKey:$,bodyText:X.body,replayHeaders:Y,isSubagent:J}}function wH(X){return f$(X?.cachekeep)}var u$=1800000,i_=2,n_=2*u$+900000,s_=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/;function a_(X){try{let $=JSON.parse(X).model;if(typeof $!=="string")return!1;let Y=s_.exec($);if(!Y)return!1;let G=Number(Y[1]),Q=Y[2]===void 0?0:Number(Y[2]);return G>5||G===5&&Q>=6}catch{return!1}}function o_(X){if(!a_(X.bodyText))return;if(!X.isSubagent)return{ttlMs:u$};return{ttlMs:u$,maxWarms:i_,maxIdleMs:n_}}function r_(X){let $=JSON.parse(X);return $.store=!1,delete $.max_output_tokens,delete $.max_tokens,delete $.max_completion_tokens,JSON.stringify($)}function p$(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function vH(X){if(!X||typeof X!=="object")return p$();let J=X,$=Number(J.input_tokens)||Number(J.prompt_tokens)||0,Y=Number(J.output_tokens)||Number(J.completion_tokens)||0,G=J.input_tokens_details??J.prompt_tokens_details,Q=Number(G?.cached_tokens)||Number(J.cached_tokens)||0,z=$>0?Q/$:null;return{input_tokens:$,output_tokens:Y,cached_tokens:Q,hit_rate:z}}function t_(X){try{let J=JSON.parse(X);return vH(J.usage)}catch{return p$()}}function e_(X){let J,$=[],Y,G=()=>{if(!$.length)return;let Q=$.join(`
162
- `).trim();$=[];let z=J;if(J=void 0,!Q||Q==="[DONE]")return;try{let Z=JSON.parse(Q),W=Z.type??z;if(W!=="response.completed"&&W!=="response.done")return;let B=Z.response;Y=vH(B?.usage??Z.usage)}catch{}};for(let Q of X.split(/\r?\n/)){if(Q===""){G();continue}if(Q.startsWith("event:")){J=Q.slice(6).trim();continue}if(Q.startsWith("data:"))$.push(Q.slice(5).trim())}return G(),Y??p$()}function yH(X,J,$=Date.now()){if(!J)return;if(X.route==="sticky-balanced"){let G=X.stickyAssignments?.[m8(J)];if(!G)return;if(G.lastSeenAt<$-kH)return;return G.accountId}let Y=X.activeRouting?.[J];if(!Y||Y.route!==X.route)return;return Y.activeId}function XA(X){let{logger:J,activeAccount:$}=X;return{buildBody:(Y)=>r_(Y.bodyText),async send({target:Y,body:G,signal:Q}){let z=async(H)=>{Q.throwIfAborted();let U={...Y.meta.replayHeaders,authorization:`Bearer ${H}`,"content-type":"application/json"};if(Y.meta.chatgptAccountId)U["ChatGPT-Account-Id"]=Y.meta.chatgptAccountId;else delete U["ChatGPT-Account-Id"];let j;try{let q=JSON.parse(G);j={warmBodyKeys:Object.keys(q),stream:q.stream,max_output_tokens:q.max_output_tokens,store:q.store,has_stream_options:"stream_options"in q,has_max_tokens:"max_tokens"in q,model:q.model}}catch{}return J?.debug("cachekeep warm request",{...j,headerKeys:Object.keys(U),hasChatGptAccountId:"ChatGPT-Account-Id"in U}),X.fetchImpl(X.codexResponsesUrl,o7({method:"POST",headers:U,body:G,signal:Q}))};if(Y.accountId&&X.vault?.owns(Y.accountId)){let H=await X.vault.send(Y.accountId,z,{site:"cachekeep",signal:Q});if(!H)throw Error(`vault refused warm for ${Y.accountId}`);return H}if(X.vault&&await X.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let Z,W;if(Y.accountId&&Y.accountId!=="main"){let H=await X.refreshFallback(Y.accountId);if(typeof H==="string")Z=H;else Z=H.token,W=H.onAuthFailure}else Z=await X.getMainToken();if(X.vault&&await X.vault.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");let B=await z(Z);if(B.status===401)await W?.(B.status);return B},readUsage({response:Y,text:G}){let Q=Y.headers.get("content-type")??"",z=Q.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(G.slice(0,200));J?.debug("cachekeep warm response",{status:Y.status,contentType:Q,bodyLen:G.length,isSse:z});let Z=z?e_(G):t_(G),W=s9(Y.headers);return{...Z,quota_primary_pct:W.primary?.usedPercent??null,quota_secondary_pct:W.secondary?.usedPercent??null}},profile:o_,...$?{activeAccount:(Y,G)=>$(G.meta.routingSessionId)}:{}}}function hH(X){let{fetchImpl:J,getMainToken:$,refreshFallback:Y,vault:G,codexResponsesUrl:Q,activeAccount:z,logger:Z,...W}=X;return new _3({...W,logger:Z,adapter:XA({fetchImpl:J,getMainToken:$,refreshFallback:Y,vault:G,codexResponsesUrl:Q,activeAccount:z,logger:Z})})}import{readFileSync as JA,statSync as $A}from"node:fs";var YA=60000,GA=15000,fH=30000,c$=2000,l$=1e4;async function T3(X,J){let $,Y=await Promise.race([X.then(()=>!0,()=>!0),new Promise((G)=>{$=setTimeout(()=>G(!1),J),$.unref?.()})]);return clearTimeout($),Y}var QA=8,zA=1800000;function ZA(X){if(!Y6(X.quota))return;let J=f0(X.quota);return J.limits.some(($)=>$.kind==="reading")?J.checkedAt:void 0}function WA(X){if(!X)return;let J=H6(X);return J?V6(J):void 0}function gH(X){try{let J=$A(X);return`${J.ino}:${J.size}:${J.mtimeMs}`}catch{return"-"}}function BA(X){try{let J=JSON.parse(JA(X,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return;return j6(J).migratedAt}catch{return}}function HA(X){if(X.type!=="oauth")return!1;return X.candidate||X.torn===!0&&X.enabled}function r7(X){return X.identity?`identity:${X.identity}`:`row:${X.id}`}function A3(X){let J=X.credential;if(J?.type!=="oauth")return;return{access:J.access??"",expires:J.expires,refresh:J.refresh}}class d${deps;now;log;snapshot={active:!1,rows:[],key:void 0,readAt:0};inflightRead;store;refreshing=new Map;backoff=new Map;rotated=new Map;pending=new Map;writes=new Map;marks=new Map;lastPull=new Map;polled=new Set;pollOutcomes=new Map;disposed=!1;vaultRosterSettled;pollsAwaitVault=!1;constructor(X){this.deps=X,this.now=X.now??Date.now,this.log=X.log??Z0("pool"),this.vaultRosterSettled=X.vaultFirstRoster===void 0;let J=()=>{this.vaultRosterSettled=!0};X.vaultFirstRoster?.then(J,J)}async awaitVaultRoster(X){let J=this.deps.vaultFirstRoster;if(this.vaultRosterSettled||!J)return;await T3(J,X)}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}async current(){let X=this.filesKey();if(this.snapshot.key===X)return this.peek();let J=this.startRead(X),$=await e7(J,this.deps.readBudgetMs??t7,()=>this.snapshot);return{active:$.active,rows:$.rows}}async load(){await this.deps.vaultAuthority?.();let X=await this.startRead(this.filesKey());return{active:X.active,rows:X.rows}}filesKey(){let X=this.deps.paths();return`${X.configPath}|${gH(X.configPath)}|${gH(X.statePath)}`}storeFor(X){if(this.store?.configPath===X.configPath)return this.store.store;let J=G8({provider:"openai",configPath:X.configPath,statePath:X.statePath,quota:f8,now:this.now,pull:($)=>this.pull($),onPullFailure:($,Y)=>{this.pollOutcomes.set($,{id:$,ok:!1,error:Y.message}),this.log.warn("pool quota poll failed",{rowId:$,kind:Y.kind,error:Y.message})},logger:this.log,...this.deps.store,onStep:async($,Y)=>{if(await this.deps.store?.onStep?.($,Y),Y.operation!=="updateSettings"&&$.startsWith("before-")&&this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")throw Error("Local account writes are disabled while connected to the vault.")}});return this.store={configPath:X.configPath,store:J},J}startRead(X){if(this.inflightRead?.key===X)return this.inflightRead.promise;let J=this.now(),$=this.read(X,J),Y={key:X,promise:$};this.inflightRead=Y;let G=()=>{if(this.inflightRead===Y)this.inflightRead=void 0};return $.then(G,G),$}async read(X,J){let $=this.deps.paths(),Y={active:!1,rows:[],key:X,readAt:J};try{if(BA($.configPath)!==void 0){let z=await this.storeFor($).read();if(z.status==="ready")Y={active:!0,rows:z.rows,key:X,readAt:J};else this.log.warn("migrated install has no readable account pool",{status:z.status,...z.status==="error"?{reason:z.reason}:{}})}}catch(Q){return this.log.warn("account pool read failed",{error:Q instanceof Error?Q.message:String(Q)}),this.snapshot}let G=this.snapshot.active;if(J>=this.snapshot.readAt)this.snapshot={...Y,rows:this.withLocalState(Y.rows)};if(this.snapshot.active){if(!G)this.log.info("account pool serves requests");this.pollUnseenRows()}return this.snapshot}withLocalState(X){let J=this.now();return X.map(($)=>{let Y=$,G=this.rotated.get($.id),Q=G?.credential;if(G&&G.credentialEpoch!==$.credentialEpoch)this.rotated.delete($.id);else if(Q?.type==="oauth"&&$.credential?.type==="oauth"){let Z=$.credential.lastRefreshedAt??0,W=Q.lastRefreshedAt??0;if(Z>=W)this.rotated.delete($.id);else Y={...Y,credential:Q}}let z=(this.pending.get(r7($))??[]).filter((Z)=>J-Z.observation.checkedAt<=zA);for(let Z of z){if(Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)continue;Y={...Y,quota:this.merged(Y.quota,Z.observation)}}return Y})}merged(X,J){try{return z7(X,J)}catch{return X}}replaceRow(X,J){this.snapshot={...this.snapshot,rows:this.snapshot.rows.map(($)=>$.id===X?J($):$)}}vaultOwned(X){if(this.deps.vaultMode?.())return!0;return X.identity!==void 0&&(this.deps.vaultIdentities?.().has(X.identity)??!1)}pollUnseenRows(){if(this.disposed)return;let X=this.deps.vaultFirstRoster;if(!this.vaultRosterSettled&&X&&!this.deps.vaultMode?.()){if(this.pollsAwaitVault)return;this.pollsAwaitVault=!0,T3(X,this.deps.vaultFirstRosterBackgroundWaitMs??l$).then((J)=>{if(this.pollsAwaitVault=!1,J)this.pollUnseenRows();else this.log.info("first quota polls skipped: the vault has not read its accounts yet")});return}for(let J of this.snapshot.rows){if(!HA(J)||this.vaultOwned(J))continue;let $=`${J.id}\x00${J.credentialEpoch??0}\x00${J.identity??""}`;if(this.polled.has($))continue;this.polled.add($),this.requestReading(J.id,!0)}}requestReading(X,J=!1){if(this.disposed||this.deps.vaultMode?.())return;let $=this.now(),Y=this.lastPull.get(X);if(!J&&Y!==void 0&&$-Y<(this.deps.pullRetryMs??GA))return;this.lastPull.set(X,$),this.storeFor(this.deps.paths()).requestReading(X)}async pull(X){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")throw Error("local accounts are not polled while this host is connected to the vault");let J;try{if(J=await this.deps.pullQuota(X),!J)throw Error("the quota poll returned no reading")}catch(Y){throw this.pollOutcomes.set(X.id,{id:X.id,ok:!1,error:Y instanceof Error?Y.message:String(Y)}),Y}this.pollOutcomes.set(X.id,{id:X.id,ok:!0});let $=this.snapshot.rows.find((Y)=>Y.id===X.id);if($&&$.credentialEpoch===X.credentialEpoch&&$.identity===X.identity)this.applyObservation($,J);return J}applyObservation(X,J){let $=r7(X),Y=[...this.pending.get($)??[],{credentialEpoch:X.credentialEpoch,identity:X.identity,observation:J}].slice(-QA);this.pending.set($,Y),this.replaceRow(X.id,(G)=>({...G,quota:this.merged(G.quota,J),needsFirstReading:!1}))}recordSnapshot(X,J,$,Y){if(!this.snapshot.active||this.disposed||this.deps.vaultMode?.())return;let G=this.snapshot.rows.find((j)=>j.id===X);if(G?.type!=="oauth")return;let Q=WA($);if(!(Q&&G.identity?Q===G.identity:A3(G)?.access===$))return;let Z=C9(J,this.now(),Y);if(!Z)return;if(this.applyObservation(G,Z),G.credentialEpoch===void 0)return;let W={credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}},B=this.storeFor(this.deps.paths()),U=(this.writes.get(G.id)??Promise.resolve()).then(async()=>{if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;return B.recordQuota(G.id,W,Z)}).catch((j)=>{this.log.warn("pool quota not recorded",{rowId:G.id,error:j instanceof Error?j.message:String(j)})});this.writes.set(G.id,U),U.finally(()=>{if(this.writes.get(G.id)===U)this.writes.delete(G.id)})}markRateLimited(X,J){let $=this.snapshot.rows.find((Q)=>Q.id===X);if(!$)return;let Y=r7($),G=this.marks.get(Y);if(G!==void 0&&G>J)return;this.marks.set(Y,J)}rateLimitMarks(X){let J=new Map;for(let $ of X){let Y=this.marks.get(r7($));if(Y!==void 0)J.set($.id,Y)}return J}async prepareTokens(X,J,$={}){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;if(!this.deps.vaultMode?.())await this.awaitVaultRoster(this.deps.vaultFirstRosterWaitMs??c$);let Y=this.now(),G=cJ(J),Q=[];for(let z of X){if(!z.candidate||this.vaultOwned(z))continue;let Z=A3(z);if(!Z)continue;let W=(Z.expires??0)-Y;if(!(!Z.access||!Z.expires||W<=G)||this.refreshBackedOff(z,J,Y))continue;let H=this.refresh(z.id);if($.waitForAll||!Z.access||!Z.expires||W<=YA)Q.push(H)}await Promise.all(Q)}refreshBackedOff(X,J,$=this.now()){let Y=A3(X);if(!Y)return!1;let G=Q8(Y.refresh),Q=this.backoff.get(X.id);if(Q&&Q.tokenHash===G&&Q.nextRetryAt>$)return!0;let z=J?.accounts.find((Z)=>Z.id===X.id);return Boolean(z?.type==="oauth"&&z.corrupt!==!0&&t0(z.lastRefreshError,Y.refresh,$))}usableToken(X,J=this.now()){let $=this.snapshot.rows.find((G)=>G.id===X.id);if(!$?.enabled||!$.candidate||$.type!=="oauth"||$.identity!==X.identity||$.credentialEpoch!==X.credentialEpoch||this.vaultOwned($))return;let Y=A3($);if(!Y?.access.trim())return;if(typeof Y.expires!=="number"||Y.expires<=J)return;return Y.access}refresh(X){let J=this.refreshing.get(X);if(J)return J;let $=this.runRefresh(X).finally(()=>{if(this.refreshing.get(X)===$)this.refreshing.delete(X)});return this.refreshing.set(X,$),$}async runRefresh(X){if(this.deps.vaultAuthority&&await this.deps.vaultAuthority()!=="local")return;let J=this.deps.paths(),$=this.snapshot.rows.find((z)=>z.id===X),Y=$?A3($)?.refresh:void 0,G,Q=(z,Z)=>{return G=Z.credentialEpoch,this.deps.refreshProvider(z,Z)};try{let z=await sB({paths:J,store:this.storeFor(J),now:this.now,...this.deps.legacyLocks?{legacyLocks:this.deps.legacyLocks}:{}},X,Q);if(z.status==="rotated"){this.backoff.delete(X),this.rotated.set(X,{credential:z.credential,credentialEpoch:G}),this.replaceRow(X,(Z)=>Z.credentialEpoch!==G?Z:{...Z,credential:z.credential,...z.identity!==void 0&&Z.identity===void 0?{identity:z.identity}:{}});return}if(z.status==="identity-contradicted"){this.backoff.delete(X),this.replaceRow(X,(Z)=>({...Z,enabled:!1,candidate:!1})),this.log.warn("pool row disabled: its refresh returned a different account",{rowId:X});return}this.recordRefreshFailure(X,Y,Error(z.reason))}catch(z){this.recordRefreshFailure(X,Y,z)}}recordRefreshFailure(X,J,$){if(this.log.warn("pool row refresh failed",{rowId:X,error:$ instanceof Error?$.message:String($)}),!J)return;let Y=this.now(),G=Q8(J),Q=this.backoff.get(X);if(typeof $?.status==="number"||R5($)){let Z=m1({error:$,now:Y,refreshToken:J,...Q?{previous:{message:"",checkedAt:Y,nextRetryAt:Q.nextRetryAt,retryCount:Q.retryCount,tokenHash:Q.tokenHash}}:{}});this.backoff.set(X,{nextRetryAt:Z.nextRetryAt,tokenHash:G,retryCount:Z.retryCount})}else this.backoff.set(X,{nextRetryAt:Y+fH,tokenHash:G,retryCount:Q?.tokenHash===G?Q.retryCount:0})}refreshBackoffFor(X){let J=this.now(),$=new Map;for(let Y of X){if(this.usableToken(Y,J))continue;let G=this.backoff.get(Y.id);$.set(Y.id,G&&G.nextRetryAt>J?G.nextRetryAt:J+fH)}return $}async active(){return(await this.current()).active}poolStore(){return this.storeFor(this.deps.paths())}async refreshDueTokens(X){let J=await this.current();if(!J.active||this.disposed)return;await this.prepareTokens(J.rows,X,{waitForAll:!0})}async pollRows(X,J={}){let $=await this.load();if(!$.active||this.disposed)return[];let Y=this.now(),G=$.rows.filter((Q)=>{if(!Q.candidate||Q.type!=="oauth"||this.vaultOwned(Q))return!1;if(J.ids&&!J.ids.includes(Q.id))return!1;if(J.skipReadWithinMs===void 0)return!0;let z=ZA(Q);return z===void 0||Y-z>=J.skipReadWithinMs});if(G.length===0)return[];await this.prepareTokens(G,X,{waitForAll:!0});for(let Q of G)this.pollOutcomes.delete(Q.id),this.requestReading(Q.id,!0);return await this.poolStore().pullsSettled(),G.map((Q)=>this.pollOutcomes.get(Q.id)??{id:Q.id,ok:!1,error:"the quota poll did not run"})}async accessFor(X,J){let $=await this.current();if(!$.active)return;let Y=$.rows.find((z)=>z.id===X);if(!Y?.candidate)return;await this.prepareTokens([Y],J);let G=this.snapshot.rows.find((z)=>z.id===X)??Y;if(!G.candidate)return;let Q=this.usableToken(G);return Q?{row:G,token:Q}:void 0}async rowAccess(X,J){let $=await this.current();if(!$.active)return;let Y=$.rows.find((Q)=>Q.id===X);if(!Y)return{};let G=await this.accessFor(X,J);return{row:{id:Y.id,type:Y.type,enabled:Y.enabled,...Y.label!==void 0?{label:Y.label}:{},...Y.identity!==void 0?{identity:Y.identity}:{}},...G?{token:G.token}:{}}}dispose(){this.disposed=!0}async settled(){for(;;){let X=[...this.writes.values(),...this.refreshing.values()];if(await Promise.allSettled(X),await this.store?.store.pullsSettled(),this.writes.size===0&&this.refreshing.size===0)return}}}var mH=60000,i$=900000,VA={set(X,J){let $=setTimeout(X,J);return $.unref?.(),$},clear(X){clearTimeout(X)}};function UA(X){return X.status==="completed"||X.status==="already-migrated"||X.status==="nothing-to-import"||X.status==="ambiguous"}function uH(X){return X.status==="deferred"||X.status==="retry"||X.status==="error"}function pH(X){let J=X.log??Z0("pool-migration"),$=X.timers??VA,Y=X.random??Math.random,G=X.migrate??g7,Q=X.adopt??m7,z=X.fence??(()=>H4({currentVersion:X.version})),Z=!1,W=!1,B=!1,H=0,U,j=Promise.resolve(),q,K,L,F=!1;function O(){if(F)return;F=!0,J.warn(W4,{reason:"placeholder-without-main"})}let _=()=>({paths:X.paths(),slot:X.slot,log:J,...X.runDeps});function C(w){let J0=j.then(w).catch((G0)=>{J.warn("account pool background run failed",{error:G0 instanceof Error?G0.message:String(G0)})});return j=J0,J0}function N(w){if(W)return;if(U!==void 0)$.clear(U);U=$.set(()=>{U=void 0,C(i)},w)}function P(){let w=Math.min(mH*2**Math.min(H,10),i$);return H++,A(w)}let A=(w)=>Math.round(w*(1-0.2*Y()));async function T(){if(!await X.paused?.())return!1;return N(A(mH)),!0}async function b(){if(await T())return;let w;try{w=await G({..._(),fence:z})}catch(J0){J.warn("account pool migration failed; it will be tried again",{error:J0 instanceof Error?J0.message:String(J0)}),N(P());return}if(w.status==="refused"){if(w.reason==="placeholder-without-main")O();N(A(i$));return}if(UA(w)){if(B=!0,H=0,w.status==="completed")J.info("account pool migration completed",{rowId:w.rowId});await p();return}if(uH(w)){if(w.status!=="deferred")J.warn("account pool migration will be tried again",{outcome:w});N(P())}}async function p(){if(await T())return;let w;try{let J0=await z();if(!J0.open){let G0=JSON.stringify(J0.blockers);if(G0!==L)L=G0,J.info("host login adoption waits for older plugin versions",{blockers:J0.blockers});N(P());return}w=await Q(_())}catch(J0){J.warn("adopting the host login into the account pool failed",{error:J0 instanceof Error?J0.message:String(J0)}),N(P());return}if(w.status==="not-migrated")return;if(w.status==="slot-read-only")return;if(B=!0,w.status==="completed")J.info("host login adopted into the account pool",{rowId:w.rowId,operation:w.operation});if(uH(w)){J.warn("host login adoption will be tried again",{outcome:w}),N(P());return}if(H=0,B)N(A(i$))}async function i(){if(W)return;if(B)await p();else await b()}function X0(){if(q)return q;let w=C(async()=>{if(q=void 0,!W)if(B)await p();else await b()});return q=w,w}return{start(){if(Z||W)return;Z=!0,C(b)},requestAdoption:X0,noticePlaceholderWithoutMain:O,noticeRealSlot(w){if(!B||W||w===K)return;K=w,X0()},dispose(){if(W=!0,U!==void 0)$.clear(U);U=void 0},idle:async()=>{for(;;){let w=j;if(await w,w===j)return}},migrated:()=>B}}var p6="main",lH=5;function dH(X){if(X==="ordered")return"roster";return X==="fallback-first"?"fallback-first":"main-first"}function n$(X){return X.reason==="exhausted"||X.reason==="budget-spent"}function iH(X,J,$){if(X===void 0)return{reason:"no-credential"};if($.get(X)===!1)return{reason:"killswitch"};let Y=J.excluded.find((Q)=>Q.id===X);if(Y?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:Y.until};if(Y)return{reason:"no-credential"};let G=J.refused.find((Q)=>Q.id===X);if(G&&"resetAtMs"in G)return{reason:"quota-exhausted",resetAtMs:G.resetAtMs};if(G)return{reason:"quota-unknown"};return{reason:"no-credential"}}function cH(X,J,$){if(J.refused.find((G)=>!n$(G)&&$.get(G.id)!==!1))return{reason:"quota-unknown"};return iH(X[0],J,$)}function nH(X){let J=X.replayable!==!1,$=J?X.placement:"main-first",Y=iX({rows:X.rows,placement:$,formerMainId:p6,killswitch:X.killswitch,rateLimitMarks:X.rateLimitMarks,refreshBackoff:X.refreshBackoff,now:X.now,requestPull:X.requestPull}),G=I1(X.rows.map((Z)=>Z.id),$,p6),Q=new Set(Y.admission.refused.filter((Z)=>n$(Z)&&X.killswitch.get(Z.id)!==!1).map((Z)=>Z.id)),z=G.filter((Z)=>Q.has(Z));if(!J){let Z=G.includes(p6),W=Z?p6:Y.order[0]??z[0];if(W!==void 0&&Y.order.includes(W))return{kind:"send",order:[W],lastPath:!1};if(W!==void 0&&Q.has(W))return{kind:"send",order:[W],lastPath:!0};return{kind:"block",block:Z?iH(p6,Y.admission,X.killswitch):cH(G,Y.admission,X.killswitch)}}if(Y.order.length>0)return{kind:"send",order:Y.order,lastPath:!1};if(z.length>0)return{kind:"send",order:z,lastPath:!0};return{kind:"block",block:cH(G,Y.admission,X.killswitch)}}function s$(X){let J=m9({rows:X.rows,rateLimitMarks:X.rateLimitMarks,refreshBackoff:X.refreshBackoff,now:X.now,requestPull:X.requestPull}),$=new Map;for(let Y of X.rows)$.set(Y.id,f0(Y.quota));for(let Y of J.admitted)if(Y.projection)$.set(Y.id,Y.projection);return{projections:$,excluded:new Set(J.excluded.map((Y)=>Y.id))}}function sH(X,J,$){let Y=$.exclude,G=Y?X.rows.filter((z)=>!Y.has(z.id)):X.rows,Q=new Map;for(let z of G){let Z=J.resetCredits(z.id);if(Z!==void 0)Q.set(z.id,Z)}return eX({rows:G,now:X.now,rateLimitMarks:X.rateLimitMarks,refreshBackoff:X.refreshBackoff,requestPull:X.requestPull,killswitch:X.killswitch,requestBytes:J.requestBytes,...$.pendingBytes?{pendingBytes:$.pendingBytes}:{},rowReservePercent:(z)=>J.reservePercent(z.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:Q,...$.pin===void 0?{}:{pin:{accountId:$.pin}},...J.onEmptyWeightedSet?{onEmptyWeightedSet:J.onEmptyWeightedSet}:{}})}function aH(X,J,$,Y){let G=sH(X,J,{exclude:$,pendingBytes:Y});if(G.outcome!=="dispatch"||G.source==="pin")return;return{accountId:G.accountId,source:G.source,...G.quotaCheckedAt===void 0?{}:{quotaCheckedAt:G.quotaCheckedAt}}}function oH(X,J,$){let Y=X.killswitch.get($)===!1,G=sH(X,J,{pin:$});if(G.outcome==="dispatch"){if(G.pin.action==="assign")return{kind:"move",reason:Y?"killswitch":"exhausted"};return G.accountId===$?{kind:"serve"}:{kind:"detour"}}let Q=G.admission.refused.find((z)=>z.id===$);if(!Y&&Q&&n$(Q))return{kind:"last-path"};return{kind:"none"}}function rH(X,J,$,Y){let G=X.killswitch.get($);return tX({quota:J.projections.get($),now:X.now,...Y===void 0?{}:{status:Y},...G===void 0?{}:{killswitchPasses:G}})}var N1={"missing-main":"Request refused locally: this setup has no main login in its account store. Sign in with opencode auth login.","no-accounts":"Request refused locally: no eligible account is configured. Sign in with opencode auth login.",unusable:"Request refused locally: no usable account credential. Sign in with opencode auth login.",...eJ};function r$(X){return X!==void 0&&X in eJ}function KA(X,J,$,Y=new Set){return X.filter((G)=>{if(!G.enabled||!G.candidate||G.type!=="oauth")return!1;if(G.credential?.type!=="oauth")return!1;if(T0(G.credential))return!1;if(G.identity!==void 0&&Y.has(G.identity))return!1;if(G.id===p6)return!0;if($9(J,{accountId:G.identity}))return!1;return Z3(b8(G.quota),J,$)})}function eH(X){let J=X.vault;return[...(J?[]:KA(X.source.peek().rows,X.storage,X.now())).map((Y)=>({id:Y.id,kind:"oauth",...Y.identity!==void 0?{identity:Y.identity}:{},...Y.quota!==void 0?{quota:Y.quota}:{},row:Y})),...(J?.routes()??[]).filter((Y)=>Z3(b8(Y.quota),X.storage,X.now())).map((Y)=>({id:Y.id,kind:Y.kind,...Y.identity!==void 0?{identity:Y.identity}:{},...Y.quota!==void 0?{quota:Y.quota}:{}}))]}function jA(X){return X.flatMap((J)=>J.row?[J.row]:[])}function a$(X,J){let $=X.now(),Y=new Map;if(Y9(X.storage))for(let W of J)Y.set(W.id,Q1(b8(W.quota),X.storage,W.id===p6?void 0:W.id,$));let G=J.map((W)=>({id:W.id,kind:W.kind,...Y6(W.quota)?{quota:W.quota}:{}})),Q=jA(J),z=new Set(J.filter((W)=>!W.row).map((W)=>W.id)),Z=X.source.rateLimitMarks(Q);for(let[W,B]of X.vault?.rateLimitMarks?.()??[])if(z.has(W)&&B>$)Z.set(W,B);return{rows:G,now:$,rateLimitMarks:Z,refreshBackoff:X.source.refreshBackoffFor(Q),killswitch:Y,requestPull:(W)=>z.has(W)?X.vault?.requestReading(W):X.source.requestReading(W)}}function tH(X){let J=X.find(($)=>$.id===p6);return{main:J?b8(J.quota):void 0,fallbacks:X.filter(($)=>$.id!==p6).map(($)=>{let Y=b8($.quota);return{accountId:$.id,...Y?{quota:Y}:{}}})}}async function o$(X,J){if(J.row){let $=X.source.usableToken(J.row);if(!$)return;let Y=await X.send(J,$);return X.recordQuota(Y,J,$),Y}return X.vault?.send(J.id,async($,Y)=>{let G=await X.send(J,$,Y);return X.recordQuota(G,J,$,Y),G})}async function XV(X){if(X.vault)await X.vault.awaitRoster();else await X.source.current(),await X.source.prepareTokens(X.source.peek().rows,X.storage);let J=eH(X);if(X.mode==="sticky-balanced"&&X.sessionId&&X.replayable&&X.body!==void 0){let $=await NA(X,J,X.sessionId,X.body);if($)return $}return qA(X,J)}async function qA(X,J){let $=dH(X.mode),Y=nH({...a$(X,J),placement:$,replayable:X.replayable});if(Y.kind==="block")return X.log.debug("pool admission blocked the request",{pid:process.pid,reason:Y.block.reason}),{response:X.blocked(Y.block,tH(J),X.vault?J.length===0?X.vault.noRouteCause():void 0:J.length===0?"no-accounts":"unusable"),servedId:p6};if(Y.lastPath)X.log.debug("pool admission: every account is exhausted; probing anyway",{pid:process.pid,order:Y.order});let G=new Map(J.map((H)=>[H.id,H])),Q=pJ(X.storage),z=[],Z=new Set,W,B=!1;for(;;){let H=nX(Y.order.filter((q)=>!Z.has(q)),z,Q),U=H===void 0?void 0:G.get(H);if(!U)break;let j;try{j=await o$(X,U)}catch(q){if(X.isAbort(q)||!W||X.mode==="fallback-first")throw q;return X.log.debug("pool fallback attempt threw; stopping",{pid:process.pid,accountId:U.id}),W}if(!j){if(!U.row)B=!0;Z.add(U.id);continue}W?.response.body?.cancel().catch(()=>{}),W={response:j,servedId:U.id},z.push({id:U.id,status:j.status})}if(W)return W;return{response:X.blocked({reason:"no-credential"},tH(J),B?"vault-refused":X.vault?"vault-empty":"unusable"),servedId:p6}}async function NA(X,J,$,Y){let G=Buffer.byteLength(Y,"utf8"),Q=new Map(J.map((O)=>[O.id,O])),z=a$(X,J),Z=s$(z),W={requestBytes:G,reservePercent:(O)=>n6(X.storage,O===p6?void 0:O),resetCredits:X.resetCredits,onEmptyWeightedSet:()=>{X.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},B=(O,_)=>(C,N)=>{let P=new Set(C);return X.placePin({sessionId:$,requestBytes:G,now:O.now,validPinnedAccountIds:O.rows.map((A)=>A.id).filter((A)=>!_.excluded.has(A)),excludeAccountIds:C,quotaCheckedAtByAccount:Object.fromEntries(O.rows.map((A)=>[A.id,_.projections.get(A.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(J.map((A)=>[A.id,A.identity])),select:(A)=>aH(O,W,P,A),persist:N})},H=B(z,Z),U=H([],!0);if(!U)return;let j=U.accountId,q=(O)=>{let _=H([j],!0);if(!_)return!1;return X.log.debug("sticky routing: migrated session pin",{pid:process.pid,fromAccountId:j,toAccountId:_.accountId,reason:O}),j=_.accountId,!0},K=oH(z,W,j);if(K.kind==="none")return;if(K.kind==="move"){if(!q(K.reason)&&K.reason==="killswitch")return}else if(K.kind==="detour"){let O=H([j],!1);if(!O)return;X.log.debug("sticky routing: pinned account awaits a quota reading",{pid:process.pid,pinnedAccountId:j,servedAccountId:O.accountId}),j=O.accountId}let L=Q.get(j);if(!L)return;let F=await o$(X,L);if(!F)return;if(F.status===401||F.status===403||F.status===429){let O=eH(X);z=a$(X,O),Z=s$(z),H=B(z,Z);let _=rH(z,Z,j,F.status);if(_.action==="migrate"){let C=j;if(q(_.reason)&&j!==C){let N=O.find((A)=>A.id===j),P=N?await o$(X,N):void 0;if(N&&P){let A=F;F=P,A.body?.cancel().catch(()=>{}),L=N}else j=C}}}return{response:F,servedId:L.id}}function R3(X){return typeof X==="number"&&Number.isFinite(X)}function LA(X){if(!Y6(X))return;let J=X.budget;if(J?.kind!=="reading")return;let{limit:$,used:Y,remaining:G,usedPercent:Q,remainingPercent:z}=J;if(!R3($)||!R3(Y)||!R3(G)||!R3(Q)||!R3(z))return;return{limit:$,used:Y,remaining:G,usedPercent:Q,remainingPercent:z,reached:J.reached,...J.resetsAt!==void 0?{resetsAt:J.resetsAt}:{},...J.unit!==void 0?{unit:J.unit}:{}}}function t$(X,J){let $=b8(X),Y=LA(X);if(!$&&!Y)return null;let G=Y6(X)?f0(X).checkedAt:void 0;return{...G!==void 0?{checkedAt:G}:{},...$?.primary?{primary:$.primary}:{},...$?.secondary?{secondary:$.secondary}:{},...Y?{spendControl:Y}:{},...J!==void 0?{resetCreditsAvailable:J}:{}}}function JV(X,J,$,Y){return{main:{quota:null,killed:!1},fallbacks:[],vaultAccounts:X.map((G)=>({id:G.routeId,label:G.email||G.label||G.routeId,...G.accountIdentity!==void 0?{accountId:G.accountIdentity}:{},quota:t$(G.quota),killed:!1,enabled:J.has(G.routeId)})),route:$?.routing?.mode??"main-first",lastUpdated:Y}}function $V(X,J,$,Y=()=>{return}){let G=X.find((z)=>z.id===V8),Q=G?Y(G.id):void 0;return{main:{quota:G?t$(G.quota,Q):null,...G?.identity!==void 0?{mainAccountId:G.identity}:{},killed:!1,...Q!==void 0?{resetCredits:Q}:{}},fallbacks:X.filter((z)=>z.id!==V8&&z.enabled).map((z)=>{let Z=Y(z.id);return{id:z.id,label:z.label,...z.identity!==void 0?{accountId:z.identity}:{},quota:t$(z.quota,Z),killed:!1,enabled:!0,...Z!==void 0?{resetCredits:Z}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:$,accountPool:!0}}import{randomUUID as DA}from"node:crypto";import{chmod as FA,mkdir as PA,rename as OA,rm as GV,writeFile as MA}from"node:fs/promises";import{homedir as _A}from"node:os";import{join as e$}from"node:path";function QV(){let X=process.env.XDG_STATE_HOME||e$(_A(),".local","state");return e$(X,"cortexkit","openai-auth","processes")}function zV(X=process.pid,J=QV()){return e$(J,`${X}.json`)}var XX=0,YV;async function AA(X,J){await PA(X,{recursive:!0,mode:448}),await FA(X,448);let $=zV(J.pid,X),Y=`${$}.${DA()}.tmp`;try{await MA(Y,`${JSON.stringify(J)}
163
- `,{mode:384}),await OA(Y,$)}catch(G){throw await GV(Y,{force:!0}).catch(()=>{}),G}return $}async function ZV(X){let J=X.pid??process.pid,$=X.dir??QV();YV??=(X.now??Date.now)(),XX++;let Y;try{Y=await AA($,{pid:J,version:X.version,startedAt:YV})}catch(Q){X.logger.warn("process heartbeat not written",{dir:$,error:Q instanceof Error?Q.message:String(Q)})}let G=!1;return{path:Y,async release(){if(G)return;if(G=!0,XX=Math.max(0,XX-1),XX>0)return;await GV(zV(J,$),{force:!0}).catch((Q)=>{X.logger.warn("process heartbeat not removed",{dir:$,error:Q instanceof Error?Q.message:String(Q)})})}}}import{resolve as JX}from"node:path";var TA=60000,RA=240000,WV=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),BV=globalThis,C3=BV[WV]??new Map;BV[WV]=C3;function HV(X,J){let $=Boolean(X.connectScoped||X.connectEnrollment),Y=JX(X.stateDir),G=JX((X.connectionFile??r9)()),Q=JSON.stringify([X.host,Y,G,JX(J.configPath),JX(J.statePath)]),z={reservedRouteIds:X.reservedRouteIds??(()=>[])},Z=$?void 0:C3.get(Q);if(!Z){let H=new Set;if(Z={vault:new X$({...X,stateDir:Y,connectionFile:()=>G,...!$?{projectRoot:Y}:{},reservedRouteIds:()=>new Set([...H].flatMap((j)=>[...j.reservedRouteIds()]))}),holders:H,firstRoster:Promise.withResolvers(),started:!1},!$)C3.set(Q,Z)}Z.holders.add(z);let W=Z,B=!1;return{vault:W.vault,firstRoster:W.firstRoster.promise,start(){if(B||W.started)return;W.started=!0;let H=async()=>{if(W.holders.size&&await W.vault.authority()!=="local")await W.vault.pollStale(RA)};W.vault.start(),W.vault.firstRoster().finally(()=>{W.firstRoster.resolve(),H()}),W.quotaPoll=setInterval(H,TA),W.quotaPoll.unref?.()},release(){if(B)return;if(B=!0,W.holders.delete(z),W.holders.size!==0)return;if(W.quotaPoll)clearInterval(W.quotaPoll);if(W.vault.close(),W.firstRoster.resolve(),!$&&C3.get(Q)===W)C3.delete(Q)}}}var qV=900000,CA=0.016666666666666666,VV=0.000001;function JY(X,J){for(let $ of[X?.primary?.checkedAt,X?.checkedAt,J])if(typeof $==="number"&&Number.isFinite($))return $;return}function $Y(X){if(X.status===401||X.status===403)return{action:"migrate",reason:"permanent"};if(!X.quota)return{action:"retain",reason:"unknown"};let J=JY(X.quota,X.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||X.now-J>qV)return{action:"retain",reason:"stale"};if(X.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let $=XY(X.quota).sort((G,Q)=>{let z=G.windowMs,Z=Q.windowMs,W=typeof z==="number"&&Number.isFinite(z),B=typeof Z==="number"&&Number.isFinite(Z);if(W!==B)return W?-1:1;if(W&&B)return Z-z;return 0});for(let{key:G,window:Q}of $)if(Number.isFinite(Q.remainingPercent)&&Q.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:G,...typeof Q.resetsAt==="string"?{resetsAt:Q.resetsAt}:{}};let Y=jV(X.quota,X.now);if(Y)return{action:"migrate",reason:"exhausted",resetsAt:Y.resetsAt};if(X.status===void 0||X.status===0||!Number.isFinite(X.status)||X.status>=500&&X.status<=599||X.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function UV(X,J,$){let Y=Math.max(0,X.remainingPercent-J);if(Y<=0)return 0;if(!X.resetsAt)return Y;let G=Date.parse(X.resetsAt);if(!Number.isFinite(G)||G<=$)return Y;let Q=Math.max((G-$)/3600000,CA);return Y/Q}function KV(X,J){if(X<J)return-1;if(X>J)return 1;return 0}function EA(X,J){if(!X.quota)return;let $=JY(X.quota,X.quotaCheckedAt);if($===void 0||J-$>qV)return;let Y=XY(X.quota).map(({key:z,window:Z})=>{return UV(Z,X.reservePercent[z]??0,J)}),G=X.quota.spendControl;if(G&&Number.isFinite(G.remainingPercent))Y.push(UV(G,0,J));let Q=Y.length>0?Math.min(...Y):0;return Q>0?{candidate:X,quotaCheckedAt:$,weight:Q}:void 0}function NV(X){let J=X.candidates.filter((G)=>G.killswitchPasses!==!1);if(X.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(J.length===0)return;let $=J.map((G)=>EA(G,X.now)).filter((G)=>G!==void 0);if($.length>0){$.sort((Q,z)=>{let Z=((X.pendingBytes.get(Q.candidate.accountId)??0)+X.requestBytes)/Math.max(Q.weight,VV),W=((X.pendingBytes.get(z.candidate.accountId)??0)+X.requestBytes)/Math.max(z.weight,VV);return Z-W||Q.candidate.configuredOrder-z.candidate.configuredOrder||KV(Q.candidate.accountId,z.candidate.accountId)});let G=$[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}X.onEmptyWeightedSet?.();let Y=[...J].sort((G,Q)=>{let z=(G.resetCreditsApplicable??0)>0?1:0;return((Q.resetCreditsApplicable??0)>0?1:0)-z||G.configuredOrder-Q.configuredOrder||KV(G.accountId,Q.accountId)})[0];if(!Y)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Y.accountId,quotaCheckedAt:JY(Y.quota,Y.quotaCheckedAt),source:"mode-fallback"}}import{createHash as sA}from"node:crypto";import{createHash as SA,randomBytes as IA}from"node:crypto";import{chmod as bA,lstat as LV,mkdir as kA,open as xA,readdir as MV,readFile as DV,rename as wA,unlink as zY,writeFile as vA}from"node:fs/promises";import{join as $X,resolve as YY}from"node:path";var yA=100,GY="session-unknown",hA=300000,fA=60000,gA=600000,mA=/\.(body|meta|request|response)\.json$/,uA=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,pA=/\.[a-f0-9]{24}\.partial$/;function _V(X){let J=X.replace(mA,"");if(J===X||!uA.test(J))return;return J}function cA(X){let J=X.replace(pA,"");return J!==X&&_V(J)!==void 0}async function FV(X){let{dir:J,maxBytes:$}=X,Y=X.now??Date.now(),G=X.minAgeMs??fA,Q=X.partialStaleMs??gA,z={removed:0,freedBytes:0};if(!($>0))return z;try{if((await LV(J)).isSymbolicLink())return z;let Z=new Set((X.protectedPaths??[]).map((F)=>YY(F))),W=await MV(J,{withFileTypes:!0}),B=[];await Promise.all(W.map(async(F)=>{if(!F.isFile())return;let O=cA(F.name),_=O?void 0:_V(F.name);if(!O&&_===void 0)return;let C=$X(J,F.name);try{let N=await LV(C);if(!N.isFile())return;B.push({path:C,size:N.size,mtimeMs:N.mtimeMs,group:_})}catch{}}));let H=B.reduce((F,O)=>F+O.size,0),U=0,j=0,q=async(F)=>{try{await zY(F.path),H-=F.size,j+=F.size,U+=1}catch{}};for(let F of B){if(F.group!==void 0)continue;if(Z.has(YY(F.path)))continue;if(Y-F.mtimeMs<Q)continue;await q(F)}let K=new Map;for(let F of B){if(F.group===void 0)continue;let O=K.get(F.group)??{files:[],newest:0};O.files.push(F),O.newest=Math.max(O.newest,F.mtimeMs),K.set(F.group,O)}let L=[...K.entries()].sort(([F,O],[_,C])=>O.newest-C.newest||F.localeCompare(_));for(let[,F]of L){if(H<=$)break;if(Y-F.newest<G)continue;if(F.files.some((O)=>Z.has(YY(O.path))))continue;for(let O of F.files)await q(O)}if(U>0)X.logger?.debug("removed old dump files",{removed:U,freedBytes:j});return{removed:U,freedBytes:j}}catch{return z}}async function lA(X,J,$){for(let Y=0;;Y+=1){let G=`${X}.${$?$():IA(12).toString("hex")}.partial`,Q=!1,z;try{z=await xA(G,"wx",384),Q=!0,await z.writeFile(J,"utf8"),await z.chmod(384),await z.close(),z=void 0,await wA(G,X);return}catch(Z){if(await z?.close().catch(()=>{}),Q)await zY(G).catch(()=>{});if(Z.code==="EEXIST"&&Y===0)continue;throw Z}}}function QY(X){return X.length<=16?X:`${X.slice(0,12)}…`}function E3(X,J){let $=X.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!$)return J;return $.slice(0,80)}function PV(X){return SA("sha256").update(X).digest("hex")}function dA(X){return X.toLowerCase().replace(/[-_]/g,"")}function OV(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function iA(X,J){if(X===void 0)return null;if(X===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:X.length,currentBytes:J.length};let $=0;while($<X.length&&$<J.length&&X[$]===J[$])$++;let Y=X.length-1,G=J.length-1;while(Y>=$&&G>=$&&X[Y]===J[G])Y--,G--;return{changed:!0,firstByte:$,lastPreviousByte:Y,lastCurrentByte:G,changedPreviousBytes:Y-$+1,changedCurrentBytes:G-$+1,previousBytes:X.length,currentBytes:J.length}}var nA=0;function AV(X){let J=X.enabled===!0,$=X.pid??process.pid,Y=X.now??Date.now,G=X.logger,Q=new Set((X.secretKeys??[]).map(dA)),z=M2({extraSecretKeys:(T)=>Q.has(T),extraValuePatterns:[...X.secretPatterns??[]]}),Z=new Set(X.schemaKeys??["tools"]),W=new Map,B=()=>typeof X.dir==="function"?X.dir():X.dir;function H(T){let b=z.redact({[T]:null})[T];return b===null?void 0:b}function U(T){if(Array.isArray(T))return T.map(U);if(OV(T)){let b={};for(let[p,i]of Object.entries(T)){let X0=H(p);if(Z.has(p))b[p]=z.redactStrings(i);else if(X0!==void 0)b[p]=X0;else b[p]=U(i)}return b}return z.redactStrings(T)}function j(T){let b;try{b=JSON.parse(T)}catch{return{text:z.redactStrings(T),parsed:void 0}}let p=U(b),i=JSON.stringify(p);return{text:JSON.stringify(b)===i?T:i,parsed:OV(p)?p:void 0}}async function q(T,b,p,i){let X0=`-${E3(b,GY)}-${E3(p,"channel")}`,w;try{w=await MV(T)}catch{return}let J0=w.filter((G0)=>G0.endsWith(".meta.json")&&G0.includes(X0)).sort().reverse();for(let G0 of J0)try{if(JSON.parse(await DV($X(T,G0),"utf8"))?.baselineKey!==i)continue;return await DV($X(T,G0.replace(/\.meta\.json$/,".body.json")),"utf8")}catch{}return}function K(T,b){if(!W.has(T))while(W.size>=yA){let p=W.keys().next().value;if(p===void 0)break;W.delete(p)}W.set(T,b)}async function L(T){if(!J)return;let b=++nA,p=T.session?.trim()||GY,i=B(),X0=new Date(Y()).toISOString(),w=[X0.replace(/[:.]/g,"-"),String($),String(b).padStart(6,"0"),E3(p,GY),E3(T.channel,"channel"),...T.phase?[E3(T.phase,"phase")]:[]].join("-"),J0=$X(i,w),G0={body:`${J0}.body.json`,metadata:`${J0}.meta.json`,request:`${J0}.request.json`},L0=PV(`${T.channel}\x00${p}`);try{await kA(i,{recursive:!0,mode:448}),await bA(i,448);let m=W.get(L0),c0=m===void 0?void 0:"memory";if(m===void 0){if(m=await q(i,p,T.channel,L0),m!==void 0)c0="disk"}let m0=j(T.bodyText),r={id:w,createdAt:X0,pid:$,session:QY(p),channel:T.channel,...T.phase?{phase:T.phase}:{},accountId:T.accountId,status:T.status,error:T.error===void 0?void 0:z.redactStrings(T.error),baselineKey:L0,bodyBytes:Buffer.byteLength(T.bodyText,"utf8"),bodyHash:PV(T.bodyText),diff:iA(m,m0.text),baselineSource:c0,body:m0.parsed?{parseable:!0,...X.summarize?.(m0.parsed)}:{parseable:!1},...T.meta?{extra:U(T.meta)}:{},files:G0},a=U({url:T.url,method:T.method,accountId:T.accountId,headers:T.headers===void 0?void 0:Object.fromEntries(new Headers(T.headers).entries())}),u0=(e,c)=>vA(e,c,{encoding:"utf8",mode:384,flag:"wx"}),t=[[G0.body,m0.text],[G0.metadata,`${JSON.stringify(r,null,2)}
164
- `],[G0.request,`${JSON.stringify(a,null,2)}
165
- `]],h=await Promise.allSettled(t.map(([e,c])=>u0(e,c))),o=h.find((e)=>e.status==="rejected");if(o){if(X.cleanupFailedDumps)await F(t,h);throw o.reason}return K(L0,m0.text),G?.debug("dumped request",{id:w,session:QY(p),body:G0.body}),P(i,Object.values(G0)),{id:w,files:G0,responseFile:`${J0}.response.json`}}catch(m){G?.warn("request dump failed",{session:QY(p),error:m instanceof Error?m.message:String(m)});return}}async function F(T,b){await Promise.all(T.map(async([p],i)=>{let X0=b[i];if(X0?.status==="rejected"&&X0.reason?.code==="EEXIST")return;await zY(p).catch(()=>{})}))}let O=X.maxBytes??0,_=X.sweepIntervalMs??hA,C=0;function N(T,b){return{dir:T,maxBytes:O,protectedPaths:b,now:Y(),minAgeMs:X.sweepMinAgeMs,partialStaleMs:X.partialStaleMs,logger:G}}function P(T,b){if(!(O>0))return;let p=Y();if(p-C<_)return;C=p,FV(N(T,b))}async function A(T,b){if(!T)return;let p=U({status:b.status,requestId:b.requestId,usage:b.usage,...b.fields,complete:b.complete??!0});try{return await lA(T.responseFile,`${JSON.stringify(p,null,2)}
166
- `,X.stageName),T.responseFile}catch(i){G?.warn("response dump failed",{id:T.id,error:i instanceof Error?i.message:String(i)});return}}return{isEnabled:()=>J,setEnabled:(T)=>{J=T},dump:L,dumpResponse:A,sweep:(T)=>FV(N(B(),T))}}var RV=Z0("dump"),I9="x-cortexkit-openai-auth-dump-session",aA=["chatgpt-account-id","email","org_name","organization_name"],oA=["tools"];function ZY(X){return sA("sha256").update(JSON.stringify(X)).digest("hex")}function rA(X){return X!=null&&typeof X==="object"&&"type"in X&&typeof X.type==="string"?X.type:"unknown"}function tA(X){let J=Array.isArray(X.input)?X.input:[],$=Array.isArray(X.tools)?X.tools:[],Y=X.client_metadata!=null&&typeof X.client_metadata==="object"&&!Array.isArray(X.client_metadata)?X.client_metadata:void 0;return{model:typeof X.model==="string"?X.model:void 0,stream:X.stream,generate:X.generate,store:X.store,previousResponseID:typeof X.previous_response_id==="string"?X.previous_response_id:void 0,promptCacheKey:typeof X.prompt_cache_key==="string"?X.prompt_cache_key:void 0,reasoning:X.reasoning,inputCount:J.length,inputHash:ZY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:ZY(J[0]),toolsCount:$.length,toolTypes:$.map(rA),toolsHash:ZY($),clientMetadataKeys:Y?Object.keys(Y).sort():[]}}function eA(){return AV({dir:()=>u6().dumpDir,logger:RV,secretKeys:aA,schemaKeys:oA,summarize:tA})}var TV=eA();async function U4(X){let J=u6().dump===!0;if(TV.setEnabled(J),!J)return;let $=typeof X.bodyText==="function"?X.bodyText():X.bodyText;await TV.dump({session:X.sessionID,channel:X.transport,phase:X.phase,bodyText:$,accountId:X.accountId,url:X.url,method:X.method,headers:X.headers,status:X.status,error:X.error})}async function L1(X){if(!u6().dump)return;RV.debug("diagnostic",X)}import{readFile as XT}from"node:fs/promises";import{homedir as JT}from"node:os";import{join as CV}from"node:path";var $T="https://models.dev/api.json",YT="OPENCODE_OPENAI_AUTH_MODELS_CACHE",GT="OPENCODE_MODELS_PATH",QT="OPENCODE_DISABLE_MODELS_FETCH",zT=1e4,ZT=300000;function b9(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)?X:null}function EV(X){if(X===void 0)return 0;return typeof X==="number"&&Number.isFinite(X)&&X>=0?X:null}function WY(X){let{input:J,output:$}=X;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;if(typeof $!=="number"||!Number.isFinite($)||$<0)return null;let Y=EV(X.cache_read),G=EV(X.cache_write);if(Y===null||G===null)return null;return{input:J,output:$,cache:{read:Y,write:G}}}function WT(X){let J=b9(X);if(!J)return null;let $=WY(J);if(!$)return null;let Y=$;if(Array.isArray(J.tiers)){let z=[];for(let Z of J.tiers){let W=b9(Z);if(!W)continue;let B=b9(W.tier),H=B?.size;if(B?.type!=="context")continue;if(typeof H!=="number"||!Number.isFinite(H)||H<=0)continue;let U=WY(W);if(!U)continue;z.push({...U,tier:{type:"context",size:H}})}if(z.length>0)Y.tiers=z}let G=b9(J.context_over_200k),Q=G?WY(G):null;if(Q)Y.experimentalOver200K=Q;return Y}function SV(X){let J=b9(X),$=b9(J?.openai),Y=b9($?.models);if(!Y)return null;let G={};for(let[Q,z]of Object.entries(Y)){let Z=b9(z),W=WT(Z?.cost);if(W)G[Q]=W}return Object.keys(G).length>0?G:null}function BT(){let X=process.env[YT]?.trim();if(X)return X;let J=process.env[GT]?.trim();if(J)return J;let $=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||CV(JT(),".cache");return CV($,"opencode","models.json")}function HT(){let X=process.env[QT]?.toLowerCase();return X==="true"||X==="1"}async function VT(){try{let X=SV(JSON.parse(await XT(BT(),"utf8")));if(X)return X}catch{}if(HT())return null;try{let X=await fetch($T,{signal:AbortSignal.timeout(zT)});if(!X.ok)return null;return SV(await X.json())}catch{return null}}var K4;function IV(){let X=Date.now();if(K4&&K4.expiresAt>X)return K4.promise;let J={expiresAt:X+ZT,promise:VT()};return K4=J,J.promise.then(($)=>{if($===null&&K4===J)K4=void 0}),J.promise}function j4(X){return typeof X==="object"&&X!==null}function UT(X){if(Array.isArray(X))return X;if(j4(X)&&Array.isArray(X.data))return X.data;return[]}function KT(X){if(!j4(X)||!j4(X.info))return;return typeof X.info.role==="string"?X.info.role:void 0}function bV(X){if(!j4(X)||!j4(X.info))return null;let J=X.info,$=j4(J.model)?J.model:void 0,Y=typeof J.agent==="string"?J.agent:void 0,G=typeof $?.providerID==="string"?$.providerID:typeof J.providerID==="string"?J.providerID:void 0,Q=typeof $?.modelID==="string"?$.modelID:typeof J.modelID==="string"?J.modelID:void 0,z=typeof $?.variant==="string"?$.variant:typeof J.variant==="string"?J.variant:void 0;if(!Y&&(!G||!Q)&&!z)return null;let Z={};if(Y)Z.agent=Y;if(G&&Q)Z.model={providerID:G,modelID:Q};if(z)Z.variant=z;return Z}function kV(X,J){return{agent:X.agent??J.agent,model:X.model??J.model,variant:X.variant??J.variant}}function xV(X){return Boolean(X.agent&&X.model&&X.variant)}async function wV(X,J){if(!X||!J)return null;let $=X;if(typeof $.session?.messages!=="function")return null;let Y=[];try{Y=UT(await Promise.resolve($.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Y.length===0)return null;let G={};for(let Q=Y.length-1;Q>=0;Q--){if(KT(Y[Q])!=="assistant")continue;let z=bV(Y[Q]);if(!z)continue;if(G=kV(G,z),xV(G))return G}for(let Q=Y.length-1;Q>=0;Q--){let z=bV(Y[Q]);if(!z)continue;if(G=kV(G,z),xV(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var jT=Z0("rpc"),yV="__openaiAuthRpcServers";function hV(X){return vV({...X,isManagedDir:l7,log:jT,drain:(J,$)=>X.drain(J,$),apply:async(J)=>await X.apply(J)})}function q4(X){return JSON.stringify(BY(X))??"undefined"}function BY(X){if(Array.isArray(X))return X.map(BY);if(!s(X))return X;return Object.fromEntries(Object.keys(X).sort().map((J)=>[J,BY(X[J])]))}var qT=512,NT=2097152;function HY(X,J){if(typeof X==="function"||typeof J==="function")return!1;if(J!==null&&typeof J==="object"&&Object.hasOwn(J,"toJSON")&&typeof J.toJSON==="function")return!1;if(X===J)return!0;if(Array.isArray(X))return Array.isArray(J)&&X.length===J.length&&X.every((Q,z)=>HY(Q,J[z]));if(X===null||J===null||typeof X!=="object"||typeof J!=="object"||Array.isArray(J))return!1;let $=X,Y=J,G=Object.keys($);return G.length===Object.keys(Y).length&&G.every((Q)=>Object.prototype.propertyIsEnumerable.call(Y,Q)&&HY($[Q],Y[Q]))}function D1(X,J){let $=[],Y=[],G=0;for(let Q=0;Q<X.length;Q++){let z=J?.texts[Q],Z=z!==void 0&&HY(J?.snapshots[Q],X[Q]),W=Z?z:q4(X[Q]);$.push(W),Y.push(Z?J?.snapshots[Q]:W==="undefined"?void 0:JSON.parse(W)),G+=W.length}return{texts:$,snapshots:Y,retainable:X.length<=qT&&G<=NT}}function S3(X){return X.retainable?X:void 0}function I3(X,J){if(X.texts.length>J.texts.length)return;for(let $=0;$<X.texts.length;$++)if(X.texts[$]!==J.texts[$])return;return X.texts.length}function F1(){let X=crypto.getRandomValues(new Uint8Array(16)),J=Date.now();X[0]=J/1099511627776&255,X[1]=J/4294967296&255,X[2]=J/16777216&255,X[3]=J/65536&255,X[4]=J/256&255,X[5]=J&255,X[6]=(X[6]??0)&15|112,X[8]=(X[8]??0)&63|128;let $=Array.from(X,(Y)=>Y.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}var U9={};KY(U9,{withoutInternalHeaders:()=>bN,sanitizeHttpFallbackBody:()=>m$,orderCodexBody:()=>n3,hasWebSocketResponsesLiteMetadata:()=>g$,createWebSocketFetch:()=>eS,applyTurnId:()=>TN,advanceTurn:()=>WG,TITLE_HEADER:()=>ZG,QUOTA_ACCOUNT_HEADER:()=>CX,OpenAIWebSocketPool:()=>U9,CODEX_BODY_KEY_ORDER:()=>_N});import{createHash as sS}from"node:crypto";var LT=Symbol.for("vercel.ai.error"),Z9=class X extends Error{constructor({name:J,message:$,cause:Y}){super($);this[LT]=!0,this.name=J,this.cause=Y}static isInstance(J){return X.hasMarker(J,"vercel.ai.error")}static hasMarker(J,$){let Y=Symbol.for($);return J!=null&&typeof J==="object"&&Y in J&&typeof J[Y]==="boolean"&&J[Y]===!0}},fV="AI_APICallError",gV=`vercel.ai.error.${fV}`,DT=Symbol.for(gV),P1=class extends Z9{constructor({message:X,url:J,requestBodyValues:$,statusCode:Y,responseHeaders:G,responseBody:Q,cause:z,isRetryable:Z=Y!=null&&(Y===408||Y===409||Y===429||Y>=500),data:W}){super({name:fV,message:X,cause:z});this[DT]=!0,this.url=J,this.requestBodyValues=$,this.statusCode=Y,this.responseHeaders=G,this.responseBody=Q,this.isRetryable=Z,this.data=W}static isInstance(X){return Z9.hasMarker(X,gV)}},FT="AI_EmptyResponseBodyError",au=`vercel.ai.error.${FT}`;var PT="AI_EvaluationUnsupportedQuestionTypeError",ou=`vercel.ai.error.${PT}`;var mV="AI_InvalidArgumentError",uV=`vercel.ai.error.${mV}`,OT=Symbol.for(uV),VY=class extends Z9{constructor({message:X,cause:J,argument:$}){super({name:mV,message:X,cause:J});this[OT]=!0,this.argument=$}static isInstance(X){return Z9.hasMarker(X,uV)}},MT="AI_InvalidPromptError",ru=`vercel.ai.error.${MT}`;var _T="AI_InvalidResponseDataError",tu=`vercel.ai.error.${_T}`;var AT="AI_JSONParseError",eu=`vercel.ai.error.${AT}`;var TT="AI_LoadAPIKeyError",Xp=`vercel.ai.error.${TT}`;var RT="AI_LoadSettingError",Jp=`vercel.ai.error.${RT}`;var CT="AI_NoContentGeneratedError",$p=`vercel.ai.error.${CT}`;var ET="AI_NoSuchModelError",Yp=`vercel.ai.error.${ET}`;var ST="AI_NoSuchProviderReferenceError",Gp=`vercel.ai.error.${ST}`;var IT="AI_TooManyEmbeddingValuesForCallError",Qp=`vercel.ai.error.${IT}`;var bT="AI_TypeValidationError",zp=`vercel.ai.error.${bT}`;var kT="AI_UnsupportedFunctionalityError",Zp=`vercel.ai.error.${kT}`;var Vp=Object.freeze({status:"aborted"});function E(X,J,$){function Y(Z,W){var B;Object.defineProperty(Z,"_zod",{value:Z._zod??{},enumerable:!1}),(B=Z._zod).traits??(B.traits=new Set),Z._zod.traits.add(X),J(Z,W);for(let H in z.prototype)if(!(H in Z))Object.defineProperty(Z,H,{value:z.prototype[H].bind(Z)});Z._zod.constr=z,Z._zod.def=W}let G=$?.Parent??Object;class Q extends G{}Object.defineProperty(Q,"name",{value:X});function z(Z){var W;let B=$?.Parent?new Q:this;Y(B,Z),(W=B._zod).deferred??(W.deferred=[]);for(let H of B._zod.deferred)H();return B}return Object.defineProperty(z,"init",{value:Y}),Object.defineProperty(z,Symbol.hasInstance,{value:(Z)=>{if($?.Parent&&Z instanceof $.Parent)return!0;return Z?._zod?.traits?.has(X)}}),Object.defineProperty(z,"name",{value:X}),z}var Up=Symbol("zod_brand");class W9 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class b3 extends Error{constructor(X){super(`Encountered unidirectional transform during encode: ${X}`);this.name="ZodEncodeError"}}var YX={};function u8(X){if(X)Object.assign(YX,X);return YX}var j0={};KY(j0,{unwrapMessage:()=>k3,uint8ArrayToHex:()=>GR,uint8ArrayToBase64url:()=>$R,uint8ArrayToBase64:()=>aV,stringifyPrimitive:()=>dV,shallowClone:()=>cV,safeExtend:()=>oT,required:()=>eT,randomString:()=>cT,propertyKeyTypes:()=>NY,promiseAllObject:()=>pT,primitiveTypes:()=>lV,prefixIssues:()=>H9,pick:()=>nT,partial:()=>tT,optionalKeys:()=>LY,omit:()=>sT,objectClone:()=>gT,numKeys:()=>lT,nullish:()=>w3,normalizeParams:()=>Y0,mergeDefs:()=>x9,merge:()=>rT,jsonStringifyReplacer:()=>N4,joinValues:()=>fT,issue:()=>D4,isPlainObject:()=>w9,isObject:()=>O1,hexToUint8Array:()=>YR,getSizableOrigin:()=>nV,getParsedType:()=>dT,getLengthableOrigin:()=>y3,getEnumValues:()=>x3,getElementAtPath:()=>uT,floatSafeRemainder:()=>jY,finalizeIssue:()=>K8,extend:()=>aT,escapeRegex:()=>B9,esc:()=>GX,defineLazy:()=>N0,createTransparentProxy:()=>iT,cloneDef:()=>mT,clone:()=>U8,cleanRegex:()=>v3,cleanEnum:()=>XR,captureStackTrace:()=>QX,cached:()=>L4,base64urlToUint8Array:()=>JR,base64ToUint8Array:()=>sV,assignProp:()=>k9,assertNotEqual:()=>wT,assertNever:()=>yT,assertIs:()=>vT,assertEqual:()=>xT,assert:()=>hT,allowsEval:()=>qY,aborted:()=>v9,NUMBER_FORMAT_RANGES:()=>DY,Class:()=>oV,BIGINT_FORMAT_RANGES:()=>iV});function xT(X){return X}function wT(X){return X}function vT(X){}function yT(X){throw Error()}function hT(X){}function x3(X){let J=Object.values(X).filter((Y)=>typeof Y==="number");return Object.entries(X).filter(([Y,G])=>J.indexOf(+Y)===-1).map(([Y,G])=>G)}function fT(X,J="|"){return X.map(($)=>dV($)).join(J)}function N4(X,J){if(typeof J==="bigint")return J.toString();return J}function L4(X){return{get value(){{let $=X();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function w3(X){return X===null||X===void 0}function v3(X){let J=X.startsWith("^")?1:0,$=X.endsWith("$")?X.length-1:X.length;return X.slice(J,$)}function jY(X,J){let $=(X.toString().split(".")[1]||"").length,Y=J.toString(),G=(Y.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(Y)){let W=Y.match(/\d?e-(\d?)/);if(W?.[1])G=Number.parseInt(W[1])}let Q=$>G?$:G,z=Number.parseInt(X.toFixed(Q).replace(".","")),Z=Number.parseInt(J.toFixed(Q).replace(".",""));return z%Z/10**Q}var pV=Symbol("evaluating");function N0(X,J,$){let Y=void 0;Object.defineProperty(X,J,{get(){if(Y===pV)return;if(Y===void 0)Y=pV,Y=$();return Y},set(G){Object.defineProperty(X,J,{value:G})},configurable:!0})}function gT(X){return Object.create(Object.getPrototypeOf(X),Object.getOwnPropertyDescriptors(X))}function k9(X,J,$){Object.defineProperty(X,J,{value:$,writable:!0,enumerable:!0,configurable:!0})}function x9(...X){let J={};for(let $ of X){let Y=Object.getOwnPropertyDescriptors($);Object.assign(J,Y)}return Object.defineProperties({},J)}function mT(X){return x9(X._zod.def)}function uT(X,J){if(!J)return X;return J.reduce(($,Y)=>$?.[Y],X)}function pT(X){let J=Object.keys(X),$=J.map((Y)=>X[Y]);return Promise.all($).then((Y)=>{let G={};for(let Q=0;Q<J.length;Q++)G[J[Q]]=Y[Q];return G})}function cT(X=10){let $="";for(let Y=0;Y<X;Y++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function GX(X){return JSON.stringify(X)}var QX="captureStackTrace"in Error?Error.captureStackTrace:(...X)=>{};function O1(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}var qY=L4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(X){return!1}});function w9(X){if(O1(X)===!1)return!1;let J=X.constructor;if(J===void 0)return!0;let $=J.prototype;if(O1($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function cV(X){if(w9(X))return{...X};if(Array.isArray(X))return[...X];return X}function lT(X){let J=0;for(let $ in X)if(Object.prototype.hasOwnProperty.call(X,$))J++;return J}var dT=(X)=>{let J=typeof X;switch(J){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(X)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(X))return"array";if(X===null)return"null";if(X.then&&typeof X.then==="function"&&X.catch&&typeof X.catch==="function")return"promise";if(typeof Map<"u"&&X instanceof Map)return"map";if(typeof Set<"u"&&X instanceof Set)return"set";if(typeof Date<"u"&&X instanceof Date)return"date";if(typeof File<"u"&&X instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${J}`)}},NY=new Set(["string","number","symbol"]),lV=new Set(["string","number","bigint","boolean","symbol","undefined"]);function B9(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U8(X,J,$){let Y=new X._zod.constr(J??X._zod.def);if(!J||$?.parent)Y._zod.parent=X;return Y}function Y0(X){let J=X;if(!J)return{};if(typeof J==="string")return{error:()=>J};if(J?.message!==void 0){if(J?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");J.error=J.message}if(delete J.message,typeof J.error==="string")return{...J,error:()=>J.error};return J}function iT(X){let J;return new Proxy({},{get($,Y,G){return J??(J=X()),Reflect.get(J,Y,G)},set($,Y,G,Q){return J??(J=X()),Reflect.set(J,Y,G,Q)},has($,Y){return J??(J=X()),Reflect.has(J,Y)},deleteProperty($,Y){return J??(J=X()),Reflect.deleteProperty(J,Y)},ownKeys($){return J??(J=X()),Reflect.ownKeys(J)},getOwnPropertyDescriptor($,Y){return J??(J=X()),Reflect.getOwnPropertyDescriptor(J,Y)},defineProperty($,Y,G){return J??(J=X()),Reflect.defineProperty(J,Y,G)}})}function dV(X){if(typeof X==="bigint")return X.toString()+"n";if(typeof X==="string")return`"${X}"`;return`${X}`}function LY(X){return Object.keys(X).filter((J)=>{return X[J]._zod.optin==="optional"&&X[J]._zod.optout==="optional"})}var DY={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},iV={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function nT(X,J){let $=X._zod.def,Y=x9(X._zod.def,{get shape(){let G={};for(let Q in J){if(!(Q in $.shape))throw Error(`Unrecognized key: "${Q}"`);if(!J[Q])continue;G[Q]=$.shape[Q]}return k9(this,"shape",G),G},checks:[]});return U8(X,Y)}function sT(X,J){let $=X._zod.def,Y=x9(X._zod.def,{get shape(){let G={...X._zod.def.shape};for(let Q in J){if(!(Q in $.shape))throw Error(`Unrecognized key: "${Q}"`);if(!J[Q])continue;delete G[Q]}return k9(this,"shape",G),G},checks:[]});return U8(X,Y)}function aT(X,J){if(!w9(J))throw Error("Invalid input to extend: expected a plain object");let $=X._zod.def.checks;if($&&$.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=x9(X._zod.def,{get shape(){let Q={...X._zod.def.shape,...J};return k9(this,"shape",Q),Q},checks:[]});return U8(X,G)}function oT(X,J){if(!w9(J))throw Error("Invalid input to safeExtend: expected a plain object");let $={...X._zod.def,get shape(){let Y={...X._zod.def.shape,...J};return k9(this,"shape",Y),Y},checks:X._zod.def.checks};return U8(X,$)}function rT(X,J){let $=x9(X._zod.def,{get shape(){let Y={...X._zod.def.shape,...J._zod.def.shape};return k9(this,"shape",Y),Y},get catchall(){return J._zod.def.catchall},checks:[]});return U8(X,$)}function tT(X,J,$){let Y=x9(J._zod.def,{get shape(){let G=J._zod.def.shape,Q={...G};if($)for(let z in $){if(!(z in G))throw Error(`Unrecognized key: "${z}"`);if(!$[z])continue;Q[z]=X?new X({type:"optional",innerType:G[z]}):G[z]}else for(let z in G)Q[z]=X?new X({type:"optional",innerType:G[z]}):G[z];return k9(this,"shape",Q),Q},checks:[]});return U8(J,Y)}function eT(X,J,$){let Y=x9(J._zod.def,{get shape(){let G=J._zod.def.shape,Q={...G};if($)for(let z in $){if(!(z in Q))throw Error(`Unrecognized key: "${z}"`);if(!$[z])continue;Q[z]=new X({type:"nonoptional",innerType:G[z]})}else for(let z in G)Q[z]=new X({type:"nonoptional",innerType:G[z]});return k9(this,"shape",Q),Q},checks:[]});return U8(J,Y)}function v9(X,J=0){if(X.aborted===!0)return!0;for(let $=J;$<X.issues.length;$++)if(X.issues[$]?.continue!==!0)return!0;return!1}function H9(X,J){return J.map(($)=>{var Y;return(Y=$).path??(Y.path=[]),$.path.unshift(X),$})}function k3(X){return typeof X==="string"?X:X?.message}function K8(X,J,$){let Y={...X,path:X.path??[]};if(!X.message){let G=k3(X.inst?._zod.def?.error?.(X))??k3(J?.error?.(X))??k3($.customError?.(X))??k3($.localeError?.(X))??"Invalid input";Y.message=G}if(delete Y.inst,delete Y.continue,!J?.reportInput)delete Y.input;return Y}function nV(X){if(X instanceof Set)return"set";if(X instanceof Map)return"map";if(X instanceof File)return"file";return"unknown"}function y3(X){if(Array.isArray(X))return"array";if(typeof X==="string")return"string";return"unknown"}function D4(...X){let[J,$,Y]=X;if(typeof J==="string")return{message:J,code:"custom",input:$,inst:Y};return{...J}}function XR(X){return Object.entries(X).filter(([J,$])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function sV(X){let J=atob(X),$=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)$[Y]=J.charCodeAt(Y);return $}function aV(X){let J="";for(let $=0;$<X.length;$++)J+=String.fromCharCode(X[$]);return btoa(J)}function JR(X){let J=X.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-J.length%4)%4);return sV(J+$)}function $R(X){return aV(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function YR(X){let J=X.replace(/^0x/,"");if(J.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(J.length/2);for(let Y=0;Y<J.length;Y+=2)$[Y/2]=Number.parseInt(J.slice(Y,Y+2),16);return $}function GR(X){return Array.from(X).map((J)=>J.toString(16).padStart(2,"0")).join("")}class oV{constructor(...X){}}var rV=(X,J)=>{X.name="$ZodError",Object.defineProperty(X,"_zod",{value:X._zod,enumerable:!1}),Object.defineProperty(X,"issues",{value:J,enumerable:!1}),X.message=JSON.stringify(J,N4,2),Object.defineProperty(X,"toString",{value:()=>X.message,enumerable:!1})},zX=E("$ZodError",rV),FY=E("$ZodError",rV,{Parent:Error});function tV(X,J=($)=>$.message){let $={},Y=[];for(let G of X.issues)if(G.path.length>0)$[G.path[0]]=$[G.path[0]]||[],$[G.path[0]].push(J(G));else Y.push(J(G));return{formErrors:Y,fieldErrors:$}}function eV(X,J){let $=J||function(Q){return Q.message},Y={_errors:[]},G=(Q)=>{for(let z of Q.issues)if(z.code==="invalid_union"&&z.errors.length)z.errors.map((Z)=>G({issues:Z}));else if(z.code==="invalid_key")G({issues:z.issues});else if(z.code==="invalid_element")G({issues:z.issues});else if(z.path.length===0)Y._errors.push($(z));else{let Z=Y,W=0;while(W<z.path.length){let B=z.path[W];if(W!==z.path.length-1)Z[B]=Z[B]||{_errors:[]};else Z[B]=Z[B]||{_errors:[]},Z[B]._errors.push($(z));Z=Z[B],W++}}};return G(X),Y}var ZX=(X)=>(J,$,Y,G)=>{let Q=Y?Object.assign(Y,{async:!1}):{async:!1},z=J._zod.run({value:$,issues:[]},Q);if(z instanceof Promise)throw new W9;if(z.issues.length){let Z=new(G?.Err??X)(z.issues.map((W)=>K8(W,Q,u8())));throw QX(Z,G?.callee),Z}return z.value};var WX=(X)=>async(J,$,Y,G)=>{let Q=Y?Object.assign(Y,{async:!0}):{async:!0},z=J._zod.run({value:$,issues:[]},Q);if(z instanceof Promise)z=await z;if(z.issues.length){let Z=new(G?.Err??X)(z.issues.map((W)=>K8(W,Q,u8())));throw QX(Z,G?.callee),Z}return z.value};var h3=(X)=>(J,$,Y)=>{let G=Y?{...Y,async:!1}:{async:!1},Q=J._zod.run({value:$,issues:[]},G);if(Q instanceof Promise)throw new W9;return Q.issues.length?{success:!1,error:new(X??zX)(Q.issues.map((z)=>K8(z,G,u8())))}:{success:!0,data:Q.value}},XU=h3(FY),f3=(X)=>async(J,$,Y)=>{let G=Y?Object.assign(Y,{async:!0}):{async:!0},Q=J._zod.run({value:$,issues:[]},G);if(Q instanceof Promise)Q=await Q;return Q.issues.length?{success:!1,error:new X(Q.issues.map((z)=>K8(z,G,u8())))}:{success:!0,data:Q.value}},JU=f3(FY),$U=(X)=>(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return ZX(X)(J,$,G)};var YU=(X)=>(J,$,Y)=>{return ZX(X)(J,$,Y)};var GU=(X)=>async(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return WX(X)(J,$,G)};var QU=(X)=>async(J,$,Y)=>{return WX(X)(J,$,Y)};var zU=(X)=>(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return h3(X)(J,$,G)};var ZU=(X)=>(J,$,Y)=>{return h3(X)(J,$,Y)};var WU=(X)=>async(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return f3(X)(J,$,G)};var BU=(X)=>async(J,$,Y)=>{return f3(X)(J,$,Y)};var HU=/^[cC][^\s-]{8,}$/,VU=/^[0-9a-z]+$/,UU=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,KU=/^[0-9a-vA-V]{20}$/,jU=/^[A-Za-z0-9]{27}$/,qU=/^[a-zA-Z0-9_-]{21}$/,NU=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var LU=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,PY=(X)=>{if(!X)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${X}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var DU=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function FU(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var PU=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,OU=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,MU=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,_U=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,AU=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,OY=/^[A-Za-z0-9_-]*$/,TU=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var RU=/^\+(?:[0-9]){6,14}[0-9]$/,CU="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",EU=new RegExp(`^${CU}$`);function SU(X){return typeof X.precision==="number"?X.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":X.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${X.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function IU(X){return new RegExp(`^${SU(X)}$`)}function bU(X){let J=SU({precision:X.precision}),$=["Z"];if(X.local)$.push("");if(X.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Y=`${J}(?:${$.join("|")})`;return new RegExp(`^${CU}T(?:${Y})$`)}var kU=(X)=>{let J=X?`[\\s\\S]{${X?.minimum??0},${X?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var xU=/^-?\d+$/,wU=/^-?\d+(?:\.\d+)?/,vU=/^(?:true|false)$/i,yU=/^null$/i;var hU=/^[^A-Z]*$/,fU=/^[^a-z]*$/;var z6=E("$ZodCheck",(X,J)=>{var $;X._zod??(X._zod={}),X._zod.def=J,($=X._zod).onattach??($.onattach=[])}),gU={number:"number",bigint:"bigint",object:"date"},MY=E("$ZodCheckLessThan",(X,J)=>{z6.init(X,J);let $=gU[typeof J.value];X._zod.onattach.push((Y)=>{let G=Y._zod.bag,Q=(J.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<Q)if(J.inclusive)G.maximum=J.value;else G.exclusiveMaximum=J.value}),X._zod.check=(Y)=>{if(J.inclusive?Y.value<=J.value:Y.value<J.value)return;Y.issues.push({origin:$,code:"too_big",maximum:J.value,input:Y.value,inclusive:J.inclusive,inst:X,continue:!J.abort})}}),_Y=E("$ZodCheckGreaterThan",(X,J)=>{z6.init(X,J);let $=gU[typeof J.value];X._zod.onattach.push((Y)=>{let G=Y._zod.bag,Q=(J.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>Q)if(J.inclusive)G.minimum=J.value;else G.exclusiveMinimum=J.value}),X._zod.check=(Y)=>{if(J.inclusive?Y.value>=J.value:Y.value>J.value)return;Y.issues.push({origin:$,code:"too_small",minimum:J.value,input:Y.value,inclusive:J.inclusive,inst:X,continue:!J.abort})}}),mU=E("$ZodCheckMultipleOf",(X,J)=>{z6.init(X,J),X._zod.onattach.push(($)=>{var Y;(Y=$._zod.bag).multipleOf??(Y.multipleOf=J.value)}),X._zod.check=($)=>{if(typeof $.value!==typeof J.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%J.value===BigInt(0):jY($.value,J.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:J.value,input:$.value,inst:X,continue:!J.abort})}}),uU=E("$ZodCheckNumberFormat",(X,J)=>{z6.init(X,J),J.format=J.format||"float64";let $=J.format?.includes("int"),Y=$?"int":"number",[G,Q]=DY[J.format];X._zod.onattach.push((z)=>{let Z=z._zod.bag;if(Z.format=J.format,Z.minimum=G,Z.maximum=Q,$)Z.pattern=xU}),X._zod.check=(z)=>{let Z=z.value;if($){if(!Number.isInteger(Z)){z.issues.push({expected:Y,format:J.format,code:"invalid_type",continue:!1,input:Z,inst:X});return}if(!Number.isSafeInteger(Z)){if(Z>0)z.issues.push({input:Z,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:X,origin:Y,continue:!J.abort});else z.issues.push({input:Z,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:X,origin:Y,continue:!J.abort});return}}if(Z<G)z.issues.push({origin:"number",input:Z,code:"too_small",minimum:G,inclusive:!0,inst:X,continue:!J.abort});if(Z>Q)z.issues.push({origin:"number",input:Z,code:"too_big",maximum:Q,inst:X})}});var pU=E("$ZodCheckMaxLength",(X,J)=>{var $;z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!w3(G)&&G.length!==void 0}),X._zod.onattach.push((Y)=>{let G=Y._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<G)Y._zod.bag.maximum=J.maximum}),X._zod.check=(Y)=>{let G=Y.value;if(G.length<=J.maximum)return;let z=y3(G);Y.issues.push({origin:z,code:"too_big",maximum:J.maximum,inclusive:!0,input:G,inst:X,continue:!J.abort})}}),cU=E("$ZodCheckMinLength",(X,J)=>{var $;z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!w3(G)&&G.length!==void 0}),X._zod.onattach.push((Y)=>{let G=Y._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>G)Y._zod.bag.minimum=J.minimum}),X._zod.check=(Y)=>{let G=Y.value;if(G.length>=J.minimum)return;let z=y3(G);Y.issues.push({origin:z,code:"too_small",minimum:J.minimum,inclusive:!0,input:G,inst:X,continue:!J.abort})}}),lU=E("$ZodCheckLengthEquals",(X,J)=>{var $;z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!w3(G)&&G.length!==void 0}),X._zod.onattach.push((Y)=>{let G=Y._zod.bag;G.minimum=J.length,G.maximum=J.length,G.length=J.length}),X._zod.check=(Y)=>{let G=Y.value,Q=G.length;if(Q===J.length)return;let z=y3(G),Z=Q>J.length;Y.issues.push({origin:z,...Z?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:Y.value,inst:X,continue:!J.abort})}}),g3=E("$ZodCheckStringFormat",(X,J)=>{var $,Y;if(z6.init(X,J),X._zod.onattach.push((G)=>{let Q=G._zod.bag;if(Q.format=J.format,J.pattern)Q.patterns??(Q.patterns=new Set),Q.patterns.add(J.pattern)}),J.pattern)($=X._zod).check??($.check=(G)=>{if(J.pattern.lastIndex=0,J.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:J.format,input:G.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:X,continue:!J.abort})});else(Y=X._zod).check??(Y.check=()=>{})}),dU=E("$ZodCheckRegex",(X,J)=>{g3.init(X,J),X._zod.check=($)=>{if(J.pattern.lastIndex=0,J.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:J.pattern.toString(),inst:X,continue:!J.abort})}}),iU=E("$ZodCheckLowerCase",(X,J)=>{J.pattern??(J.pattern=hU),g3.init(X,J)}),nU=E("$ZodCheckUpperCase",(X,J)=>{J.pattern??(J.pattern=fU),g3.init(X,J)}),sU=E("$ZodCheckIncludes",(X,J)=>{z6.init(X,J);let $=B9(J.includes),Y=new RegExp(typeof J.position==="number"?`^.{${J.position}}${$}`:$);J.pattern=Y,X._zod.onattach.push((G)=>{let Q=G._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(Y)}),X._zod.check=(G)=>{if(G.value.includes(J.includes,J.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:G.value,inst:X,continue:!J.abort})}}),aU=E("$ZodCheckStartsWith",(X,J)=>{z6.init(X,J);let $=new RegExp(`^${B9(J.prefix)}.*`);J.pattern??(J.pattern=$),X._zod.onattach.push((Y)=>{let G=Y._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add($)}),X._zod.check=(Y)=>{if(Y.value.startsWith(J.prefix))return;Y.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:Y.value,inst:X,continue:!J.abort})}}),oU=E("$ZodCheckEndsWith",(X,J)=>{z6.init(X,J);let $=new RegExp(`.*${B9(J.suffix)}$`);J.pattern??(J.pattern=$),X._zod.onattach.push((Y)=>{let G=Y._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add($)}),X._zod.check=(Y)=>{if(Y.value.endsWith(J.suffix))return;Y.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:Y.value,inst:X,continue:!J.abort})}});var rU=E("$ZodCheckOverwrite",(X,J)=>{z6.init(X,J),X._zod.check=($)=>{$.value=J.tx($.value)}});class AY{constructor(X=[]){if(this.content=[],this.indent=0,this)this.args=X}indented(X){this.indent+=1,X(this),this.indent-=1}write(X){if(typeof X==="function"){X(this,{execution:"sync"}),X(this,{execution:"async"});return}let $=X.split(`
167
- `).filter((Q)=>Q),Y=Math.min(...$.map((Q)=>Q.length-Q.trimStart().length)),G=$.map((Q)=>Q.slice(Y)).map((Q)=>" ".repeat(this.indent*2)+Q);for(let Q of G)this.content.push(Q)}compile(){let X=Function,J=this?.args,Y=[...(this?.content??[""]).map((G)=>` ${G}`)];return new X(...J,Y.join(`
168
- `))}}var eU={major:4,minor:1,patch:8};var S0=E("$ZodType",(X,J)=>{var $;X??(X={}),X._zod.def=J,X._zod.bag=X._zod.bag||{},X._zod.version=eU;let Y=[...X._zod.def.checks??[]];if(X._zod.traits.has("$ZodCheck"))Y.unshift(X);for(let G of Y)for(let Q of G._zod.onattach)Q(X);if(Y.length===0)($=X._zod).deferred??($.deferred=[]),X._zod.deferred?.push(()=>{X._zod.run=X._zod.parse});else{let G=(z,Z,W)=>{let B=v9(z),H;for(let U of Z){if(U._zod.def.when){if(!U._zod.def.when(z))continue}else if(B)continue;let j=z.issues.length,q=U._zod.check(z);if(q instanceof Promise&&W?.async===!1)throw new W9;if(H||q instanceof Promise)H=(H??Promise.resolve()).then(async()=>{if(await q,z.issues.length===j)return;if(!B)B=v9(z,j)});else{if(z.issues.length===j)continue;if(!B)B=v9(z,j)}}if(H)return H.then(()=>{return z});return z},Q=(z,Z,W)=>{if(v9(z))return z.aborted=!0,z;let B=G(Z,Y,W);if(B instanceof Promise){if(W.async===!1)throw new W9;return B.then((H)=>X._zod.parse(H,W))}return X._zod.parse(B,W)};X._zod.run=(z,Z)=>{if(Z.skipChecks)return X._zod.parse(z,Z);if(Z.direction==="backward"){let B=X._zod.parse({value:z.value,issues:[]},{...Z,skipChecks:!0});if(B instanceof Promise)return B.then((H)=>{return Q(H,z,Z)});return Q(B,z,Z)}let W=X._zod.parse(z,Z);if(W instanceof Promise){if(Z.async===!1)throw new W9;return W.then((B)=>G(B,Y,Z))}return G(W,Y,Z)}}X["~standard"]={validate:(G)=>{try{let Q=XU(X,G);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return JU(X,G).then((z)=>z.success?{value:z.data}:{issues:z.error?.issues})}},vendor:"zod",version:1}}),UX=E("$ZodString",(X,J)=>{S0.init(X,J),X._zod.pattern=[...X?._zod.bag?.patterns??[]].pop()??kU(X._zod.bag),X._zod.parse=($,Y)=>{if(J.coerce)try{$.value=String($.value)}catch(G){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:X}),$}}),k0=E("$ZodStringFormat",(X,J)=>{g3.init(X,J),UX.init(X,J)}),WK=E("$ZodGUID",(X,J)=>{J.pattern??(J.pattern=LU),k0.init(X,J)}),BK=E("$ZodUUID",(X,J)=>{if(J.version){let Y={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[J.version];if(Y===void 0)throw Error(`Invalid UUID version: "${J.version}"`);J.pattern??(J.pattern=PY(Y))}else J.pattern??(J.pattern=PY());k0.init(X,J)}),HK=E("$ZodEmail",(X,J)=>{J.pattern??(J.pattern=DU),k0.init(X,J)}),VK=E("$ZodURL",(X,J)=>{k0.init(X,J),X._zod.check=($)=>{try{let Y=$.value.trim(),G=new URL(Y);if(J.hostname){if(J.hostname.lastIndex=0,!J.hostname.test(G.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:TU.source,input:$.value,inst:X,continue:!J.abort})}if(J.protocol){if(J.protocol.lastIndex=0,!J.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:J.protocol.source,input:$.value,inst:X,continue:!J.abort})}if(J.normalize)$.value=G.href;else $.value=Y;return}catch(Y){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:X,continue:!J.abort})}}}),UK=E("$ZodEmoji",(X,J)=>{J.pattern??(J.pattern=FU()),k0.init(X,J)}),KK=E("$ZodNanoID",(X,J)=>{J.pattern??(J.pattern=qU),k0.init(X,J)}),jK=E("$ZodCUID",(X,J)=>{J.pattern??(J.pattern=HU),k0.init(X,J)}),qK=E("$ZodCUID2",(X,J)=>{J.pattern??(J.pattern=VU),k0.init(X,J)}),NK=E("$ZodULID",(X,J)=>{J.pattern??(J.pattern=UU),k0.init(X,J)}),LK=E("$ZodXID",(X,J)=>{J.pattern??(J.pattern=KU),k0.init(X,J)}),DK=E("$ZodKSUID",(X,J)=>{J.pattern??(J.pattern=jU),k0.init(X,J)}),FK=E("$ZodISODateTime",(X,J)=>{J.pattern??(J.pattern=bU(J)),k0.init(X,J)}),PK=E("$ZodISODate",(X,J)=>{J.pattern??(J.pattern=EU),k0.init(X,J)}),OK=E("$ZodISOTime",(X,J)=>{J.pattern??(J.pattern=IU(J)),k0.init(X,J)}),MK=E("$ZodISODuration",(X,J)=>{J.pattern??(J.pattern=NU),k0.init(X,J)}),_K=E("$ZodIPv4",(X,J)=>{J.pattern??(J.pattern=PU),k0.init(X,J),X._zod.onattach.push(($)=>{let Y=$._zod.bag;Y.format="ipv4"})}),AK=E("$ZodIPv6",(X,J)=>{J.pattern??(J.pattern=OU),k0.init(X,J),X._zod.onattach.push(($)=>{let Y=$._zod.bag;Y.format="ipv6"}),X._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:X,continue:!J.abort})}}}),TK=E("$ZodCIDRv4",(X,J)=>{J.pattern??(J.pattern=MU),k0.init(X,J)}),RK=E("$ZodCIDRv6",(X,J)=>{J.pattern??(J.pattern=_U),k0.init(X,J),X._zod.check=($)=>{let Y=$.value.split("/");try{if(Y.length!==2)throw Error();let[G,Q]=Y;if(!Q)throw Error();let z=Number(Q);if(`${z}`!==Q)throw Error();if(z<0||z>128)throw Error();new URL(`http://[${G}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:X,continue:!J.abort})}}});function CK(X){if(X==="")return!0;if(X.length%4!==0)return!1;try{return atob(X),!0}catch{return!1}}var EK=E("$ZodBase64",(X,J)=>{J.pattern??(J.pattern=AU),k0.init(X,J),X._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),X._zod.check=($)=>{if(CK($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:X,continue:!J.abort})}});function zR(X){if(!OY.test(X))return!1;let J=X.replace(/[-_]/g,(Y)=>Y==="-"?"+":"/"),$=J.padEnd(Math.ceil(J.length/4)*4,"=");return CK($)}var SK=E("$ZodBase64URL",(X,J)=>{J.pattern??(J.pattern=OY),k0.init(X,J),X._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),X._zod.check=($)=>{if(zR($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:X,continue:!J.abort})}}),IK=E("$ZodE164",(X,J)=>{J.pattern??(J.pattern=RU),k0.init(X,J)});function ZR(X,J=null){try{let $=X.split(".");if($.length!==3)return!1;let[Y]=$;if(!Y)return!1;let G=JSON.parse(atob(Y));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(J&&(!("alg"in G)||G.alg!==J))return!1;return!0}catch{return!1}}var bK=E("$ZodJWT",(X,J)=>{k0.init(X,J),X._zod.check=($)=>{if(ZR($.value,J.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:X,continue:!J.abort})}});var RY=E("$ZodNumber",(X,J)=>{S0.init(X,J),X._zod.pattern=X._zod.bag.pattern??wU,X._zod.parse=($,Y)=>{if(J.coerce)try{$.value=Number($.value)}catch(z){}let G=$.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return $;let Q=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:G,inst:X,...Q?{received:Q}:{}}),$}}),kK=E("$ZodNumber",(X,J)=>{uU.init(X,J),RY.init(X,J)}),xK=E("$ZodBoolean",(X,J)=>{S0.init(X,J),X._zod.pattern=vU,X._zod.parse=($,Y)=>{if(J.coerce)try{$.value=Boolean($.value)}catch(Q){}let G=$.value;if(typeof G==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:X}),$}});var wK=E("$ZodNull",(X,J)=>{S0.init(X,J),X._zod.pattern=yU,X._zod.values=new Set([null]),X._zod.parse=($,Y)=>{let G=$.value;if(G===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:G,inst:X}),$}});var vK=E("$ZodUnknown",(X,J)=>{S0.init(X,J),X._zod.parse=($)=>$}),yK=E("$ZodNever",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:X}),$}});function XK(X,J,$){if(X.issues.length)J.issues.push(...H9($,X.issues));J.value[$]=X.value}var hK=E("$ZodArray",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{let G=$.value;if(!Array.isArray(G))return $.issues.push({expected:"array",code:"invalid_type",input:G,inst:X}),$;$.value=Array(G.length);let Q=[];for(let z=0;z<G.length;z++){let Z=G[z],W=J.element._zod.run({value:Z,issues:[]},Y);if(W instanceof Promise)Q.push(W.then((B)=>XK(B,$,z)));else XK(W,$,z)}if(Q.length)return Promise.all(Q).then(()=>$);return $}});function VX(X,J,$,Y){if(X.issues.length)J.issues.push(...H9($,X.issues));if(X.value===void 0){if($ in Y)J.value[$]=void 0}else J.value[$]=X.value}function fK(X){let J=Object.keys(X.shape);for(let Y of J)if(!X.shape?.[Y]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Y}": expected a Zod schema`);let $=LY(X.shape);return{...X,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set($)}}function gK(X,J,$,Y,G,Q){let z=[],Z=G.keySet,W=G.catchall._zod,B=W.def.type;for(let H of Object.keys(J)){if(Z.has(H))continue;if(B==="never"){z.push(H);continue}let U=W.run({value:J[H],issues:[]},Y);if(U instanceof Promise)X.push(U.then((j)=>VX(j,$,H,J)));else VX(U,$,H,J)}if(z.length)$.issues.push({code:"unrecognized_keys",keys:z,input:J,inst:Q});if(!X.length)return $;return Promise.all(X).then(()=>{return $})}var WR=E("$ZodObject",(X,J)=>{S0.init(X,J);let $=L4(()=>fK(J));N0(X._zod,"propValues",()=>{let z=J.shape,Z={};for(let W in z){let B=z[W]._zod;if(B.values){Z[W]??(Z[W]=new Set);for(let H of B.values)Z[W].add(H)}}return Z});let Y=O1,G=J.catchall,Q;X._zod.parse=(z,Z)=>{Q??(Q=$.value);let W=z.value;if(!Y(W))return z.issues.push({expected:"object",code:"invalid_type",input:W,inst:X}),z;z.value={};let B=[],H=Q.shape;for(let U of Q.keys){let q=H[U]._zod.run({value:W[U],issues:[]},Z);if(q instanceof Promise)B.push(q.then((K)=>VX(K,z,U,W)));else VX(q,z,U,W)}if(!G)return B.length?Promise.all(B).then(()=>z):z;return gK(B,W,z,Z,$.value,X)}}),mK=E("$ZodObjectJIT",(X,J)=>{WR.init(X,J);let $=X._zod.parse,Y=L4(()=>fK(J)),G=(j)=>{let q=new AY(["shape","payload","ctx"]),K=Y.value,L=(C)=>{let N=GX(C);return`shape[${N}]._zod.run({ value: input[${N}], issues: [] }, ctx)`};q.write("const input = payload.value;");let F=Object.create(null),O=0;for(let C of K.keys)F[C]=`key_${O++}`;q.write("const newResult = {};");for(let C of K.keys){let N=F[C],P=GX(C);q.write(`const ${N} = ${L(C)};`),q.write(`
169
- if (${N}.issues.length) {
170
- payload.issues = payload.issues.concat(${N}.issues.map(iss => ({
171
- ...iss,
172
- path: iss.path ? [${P}, ...iss.path] : [${P}]
173
- })));
174
- }
175
-
176
-
177
- if (${N}.value === undefined) {
178
- if (${P} in input) {
179
- newResult[${P}] = undefined;
180
- }
181
- } else {
182
- newResult[${P}] = ${N}.value;
183
- }
184
-
185
- `)}q.write("payload.value = newResult;"),q.write("return payload;");let _=q.compile();return(C,N)=>_(j,C,N)},Q,z=O1,Z=!YX.jitless,B=Z&&qY.value,H=J.catchall,U;X._zod.parse=(j,q)=>{U??(U=Y.value);let K=j.value;if(!z(K))return j.issues.push({expected:"object",code:"invalid_type",input:K,inst:X}),j;if(Z&&B&&q?.async===!1&&q.jitless!==!0){if(!Q)Q=G(J.shape);if(j=Q(j,q),!H)return j;return gK([],K,j,q,U,X)}return $(j,q)}});function JK(X,J,$,Y){for(let Q of X)if(Q.issues.length===0)return J.value=Q.value,J;let G=X.filter((Q)=>!v9(Q));if(G.length===1)return J.value=G[0].value,G[0];return J.issues.push({code:"invalid_union",input:J.value,inst:$,errors:X.map((Q)=>Q.issues.map((z)=>K8(z,Y,u8())))}),J}var CY=E("$ZodUnion",(X,J)=>{S0.init(X,J),N0(X._zod,"optin",()=>J.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),N0(X._zod,"optout",()=>J.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),N0(X._zod,"values",()=>{if(J.options.every((G)=>G._zod.values))return new Set(J.options.flatMap((G)=>Array.from(G._zod.values)));return}),N0(X._zod,"pattern",()=>{if(J.options.every((G)=>G._zod.pattern)){let G=J.options.map((Q)=>Q._zod.pattern);return new RegExp(`^(${G.map((Q)=>v3(Q.source)).join("|")})$`)}return});let $=J.options.length===1,Y=J.options[0]._zod.run;X._zod.parse=(G,Q)=>{if($)return Y(G,Q);let z=!1,Z=[];for(let W of J.options){let B=W._zod.run({value:G.value,issues:[]},Q);if(B instanceof Promise)Z.push(B),z=!0;else{if(B.issues.length===0)return B;Z.push(B)}}if(!z)return JK(Z,G,X,Q);return Promise.all(Z).then((W)=>{return JK(W,G,X,Q)})}}),uK=E("$ZodDiscriminatedUnion",(X,J)=>{CY.init(X,J);let $=X._zod.parse;N0(X._zod,"propValues",()=>{let G={};for(let Q of J.options){let z=Q._zod.propValues;if(!z||Object.keys(z).length===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(Q)}"`);for(let[Z,W]of Object.entries(z)){if(!G[Z])G[Z]=new Set;for(let B of W)G[Z].add(B)}}return G});let Y=L4(()=>{let G=J.options,Q=new Map;for(let z of G){let Z=z._zod.propValues?.[J.discriminator];if(!Z||Z.size===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(z)}"`);for(let W of Z){if(Q.has(W))throw Error(`Duplicate discriminator value "${String(W)}"`);Q.set(W,z)}}return Q});X._zod.parse=(G,Q)=>{let z=G.value;if(!O1(z))return G.issues.push({code:"invalid_type",expected:"object",input:z,inst:X}),G;let Z=Y.value.get(z?.[J.discriminator]);if(Z)return Z._zod.run(G,Q);if(J.unionFallback)return $(G,Q);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:J.discriminator,input:z,path:[J.discriminator],inst:X}),G}}),pK=E("$ZodIntersection",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{let G=$.value,Q=J.left._zod.run({value:G,issues:[]},Y),z=J.right._zod.run({value:G,issues:[]},Y);if(Q instanceof Promise||z instanceof Promise)return Promise.all([Q,z]).then(([W,B])=>{return $K($,W,B)});return $K($,Q,z)}});function TY(X,J){if(X===J)return{valid:!0,data:X};if(X instanceof Date&&J instanceof Date&&+X===+J)return{valid:!0,data:X};if(w9(X)&&w9(J)){let $=Object.keys(J),Y=Object.keys(X).filter((Q)=>$.indexOf(Q)!==-1),G={...X,...J};for(let Q of Y){let z=TY(X[Q],J[Q]);if(!z.valid)return{valid:!1,mergeErrorPath:[Q,...z.mergeErrorPath]};G[Q]=z.data}return{valid:!0,data:G}}if(Array.isArray(X)&&Array.isArray(J)){if(X.length!==J.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let Y=0;Y<X.length;Y++){let G=X[Y],Q=J[Y],z=TY(G,Q);if(!z.valid)return{valid:!1,mergeErrorPath:[Y,...z.mergeErrorPath]};$.push(z.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function $K(X,J,$){if(J.issues.length)X.issues.push(...J.issues);if($.issues.length)X.issues.push(...$.issues);if(v9(X))return X;let Y=TY(J.value,$.value);if(!Y.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Y.mergeErrorPath)}`);return X.value=Y.data,X}var cK=E("$ZodRecord",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{let G=$.value;if(!w9(G))return $.issues.push({expected:"record",code:"invalid_type",input:G,inst:X}),$;let Q=[];if(J.keyType._zod.values){let z=J.keyType._zod.values;$.value={};for(let W of z)if(typeof W==="string"||typeof W==="number"||typeof W==="symbol"){let B=J.valueType._zod.run({value:G[W],issues:[]},Y);if(B instanceof Promise)Q.push(B.then((H)=>{if(H.issues.length)$.issues.push(...H9(W,H.issues));$.value[W]=H.value}));else{if(B.issues.length)$.issues.push(...H9(W,B.issues));$.value[W]=B.value}}let Z;for(let W in G)if(!z.has(W))Z=Z??[],Z.push(W);if(Z&&Z.length>0)$.issues.push({code:"unrecognized_keys",input:G,inst:X,keys:Z})}else{$.value={};for(let z of Reflect.ownKeys(G)){if(z==="__proto__")continue;let Z=J.keyType._zod.run({value:z,issues:[]},Y);if(Z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Z.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:Z.issues.map((B)=>K8(B,Y,u8())),input:z,path:[z],inst:X}),$.value[Z.value]=Z.value;continue}let W=J.valueType._zod.run({value:G[z],issues:[]},Y);if(W instanceof Promise)Q.push(W.then((B)=>{if(B.issues.length)$.issues.push(...H9(z,B.issues));$.value[Z.value]=B.value}));else{if(W.issues.length)$.issues.push(...H9(z,W.issues));$.value[Z.value]=W.value}}}if(Q.length)return Promise.all(Q).then(()=>$);return $}});var lK=E("$ZodEnum",(X,J)=>{S0.init(X,J);let $=x3(J.entries),Y=new Set($);X._zod.values=Y,X._zod.pattern=new RegExp(`^(${$.filter((G)=>NY.has(typeof G)).map((G)=>typeof G==="string"?B9(G):G.toString()).join("|")})$`),X._zod.parse=(G,Q)=>{let z=G.value;if(Y.has(z))return G;return G.issues.push({code:"invalid_value",values:$,input:z,inst:X}),G}}),dK=E("$ZodLiteral",(X,J)=>{if(S0.init(X,J),J.values.length===0)throw Error("Cannot create literal schema with no valid values");X._zod.values=new Set(J.values),X._zod.pattern=new RegExp(`^(${J.values.map(($)=>typeof $==="string"?B9($):$?B9($.toString()):String($)).join("|")})$`),X._zod.parse=($,Y)=>{let G=$.value;if(X._zod.values.has(G))return $;return $.issues.push({code:"invalid_value",values:J.values,input:G,inst:X}),$}});var iK=E("$ZodTransform",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{if(Y.direction==="backward")throw new b3(X.constructor.name);let G=J.transform($.value,$);if(Y.async)return(G instanceof Promise?G:Promise.resolve(G)).then((z)=>{return $.value=z,$});if(G instanceof Promise)throw new W9;return $.value=G,$}});function YK(X,J){if(X.issues.length&&J===void 0)return{issues:[],value:void 0};return X}var nK=E("$ZodOptional",(X,J)=>{S0.init(X,J),X._zod.optin="optional",X._zod.optout="optional",N0(X._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,void 0]):void 0}),N0(X._zod,"pattern",()=>{let $=J.innerType._zod.pattern;return $?new RegExp(`^(${v3($.source)})?$`):void 0}),X._zod.parse=($,Y)=>{if(J.innerType._zod.optin==="optional"){let G=J.innerType._zod.run($,Y);if(G instanceof Promise)return G.then((Q)=>YK(Q,$.value));return YK(G,$.value)}if($.value===void 0)return $;return J.innerType._zod.run($,Y)}}),sK=E("$ZodNullable",(X,J)=>{S0.init(X,J),N0(X._zod,"optin",()=>J.innerType._zod.optin),N0(X._zod,"optout",()=>J.innerType._zod.optout),N0(X._zod,"pattern",()=>{let $=J.innerType._zod.pattern;return $?new RegExp(`^(${v3($.source)}|null)$`):void 0}),N0(X._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,null]):void 0}),X._zod.parse=($,Y)=>{if($.value===null)return $;return J.innerType._zod.run($,Y)}}),aK=E("$ZodDefault",(X,J)=>{S0.init(X,J),X._zod.optin="optional",N0(X._zod,"values",()=>J.innerType._zod.values),X._zod.parse=($,Y)=>{if(Y.direction==="backward")return J.innerType._zod.run($,Y);if($.value===void 0)return $.value=J.defaultValue,$;let G=J.innerType._zod.run($,Y);if(G instanceof Promise)return G.then((Q)=>GK(Q,J));return GK(G,J)}});function GK(X,J){if(X.value===void 0)X.value=J.defaultValue;return X}var oK=E("$ZodPrefault",(X,J)=>{S0.init(X,J),X._zod.optin="optional",N0(X._zod,"values",()=>J.innerType._zod.values),X._zod.parse=($,Y)=>{if(Y.direction==="backward")return J.innerType._zod.run($,Y);if($.value===void 0)$.value=J.defaultValue;return J.innerType._zod.run($,Y)}}),rK=E("$ZodNonOptional",(X,J)=>{S0.init(X,J),N0(X._zod,"values",()=>{let $=J.innerType._zod.values;return $?new Set([...$].filter((Y)=>Y!==void 0)):void 0}),X._zod.parse=($,Y)=>{let G=J.innerType._zod.run($,Y);if(G instanceof Promise)return G.then((Q)=>QK(Q,X));return QK(G,X)}});function QK(X,J){if(!X.issues.length&&X.value===void 0)X.issues.push({code:"invalid_type",expected:"nonoptional",input:X.value,inst:J});return X}var tK=E("$ZodCatch",(X,J)=>{S0.init(X,J),N0(X._zod,"optin",()=>J.innerType._zod.optin),N0(X._zod,"optout",()=>J.innerType._zod.optout),N0(X._zod,"values",()=>J.innerType._zod.values),X._zod.parse=($,Y)=>{if(Y.direction==="backward")return J.innerType._zod.run($,Y);let G=J.innerType._zod.run($,Y);if(G instanceof Promise)return G.then((Q)=>{if($.value=Q.value,Q.issues.length)$.value=J.catchValue({...$,error:{issues:Q.issues.map((z)=>K8(z,Y,u8()))},input:$.value}),$.issues=[];return $});if($.value=G.value,G.issues.length)$.value=J.catchValue({...$,error:{issues:G.issues.map((Q)=>K8(Q,Y,u8()))},input:$.value}),$.issues=[];return $}});var eK=E("$ZodPipe",(X,J)=>{S0.init(X,J),N0(X._zod,"values",()=>J.in._zod.values),N0(X._zod,"optin",()=>J.in._zod.optin),N0(X._zod,"optout",()=>J.out._zod.optout),N0(X._zod,"propValues",()=>J.in._zod.propValues),X._zod.parse=($,Y)=>{if(Y.direction==="backward"){let Q=J.out._zod.run($,Y);if(Q instanceof Promise)return Q.then((z)=>HX(z,J.in,Y));return HX(Q,J.in,Y)}let G=J.in._zod.run($,Y);if(G instanceof Promise)return G.then((Q)=>HX(Q,J.out,Y));return HX(G,J.out,Y)}});function HX(X,J,$){if(X.issues.length)return X.aborted=!0,X;return J._zod.run({value:X.value,issues:X.issues},$)}var Xj=E("$ZodReadonly",(X,J)=>{S0.init(X,J),N0(X._zod,"propValues",()=>J.innerType._zod.propValues),N0(X._zod,"values",()=>J.innerType._zod.values),N0(X._zod,"optin",()=>J.innerType._zod.optin),N0(X._zod,"optout",()=>J.innerType._zod.optout),X._zod.parse=($,Y)=>{if(Y.direction==="backward")return J.innerType._zod.run($,Y);let G=J.innerType._zod.run($,Y);if(G instanceof Promise)return G.then(zK);return zK(G)}});function zK(X){return X.value=Object.freeze(X.value),X}var Jj=E("$ZodLazy",(X,J)=>{S0.init(X,J),N0(X._zod,"innerType",()=>J.getter()),N0(X._zod,"pattern",()=>X._zod.innerType._zod.pattern),N0(X._zod,"propValues",()=>X._zod.innerType._zod.propValues),N0(X._zod,"optin",()=>X._zod.innerType._zod.optin??void 0),N0(X._zod,"optout",()=>X._zod.innerType._zod.optout??void 0),X._zod.parse=($,Y)=>{return X._zod.innerType._zod.run($,Y)}}),$j=E("$ZodCustom",(X,J)=>{z6.init(X,J),S0.init(X,J),X._zod.parse=($,Y)=>{return $},X._zod.check=($)=>{let Y=$.value,G=J.fn(Y);if(G instanceof Promise)return G.then((Q)=>ZK(Q,$,Y,X));ZK(G,$,Y,X);return}});function ZK(X,J,$,Y){if(!X){let G={code:"custom",input:$,inst:Y,path:[...Y._zod.def.path??[]],continue:!Y._zod.def.abort};if(Y._zod.def.params)G.params=Y._zod.def.params;J.issues.push(D4(G))}}var Cp=Symbol("ZodOutput"),Ep=Symbol("ZodInput");class KX{constructor(){this._map=new WeakMap,this._idmap=new Map}add(X,...J){let $=J[0];if(this._map.set(X,$),$&&typeof $==="object"&&"id"in $){if(this._idmap.has($.id))throw Error(`ID ${$.id} already exists in the registry`);this._idmap.set($.id,X)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(X){let J=this._map.get(X);if(J&&typeof J==="object"&&"id"in J)this._idmap.delete(J.id);return this._map.delete(X),this}get(X){let J=X._zod.parent;if(J){let $={...this.get(J)??{}};delete $.id;let Y={...$,...this._map.get(X)};return Object.keys(Y).length?Y:void 0}return this._map.get(X)}has(X){return this._map.has(X)}}function BR(){return new KX}var M1=BR();function Yj(X,J){return new X({type:"string",...Y0(J)})}function Gj(X,J){return new X({type:"string",format:"email",check:"string_format",abort:!1,...Y0(J)})}function EY(X,J){return new X({type:"string",format:"guid",check:"string_format",abort:!1,...Y0(J)})}function Qj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,...Y0(J)})}function zj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Y0(J)})}function Zj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Y0(J)})}function Wj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Y0(J)})}function Bj(X,J){return new X({type:"string",format:"url",check:"string_format",abort:!1,...Y0(J)})}function Hj(X,J){return new X({type:"string",format:"emoji",check:"string_format",abort:!1,...Y0(J)})}function Vj(X,J){return new X({type:"string",format:"nanoid",check:"string_format",abort:!1,...Y0(J)})}function Uj(X,J){return new X({type:"string",format:"cuid",check:"string_format",abort:!1,...Y0(J)})}function Kj(X,J){return new X({type:"string",format:"cuid2",check:"string_format",abort:!1,...Y0(J)})}function jj(X,J){return new X({type:"string",format:"ulid",check:"string_format",abort:!1,...Y0(J)})}function qj(X,J){return new X({type:"string",format:"xid",check:"string_format",abort:!1,...Y0(J)})}function Nj(X,J){return new X({type:"string",format:"ksuid",check:"string_format",abort:!1,...Y0(J)})}function Lj(X,J){return new X({type:"string",format:"ipv4",check:"string_format",abort:!1,...Y0(J)})}function Dj(X,J){return new X({type:"string",format:"ipv6",check:"string_format",abort:!1,...Y0(J)})}function Fj(X,J){return new X({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Y0(J)})}function Pj(X,J){return new X({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Y0(J)})}function Oj(X,J){return new X({type:"string",format:"base64",check:"string_format",abort:!1,...Y0(J)})}function Mj(X,J){return new X({type:"string",format:"base64url",check:"string_format",abort:!1,...Y0(J)})}function _j(X,J){return new X({type:"string",format:"e164",check:"string_format",abort:!1,...Y0(J)})}function Aj(X,J){return new X({type:"string",format:"jwt",check:"string_format",abort:!1,...Y0(J)})}function Tj(X,J){return new X({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Y0(J)})}function Rj(X,J){return new X({type:"string",format:"date",check:"string_format",...Y0(J)})}function Cj(X,J){return new X({type:"string",format:"time",check:"string_format",precision:null,...Y0(J)})}function Ej(X,J){return new X({type:"string",format:"duration",check:"string_format",...Y0(J)})}function Sj(X,J){return new X({type:"number",checks:[],...Y0(J)})}function Ij(X,J){return new X({type:"number",check:"number_format",abort:!1,format:"safeint",...Y0(J)})}function bj(X,J){return new X({type:"boolean",...Y0(J)})}function kj(X,J){return new X({type:"null",...Y0(J)})}function xj(X){return new X({type:"unknown"})}function wj(X,J){return new X({type:"never",...Y0(J)})}function jX(X,J){return new MY({check:"less_than",...Y0(J),value:X,inclusive:!1})}function m3(X,J){return new MY({check:"less_than",...Y0(J),value:X,inclusive:!0})}function qX(X,J){return new _Y({check:"greater_than",...Y0(J),value:X,inclusive:!1})}function u3(X,J){return new _Y({check:"greater_than",...Y0(J),value:X,inclusive:!0})}function NX(X,J){return new mU({check:"multiple_of",...Y0(J),value:X})}function LX(X,J){return new pU({check:"max_length",...Y0(J),maximum:X})}function F4(X,J){return new cU({check:"min_length",...Y0(J),minimum:X})}function DX(X,J){return new lU({check:"length_equals",...Y0(J),length:X})}function SY(X,J){return new dU({check:"string_format",format:"regex",...Y0(J),pattern:X})}function IY(X){return new iU({check:"string_format",format:"lowercase",...Y0(X)})}function bY(X){return new nU({check:"string_format",format:"uppercase",...Y0(X)})}function kY(X,J){return new sU({check:"string_format",format:"includes",...Y0(J),includes:X})}function xY(X,J){return new aU({check:"string_format",format:"starts_with",...Y0(J),prefix:X})}function wY(X,J){return new oU({check:"string_format",format:"ends_with",...Y0(J),suffix:X})}function _1(X){return new rU({check:"overwrite",tx:X})}function vY(X){return _1((J)=>J.normalize(X))}function yY(){return _1((X)=>X.trim())}function hY(){return _1((X)=>X.toLowerCase())}function fY(){return _1((X)=>X.toUpperCase())}function vj(X,J,$){return new X({type:"array",element:J,...Y0($)})}function yj(X,J,$){let Y=Y0($);return Y.abort??(Y.abort=!0),new X({type:"custom",check:"custom",fn:J,...Y})}function hj(X,J,$){return new X({type:"custom",check:"custom",fn:J,...Y0($)})}function fj(X){let J=HR(($)=>{return $.addIssue=(Y)=>{if(typeof Y==="string")$.issues.push(D4(Y,$.value,J._zod.def));else{let G=Y;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=$.value),G.inst??(G.inst=J),G.continue??(G.continue=!J._zod.def.abort),$.issues.push(D4(G))}},X($.value,$)});return J}function HR(X,J){let $=new z6({check:"custom",...Y0(J)});return $._zod.check=X,$}class gY{constructor(X){this.counter=0,this.metadataRegistry=X?.metadata??M1,this.target=X?.target??"draft-2020-12",this.unrepresentable=X?.unrepresentable??"throw",this.override=X?.override??(()=>{}),this.io=X?.io??"output",this.seen=new Map}process(X,J={path:[],schemaPath:[]}){var $;let Y=X._zod.def,G={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Q=this.seen.get(X);if(Q){if(Q.count++,J.schemaPath.includes(X))Q.cycle=J.path;return Q.schema}let z={schema:{},count:1,cycle:void 0,path:J.path};this.seen.set(X,z);let Z=X._zod.toJSONSchema?.();if(Z)z.schema=Z;else{let H={...J,schemaPath:[...J.schemaPath,X],path:J.path},U=X._zod.parent;if(U)z.ref=U,this.process(U,H),this.seen.get(U).isParent=!0;else{let j=z.schema;switch(Y.type){case"string":{let q=j;q.type="string";let{minimum:K,maximum:L,format:F,patterns:O,contentEncoding:_}=X._zod.bag;if(typeof K==="number")q.minLength=K;if(typeof L==="number")q.maxLength=L;if(F){if(q.format=G[F]??F,q.format==="")delete q.format}if(_)q.contentEncoding=_;if(O&&O.size>0){let C=[...O];if(C.length===1)q.pattern=C[0].source;else if(C.length>1)z.schema.allOf=[...C.map((N)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:N.source}))]}break}case"number":{let q=j,{minimum:K,maximum:L,format:F,multipleOf:O,exclusiveMaximum:_,exclusiveMinimum:C}=X._zod.bag;if(typeof F==="string"&&F.includes("int"))q.type="integer";else q.type="number";if(typeof C==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")q.minimum=C,q.exclusiveMinimum=!0;else q.exclusiveMinimum=C;if(typeof K==="number"){if(q.minimum=K,typeof C==="number"&&this.target!=="draft-4")if(C>=K)delete q.minimum;else delete q.exclusiveMinimum}if(typeof _==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")q.maximum=_,q.exclusiveMaximum=!0;else q.exclusiveMaximum=_;if(typeof L==="number"){if(q.maximum=L,typeof _==="number"&&this.target!=="draft-4")if(_<=L)delete q.maximum;else delete q.exclusiveMaximum}if(typeof O==="number")q.multipleOf=O;break}case"boolean":{let q=j;q.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")j.type="string",j.nullable=!0,j.enum=[null];else j.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{j.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let q=j,{minimum:K,maximum:L}=X._zod.bag;if(typeof K==="number")q.minItems=K;if(typeof L==="number")q.maxItems=L;q.type="array",q.items=this.process(Y.element,{...H,path:[...H.path,"items"]});break}case"object":{let q=j;q.type="object",q.properties={};let K=Y.shape;for(let O in K)q.properties[O]=this.process(K[O],{...H,path:[...H.path,"properties",O]});let L=new Set(Object.keys(K)),F=new Set([...L].filter((O)=>{let _=Y.shape[O]._zod;if(this.io==="input")return _.optin===void 0;else return _.optout===void 0}));if(F.size>0)q.required=Array.from(F);if(Y.catchall?._zod.def.type==="never")q.additionalProperties=!1;else if(!Y.catchall){if(this.io==="output")q.additionalProperties=!1}else if(Y.catchall)q.additionalProperties=this.process(Y.catchall,{...H,path:[...H.path,"additionalProperties"]});break}case"union":{let q=j,K=Y.options.map((L,F)=>this.process(L,{...H,path:[...H.path,"anyOf",F]}));q.anyOf=K;break}case"intersection":{let q=j,K=this.process(Y.left,{...H,path:[...H.path,"allOf",0]}),L=this.process(Y.right,{...H,path:[...H.path,"allOf",1]}),F=(_)=>("allOf"in _)&&Object.keys(_).length===1,O=[...F(K)?K.allOf:[K],...F(L)?L.allOf:[L]];q.allOf=O;break}case"tuple":{let q=j;q.type="array";let K=this.target==="draft-2020-12"?"prefixItems":"items",L=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",F=Y.items.map((N,P)=>this.process(N,{...H,path:[...H.path,K,P]})),O=Y.rest?this.process(Y.rest,{...H,path:[...H.path,L,...this.target==="openapi-3.0"?[Y.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(q.prefixItems=F,O)q.items=O}else if(this.target==="openapi-3.0"){if(q.items={anyOf:F},O)q.items.anyOf.push(O);if(q.minItems=F.length,!O)q.maxItems=F.length}else if(q.items=F,O)q.additionalItems=O;let{minimum:_,maximum:C}=X._zod.bag;if(typeof _==="number")q.minItems=_;if(typeof C==="number")q.maxItems=C;break}case"record":{let q=j;if(q.type="object",this.target==="draft-7"||this.target==="draft-2020-12")q.propertyNames=this.process(Y.keyType,{...H,path:[...H.path,"propertyNames"]});q.additionalProperties=this.process(Y.valueType,{...H,path:[...H.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let q=j,K=x3(Y.entries);if(K.every((L)=>typeof L==="number"))q.type="number";if(K.every((L)=>typeof L==="string"))q.type="string";q.enum=K;break}case"literal":{let q=j,K=[];for(let L of Y.values)if(L===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof L==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else K.push(Number(L));else K.push(L);if(K.length===0);else if(K.length===1){let L=K[0];if(q.type=L===null?"null":typeof L,this.target==="draft-4"||this.target==="openapi-3.0")q.enum=[L];else q.const=L}else{if(K.every((L)=>typeof L==="number"))q.type="number";if(K.every((L)=>typeof L==="string"))q.type="string";if(K.every((L)=>typeof L==="boolean"))q.type="string";if(K.every((L)=>L===null))q.type="null";q.enum=K}break}case"file":{let q=j,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:L,maximum:F,mime:O}=X._zod.bag;if(L!==void 0)K.minLength=L;if(F!==void 0)K.maxLength=F;if(O)if(O.length===1)K.contentMediaType=O[0],Object.assign(q,K);else q.anyOf=O.map((_)=>{return{...K,contentMediaType:_}});else Object.assign(q,K);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let q=this.process(Y.innerType,H);if(this.target==="openapi-3.0")z.ref=Y.innerType,j.nullable=!0;else j.anyOf=[q,{type:"null"}];break}case"nonoptional":{this.process(Y.innerType,H),z.ref=Y.innerType;break}case"success":{let q=j;q.type="boolean";break}case"default":{this.process(Y.innerType,H),z.ref=Y.innerType,j.default=JSON.parse(JSON.stringify(Y.defaultValue));break}case"prefault":{if(this.process(Y.innerType,H),z.ref=Y.innerType,this.io==="input")j._prefault=JSON.parse(JSON.stringify(Y.defaultValue));break}case"catch":{this.process(Y.innerType,H),z.ref=Y.innerType;let q;try{q=Y.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}j.default=q;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let q=j,K=X._zod.pattern;if(!K)throw Error("Pattern not found in template literal");q.type="string",q.pattern=K.source;break}case"pipe":{let q=this.io==="input"?Y.in._zod.def.type==="transform"?Y.out:Y.in:Y.out;this.process(q,H),z.ref=q;break}case"readonly":{this.process(Y.innerType,H),z.ref=Y.innerType,j.readOnly=!0;break}case"promise":{this.process(Y.innerType,H),z.ref=Y.innerType;break}case"optional":{this.process(Y.innerType,H),z.ref=Y.innerType;break}case"lazy":{let q=X._zod.innerType;this.process(q,H),z.ref=q;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let W=this.metadataRegistry.get(X);if(W)Object.assign(z.schema,W);if(this.io==="input"&&o0(X))delete z.schema.examples,delete z.schema.default;if(this.io==="input"&&z.schema._prefault)($=z.schema).default??($.default=z.schema._prefault);return delete z.schema._prefault,this.seen.get(X).schema}emit(X,J){let $={cycles:J?.cycles??"ref",reused:J?.reused??"inline",external:J?.external??void 0},Y=this.seen.get(X);if(!Y)throw Error("Unprocessed schema. This is a bug in Zod.");let G=(B)=>{let H=this.target==="draft-2020-12"?"$defs":"definitions";if($.external){let K=$.external.registry.get(B[0])?.id,L=$.external.uri??((O)=>O);if(K)return{ref:L(K)};let F=B[1].defId??B[1].schema.id??`schema${this.counter++}`;return B[1].defId=F,{defId:F,ref:`${L("__shared")}#/${H}/${F}`}}if(B[1]===Y)return{ref:"#"};let j=`${"#"}/${H}/`,q=B[1].schema.id??`__schema${this.counter++}`;return{defId:q,ref:j+q}},Q=(B)=>{if(B[1].schema.$ref)return;let H=B[1],{ref:U,defId:j}=G(B);if(H.def={...H.schema},j)H.defId=j;let q=H.schema;for(let K in q)delete q[K];q.$ref=U};if($.cycles==="throw")for(let B of this.seen.entries()){let H=B[1];if(H.cycle)throw Error(`Cycle detected: #/${H.cycle?.join("/")}/<root>
186
-
187
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let B of this.seen.entries()){let H=B[1];if(X===B[0]){Q(B);continue}if($.external){let j=$.external.registry.get(B[0])?.id;if(X!==B[0]&&j){Q(B);continue}}if(this.metadataRegistry.get(B[0])?.id){Q(B);continue}if(H.cycle){Q(B);continue}if(H.count>1){if($.reused==="ref"){Q(B);continue}}}let z=(B,H)=>{let U=this.seen.get(B),j=U.def??U.schema,q={...j};if(U.ref===null)return;let K=U.ref;if(U.ref=null,K){z(K,H);let L=this.seen.get(K).schema;if(L.$ref&&(H.target==="draft-7"||H.target==="draft-4"||H.target==="openapi-3.0"))j.allOf=j.allOf??[],j.allOf.push(L);else Object.assign(j,L),Object.assign(j,q)}if(!U.isParent)this.override({zodSchema:B,jsonSchema:j,path:U.path??[]})};for(let B of[...this.seen.entries()].reverse())z(B[0],{target:this.target});let Z={};if(this.target==="draft-2020-12")Z.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")Z.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")Z.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if($.external?.uri){let B=$.external.registry.get(X)?.id;if(!B)throw Error("Schema is missing an `id` property");Z.$id=$.external.uri(B)}Object.assign(Z,Y.def);let W=$.external?.defs??{};for(let B of this.seen.entries()){let H=B[1];if(H.def&&H.defId)W[H.defId]=H.def}if($.external);else if(Object.keys(W).length>0)if(this.target==="draft-2020-12")Z.$defs=W;else Z.definitions=W;try{return JSON.parse(JSON.stringify(Z))}catch(B){throw Error("Error converting schema to JSON.")}}}function gj(X,J){if(X instanceof KX){let Y=new gY(J),G={};for(let Z of X._idmap.entries()){let[W,B]=Z;Y.process(B)}let Q={},z={registry:X,uri:J?.uri,defs:G};for(let Z of X._idmap.entries()){let[W,B]=Z;Q[W]=Y.emit(B,{...J,external:z})}if(Object.keys(G).length>0){let Z=Y.target==="draft-2020-12"?"$defs":"definitions";Q.__shared={[Z]:G}}return{schemas:Q}}let $=new gY(J);return $.process(X),$.emit(X,J)}function o0(X,J){let $=J??{seen:new Set};if($.seen.has(X))return!1;$.seen.add(X);let G=X._zod.def;switch(G.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return o0(G.element,$);case"object":{for(let Q in G.shape)if(o0(G.shape[Q],$))return!0;return!1}case"union":{for(let Q of G.options)if(o0(Q,$))return!0;return!1}case"intersection":return o0(G.left,$)||o0(G.right,$);case"tuple":{for(let Q of G.items)if(o0(Q,$))return!0;if(G.rest&&o0(G.rest,$))return!0;return!1}case"record":return o0(G.keyType,$)||o0(G.valueType,$);case"map":return o0(G.keyType,$)||o0(G.valueType,$);case"set":return o0(G.valueType,$);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return o0(G.innerType,$);case"lazy":return o0(G.getter(),$);case"default":return o0(G.innerType,$);case"prefault":return o0(G.innerType,$);case"custom":return!1;case"transform":return!0;case"pipe":return o0(G.in,$)||o0(G.out,$);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${G.type}`)}var NR=E("ZodISODateTime",(X,J)=>{FK.init(X,J),y0.init(X,J)});function mj(X){return Tj(NR,X)}var LR=E("ZodISODate",(X,J)=>{PK.init(X,J),y0.init(X,J)});function uj(X){return Rj(LR,X)}var DR=E("ZodISOTime",(X,J)=>{OK.init(X,J),y0.init(X,J)});function pj(X){return Cj(DR,X)}var FR=E("ZodISODuration",(X,J)=>{MK.init(X,J),y0.init(X,J)});function cj(X){return Ej(FR,X)}var lj=(X,J)=>{zX.init(X,J),X.name="ZodError",Object.defineProperties(X,{format:{value:($)=>eV(X,$)},flatten:{value:($)=>tV(X,$)},addIssue:{value:($)=>{X.issues.push($),X.message=JSON.stringify(X.issues,N4,2)}},addIssues:{value:($)=>{X.issues.push(...$),X.message=JSON.stringify(X.issues,N4,2)}},isEmpty:{get(){return X.issues.length===0}}})},Gc=E("ZodError",lj),c6=E("ZodError",lj,{Parent:Error});var dj=ZX(c6),ij=WX(c6),nj=h3(c6),PX=f3(c6),sj=$U(c6),aj=YU(c6),oj=GU(c6),rj=QU(c6),tj=zU(c6),ej=ZU(c6),Xq=WU(c6),Jq=BU(c6);var h0=E("ZodType",(X,J)=>{return S0.init(X,J),X.def=J,X.type=J.type,Object.defineProperty(X,"_def",{value:J}),X.check=(...$)=>{return X.clone({...J,checks:[...J.checks??[],...$.map((Y)=>typeof Y==="function"?{_zod:{check:Y,def:{check:"custom"},onattach:[]}}:Y)]})},X.clone=($,Y)=>U8(X,$,Y),X.brand=()=>X,X.register=($,Y)=>{return $.add(X,Y),X},X.parse=($,Y)=>dj(X,$,Y,{callee:X.parse}),X.safeParse=($,Y)=>nj(X,$,Y),X.parseAsync=async($,Y)=>ij(X,$,Y,{callee:X.parseAsync}),X.safeParseAsync=async($,Y)=>PX(X,$,Y),X.spa=X.safeParseAsync,X.encode=($,Y)=>sj(X,$,Y),X.decode=($,Y)=>aj(X,$,Y),X.encodeAsync=async($,Y)=>oj(X,$,Y),X.decodeAsync=async($,Y)=>rj(X,$,Y),X.safeEncode=($,Y)=>tj(X,$,Y),X.safeDecode=($,Y)=>ej(X,$,Y),X.safeEncodeAsync=async($,Y)=>Xq(X,$,Y),X.safeDecodeAsync=async($,Y)=>Jq(X,$,Y),X.refine=($,Y)=>X.check(UC($,Y)),X.superRefine=($)=>X.check(KC($)),X.overwrite=($)=>X.check(_1($)),X.optional=()=>Gq(X),X.nullable=()=>Qq(X),X.nullish=()=>Gq(Qq(X)),X.nonoptional=($)=>QC(X,$),X.array=()=>pY(X),X.or=($)=>cY([X,$]),X.and=($)=>aR(X,$),X.transform=($)=>zq(X,eR($)),X.default=($)=>$C(X,$),X.prefault=($)=>GC(X,$),X.catch=($)=>ZC(X,$),X.pipe=($)=>zq(X,$),X.readonly=()=>HC(X),X.describe=($)=>{let Y=X.clone();return M1.add(Y,{description:$}),Y},Object.defineProperty(X,"description",{get(){return M1.get(X)?.description},configurable:!0}),X.meta=(...$)=>{if($.length===0)return M1.get(X);let Y=X.clone();return M1.add(Y,$[0]),Y},X.isOptional=()=>X.safeParse(void 0).success,X.isNullable=()=>X.safeParse(null).success,X}),Zq=E("_ZodString",(X,J)=>{UX.init(X,J),h0.init(X,J);let $=X._zod.bag;X.format=$.format??null,X.minLength=$.minimum??null,X.maxLength=$.maximum??null,X.regex=(...Y)=>X.check(SY(...Y)),X.includes=(...Y)=>X.check(kY(...Y)),X.startsWith=(...Y)=>X.check(xY(...Y)),X.endsWith=(...Y)=>X.check(wY(...Y)),X.min=(...Y)=>X.check(F4(...Y)),X.max=(...Y)=>X.check(LX(...Y)),X.length=(...Y)=>X.check(DX(...Y)),X.nonempty=(...Y)=>X.check(F4(1,...Y)),X.lowercase=(Y)=>X.check(IY(Y)),X.uppercase=(Y)=>X.check(bY(Y)),X.trim=()=>X.check(yY()),X.normalize=(...Y)=>X.check(vY(...Y)),X.toLowerCase=()=>X.check(hY()),X.toUpperCase=()=>X.check(fY())}),_R=E("ZodString",(X,J)=>{UX.init(X,J),Zq.init(X,J),X.email=($)=>X.check(Gj(AR,$)),X.url=($)=>X.check(Bj(TR,$)),X.jwt=($)=>X.check(Aj(mR,$)),X.emoji=($)=>X.check(Hj(RR,$)),X.guid=($)=>X.check(EY($q,$)),X.uuid=($)=>X.check(Qj(OX,$)),X.uuidv4=($)=>X.check(zj(OX,$)),X.uuidv6=($)=>X.check(Zj(OX,$)),X.uuidv7=($)=>X.check(Wj(OX,$)),X.nanoid=($)=>X.check(Vj(CR,$)),X.guid=($)=>X.check(EY($q,$)),X.cuid=($)=>X.check(Uj(ER,$)),X.cuid2=($)=>X.check(Kj(SR,$)),X.ulid=($)=>X.check(jj(IR,$)),X.base64=($)=>X.check(Oj(hR,$)),X.base64url=($)=>X.check(Mj(fR,$)),X.xid=($)=>X.check(qj(bR,$)),X.ksuid=($)=>X.check(Nj(kR,$)),X.ipv4=($)=>X.check(Lj(xR,$)),X.ipv6=($)=>X.check(Dj(wR,$)),X.cidrv4=($)=>X.check(Fj(vR,$)),X.cidrv6=($)=>X.check(Pj(yR,$)),X.e164=($)=>X.check(_j(gR,$)),X.datetime=($)=>X.check(mj($)),X.date=($)=>X.check(uj($)),X.time=($)=>X.check(pj($)),X.duration=($)=>X.check(cj($))});function Wq(X){return Yj(_R,X)}var y0=E("ZodStringFormat",(X,J)=>{k0.init(X,J),Zq.init(X,J)}),AR=E("ZodEmail",(X,J)=>{HK.init(X,J),y0.init(X,J)});var $q=E("ZodGUID",(X,J)=>{WK.init(X,J),y0.init(X,J)});var OX=E("ZodUUID",(X,J)=>{BK.init(X,J),y0.init(X,J)});var TR=E("ZodURL",(X,J)=>{VK.init(X,J),y0.init(X,J)});var RR=E("ZodEmoji",(X,J)=>{UK.init(X,J),y0.init(X,J)});var CR=E("ZodNanoID",(X,J)=>{KK.init(X,J),y0.init(X,J)});var ER=E("ZodCUID",(X,J)=>{jK.init(X,J),y0.init(X,J)});var SR=E("ZodCUID2",(X,J)=>{qK.init(X,J),y0.init(X,J)});var IR=E("ZodULID",(X,J)=>{NK.init(X,J),y0.init(X,J)});var bR=E("ZodXID",(X,J)=>{LK.init(X,J),y0.init(X,J)});var kR=E("ZodKSUID",(X,J)=>{DK.init(X,J),y0.init(X,J)});var xR=E("ZodIPv4",(X,J)=>{_K.init(X,J),y0.init(X,J)});var wR=E("ZodIPv6",(X,J)=>{AK.init(X,J),y0.init(X,J)});var vR=E("ZodCIDRv4",(X,J)=>{TK.init(X,J),y0.init(X,J)});var yR=E("ZodCIDRv6",(X,J)=>{RK.init(X,J),y0.init(X,J)});var hR=E("ZodBase64",(X,J)=>{EK.init(X,J),y0.init(X,J)});var fR=E("ZodBase64URL",(X,J)=>{SK.init(X,J),y0.init(X,J)});var gR=E("ZodE164",(X,J)=>{IK.init(X,J),y0.init(X,J)});var mR=E("ZodJWT",(X,J)=>{bK.init(X,J),y0.init(X,J)});var Bq=E("ZodNumber",(X,J)=>{RY.init(X,J),h0.init(X,J),X.gt=(Y,G)=>X.check(qX(Y,G)),X.gte=(Y,G)=>X.check(u3(Y,G)),X.min=(Y,G)=>X.check(u3(Y,G)),X.lt=(Y,G)=>X.check(jX(Y,G)),X.lte=(Y,G)=>X.check(m3(Y,G)),X.max=(Y,G)=>X.check(m3(Y,G)),X.int=(Y)=>X.check(Yq(Y)),X.safe=(Y)=>X.check(Yq(Y)),X.positive=(Y)=>X.check(qX(0,Y)),X.nonnegative=(Y)=>X.check(u3(0,Y)),X.negative=(Y)=>X.check(jX(0,Y)),X.nonpositive=(Y)=>X.check(m3(0,Y)),X.multipleOf=(Y,G)=>X.check(NX(Y,G)),X.step=(Y,G)=>X.check(NX(Y,G)),X.finite=()=>X;let $=X._zod.bag;X.minValue=Math.max($.minimum??Number.NEGATIVE_INFINITY,$.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,X.maxValue=Math.min($.maximum??Number.POSITIVE_INFINITY,$.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,X.isInt=($.format??"").includes("int")||Number.isSafeInteger($.multipleOf??0.5),X.isFinite=!0,X.format=$.format??null});function Hq(X){return Sj(Bq,X)}var uR=E("ZodNumberFormat",(X,J)=>{kK.init(X,J),Bq.init(X,J)});function Yq(X){return Ij(uR,X)}var pR=E("ZodBoolean",(X,J)=>{xK.init(X,J),h0.init(X,J)});function Vq(X){return bj(pR,X)}var cR=E("ZodNull",(X,J)=>{wK.init(X,J),h0.init(X,J)});function Uq(X){return kj(cR,X)}var lR=E("ZodUnknown",(X,J)=>{vK.init(X,J),h0.init(X,J)});function p3(){return xj(lR)}var dR=E("ZodNever",(X,J)=>{yK.init(X,J),h0.init(X,J)});function uY(X){return wj(dR,X)}var iR=E("ZodArray",(X,J)=>{hK.init(X,J),h0.init(X,J),X.element=J.element,X.min=($,Y)=>X.check(F4($,Y)),X.nonempty=($)=>X.check(F4(1,$)),X.max=($,Y)=>X.check(LX($,Y)),X.length=($,Y)=>X.check(DX($,Y)),X.unwrap=()=>X.element});function pY(X,J){return vj(iR,X,J)}var Kq=E("ZodObject",(X,J)=>{mK.init(X,J),h0.init(X,J),j0.defineLazy(X,"shape",()=>J.shape),X.keyof=()=>lY(Object.keys(X._zod.def.shape)),X.catchall=($)=>X.clone({...X._zod.def,catchall:$}),X.passthrough=()=>X.clone({...X._zod.def,catchall:p3()}),X.loose=()=>X.clone({...X._zod.def,catchall:p3()}),X.strict=()=>X.clone({...X._zod.def,catchall:uY()}),X.strip=()=>X.clone({...X._zod.def,catchall:void 0}),X.extend=($)=>{return j0.extend(X,$)},X.safeExtend=($)=>{return j0.safeExtend(X,$)},X.merge=($)=>j0.merge(X,$),X.pick=($)=>j0.pick(X,$),X.omit=($)=>j0.omit(X,$),X.partial=(...$)=>j0.partial(Pq,X,$[0]),X.required=(...$)=>j0.required(Oq,X,$[0])});function jq(X,J){let $={type:"object",get shape(){return j0.assignProp(this,"shape",X?j0.objectClone(X):{}),this.shape},...j0.normalizeParams(J)};return new Kq($)}function qq(X,J){return new Kq({type:"object",get shape(){return j0.assignProp(this,"shape",j0.objectClone(X)),this.shape},catchall:p3(),...j0.normalizeParams(J)})}var Nq=E("ZodUnion",(X,J)=>{CY.init(X,J),h0.init(X,J),X.options=J.options});function cY(X,J){return new Nq({type:"union",options:X,...j0.normalizeParams(J)})}var nR=E("ZodDiscriminatedUnion",(X,J)=>{Nq.init(X,J),uK.init(X,J)});function Lq(X,J,$){return new nR({type:"union",options:J,discriminator:X,...j0.normalizeParams($)})}var sR=E("ZodIntersection",(X,J)=>{pK.init(X,J),h0.init(X,J)});function aR(X,J){return new sR({type:"intersection",left:X,right:J})}var oR=E("ZodRecord",(X,J)=>{cK.init(X,J),h0.init(X,J),X.keyType=J.keyType,X.valueType=J.valueType});function Dq(X,J,$){return new oR({type:"record",keyType:X,valueType:J,...j0.normalizeParams($)})}var mY=E("ZodEnum",(X,J)=>{lK.init(X,J),h0.init(X,J),X.enum=J.entries,X.options=Object.values(J.entries);let $=new Set(Object.keys(J.entries));X.extract=(Y,G)=>{let Q={};for(let z of Y)if($.has(z))Q[z]=J.entries[z];else throw Error(`Key ${z} not found in enum`);return new mY({...J,checks:[],...j0.normalizeParams(G),entries:Q})},X.exclude=(Y,G)=>{let Q={...J.entries};for(let z of Y)if($.has(z))delete Q[z];else throw Error(`Key ${z} not found in enum`);return new mY({...J,checks:[],...j0.normalizeParams(G),entries:Q})}});function lY(X,J){let $=Array.isArray(X)?Object.fromEntries(X.map((Y)=>[Y,Y])):X;return new mY({type:"enum",entries:$,...j0.normalizeParams(J)})}var rR=E("ZodLiteral",(X,J)=>{dK.init(X,J),h0.init(X,J),X.values=new Set(J.values),Object.defineProperty(X,"value",{get(){if(J.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return J.values[0]}})});function Fq(X,J){return new rR({type:"literal",values:Array.isArray(X)?X:[X],...j0.normalizeParams(J)})}var tR=E("ZodTransform",(X,J)=>{iK.init(X,J),h0.init(X,J),X._zod.parse=($,Y)=>{if(Y.direction==="backward")throw new b3(X.constructor.name);$.addIssue=(Q)=>{if(typeof Q==="string")$.issues.push(j0.issue(Q,$.value,J));else{let z=Q;if(z.fatal)z.continue=!1;z.code??(z.code="custom"),z.input??(z.input=$.value),z.inst??(z.inst=X),$.issues.push(j0.issue(z))}};let G=J.transform($.value,$);if(G instanceof Promise)return G.then((Q)=>{return $.value=Q,$});return $.value=G,$}});function eR(X){return new tR({type:"transform",transform:X})}var Pq=E("ZodOptional",(X,J)=>{nK.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function Gq(X){return new Pq({type:"optional",innerType:X})}var XC=E("ZodNullable",(X,J)=>{sK.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function Qq(X){return new XC({type:"nullable",innerType:X})}var JC=E("ZodDefault",(X,J)=>{aK.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType,X.removeDefault=X.unwrap});function $C(X,J){return new JC({type:"default",innerType:X,get defaultValue(){return typeof J==="function"?J():j0.shallowClone(J)}})}var YC=E("ZodPrefault",(X,J)=>{oK.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function GC(X,J){return new YC({type:"prefault",innerType:X,get defaultValue(){return typeof J==="function"?J():j0.shallowClone(J)}})}var Oq=E("ZodNonOptional",(X,J)=>{rK.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function QC(X,J){return new Oq({type:"nonoptional",innerType:X,...j0.normalizeParams(J)})}var zC=E("ZodCatch",(X,J)=>{tK.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType,X.removeCatch=X.unwrap});function ZC(X,J){return new zC({type:"catch",innerType:X,catchValue:typeof J==="function"?J:()=>J})}var WC=E("ZodPipe",(X,J)=>{eK.init(X,J),h0.init(X,J),X.in=J.in,X.out=J.out});function zq(X,J){return new WC({type:"pipe",in:X,out:J})}var BC=E("ZodReadonly",(X,J)=>{Xj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function HC(X){return new BC({type:"readonly",innerType:X})}var VC=E("ZodLazy",(X,J)=>{Jj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.getter()});function Mq(X){return new VC({type:"lazy",getter:X})}var dY=E("ZodCustom",(X,J)=>{$j.init(X,J),h0.init(X,J)});function _q(X,J){return yj(dY,X??(()=>!0),J)}function UC(X,J={}){return hj(dY,X,J)}function KC(X){return fj(X)}function Aq(X,J={error:`Input not instance of ${X.name}`}){let $=new dY({type:"custom",check:"custom",fn:(Y)=>Y instanceof X,abort:!0,...j0.normalizeParams(J)});return $._zod.bag.Class=X,$}function wq(X=globalThis){if(X.navigator?.userAgent)return X.navigator.userAgent.toLowerCase();if(X.process?.versions?.node)return`node.js/${X.process.version}`;if(X.EdgeRuntime)return"vercel-edge";return""}function vq(X){if(X==null)return{};let J={};if(X instanceof Headers)X.forEach(($,Y)=>{J[Y.toLowerCase()]=$});else{if(!Array.isArray(X))X=Object.entries(X);for(let[$,Y]of X)if(Y!=null)J[$.toLowerCase()]=Y}return J}function yq(X,...J){let $=new Headers(vq(X)),Y=$.get("user-agent")||"";return $.set("user-agent",[Y,...J].filter(Boolean).join(" ")),Object.fromEntries($.entries())}var LC=[{mediaType:"audio/aac",bytesPrefix:[255,240]},{mediaType:"audio/aac",bytesPrefix:[255,241]},{mediaType:"audio/aac",bytesPrefix:[255,248]},{mediaType:"audio/aac",bytesPrefix:[255,249]},{mediaType:"audio/mpeg",bytesPrefix:[255,251]},{mediaType:"audio/mpeg",bytesPrefix:[255,250]},{mediaType:"audio/mpeg",bytesPrefix:[255,243]},{mediaType:"audio/mpeg",bytesPrefix:[255,242]},{mediaType:"audio/mpeg",bytesPrefix:[255,227]},{mediaType:"audio/mpeg",bytesPrefix:[255,226]},{mediaType:"audio/wav",bytesPrefix:[82,73,70,70,null,null,null,null,87,65,86,69]},{mediaType:"audio/ogg",bytesPrefix:[79,103,103,83]},{mediaType:"audio/flac",bytesPrefix:[102,76,97,67]},{mediaType:"audio/aac",bytesPrefix:[64,21,0,0]},{mediaType:"audio/webm",bytesPrefix:[26,69,223,163]}],ac=[...LC,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];async function MX(X){try{await X.body?.cancel()}catch{}}var hq="AI_DownloadError",fq=`vercel.ai.error.${hq}`,DC=Symbol.for(fq),q6=class extends Z9{constructor({url:X,statusCode:J,statusText:$,cause:Y,message:G=Y==null?`Failed to download ${X}: ${J} ${$}`:`Failed to download ${X}: ${Y}`}){super({name:hq,message:G,cause:Y});this[DC]=!0,this.url=X,this.statusCode=J,this.statusText=$}static isInstance(X){return Z9.hasMarker(X,fq)}};function FC(X=globalThis){return X.window!=null}function sY(X,J){try{return new URL(X).origin===new URL(J).origin}catch{return!1}}function PC(X){let J;try{J=new URL(X)}catch{throw new q6({url:X,message:`Invalid URL: ${X}`})}if(J.protocol==="data:")return;if(J.protocol!=="http:"&&J.protocol!=="https:")throw new q6({url:X,message:`URL scheme must be http, https, or data, got ${J.protocol}`});let $=J.hostname.toLowerCase().replace(/\.+$/,"");if(!$)throw new q6({url:X,message:"URL must have a hostname"});if($==="localhost"||$.endsWith(".local")||$.endsWith(".localhost"))throw new q6({url:X,message:`URL with hostname ${$} is not allowed`});if($.startsWith("[")&&$.endsWith("]")){if(gq($.slice(1,-1)))throw new q6({url:X,message:`URL with IPv6 address ${$} is not allowed`});return}if(oY($)){if(rY($))throw new q6({url:X,message:`URL with IP address ${$} is not allowed`})}}function OC({address:X,family:J,hostname:$}){if(J===4?!oY(X)||rY(X):J===6?gq(X):!0)throw new q6({url:$,message:`Hostname ${$} resolved to disallowed IP address ${X}`})}function oY(X){let J=X.split(".");if(J.length!==4)return!1;return J.every(($)=>{let Y=Number($);return Number.isInteger(Y)&&Y>=0&&Y<=255&&String(Y)===$})}function rY(X){let[J,$,Y]=X.split(".").map(Number);if(J===0)return!0;if(J===10)return!0;if(J===100&&$>=64&&$<=127)return!0;if(J===127)return!0;if(J===169&&$===254)return!0;if(J===172&&$>=16&&$<=31)return!0;if(J===192&&$===0&&Y===0)return!0;if(J===192&&$===0&&Y===2)return!0;if(J===192&&$===168)return!0;if(J===198&&($===18||$===19))return!0;if(J===198&&$===51&&Y===100)return!0;if(J===203&&$===0&&Y===113)return!0;if(J>=224)return!0;return!1}function MC(X){let J=X.toLowerCase(),$=J.indexOf("%");if($!==-1)J=J.slice(0,$);let Y=J.split("::");if(Y.length>2)return null;let G=(z)=>{if(z==="")return[];let Z=[],W=z.split(":");for(let B=0;B<W.length;B++){let H=W[B];if(H.includes(".")){if(B!==W.length-1||!oY(H))return null;let[U,j,q,K]=H.split(".").map(Number);Z.push(U<<8|j,q<<8|K);continue}if(!/^[0-9a-f]{1,4}$/.test(H))return null;Z.push(parseInt(H,16))}return Z},Q=G(Y[0]);if(Q===null)return null;if(Y.length===2){let z=G(Y[1]);if(z===null)return null;let Z=8-Q.length-z.length;if(Z<0)return null;return[...Q,...Array(Z).fill(0),...z]}return Q.length===8?Q:null}function gq(X){let J=MC(X);if(J===null)return!0;let $=(Y)=>J.slice(0,Y).every((G)=>G===0);if($(7)&&(J[7]===0||J[7]===1))return!0;if((J[0]&65024)===64512)return!0;if((J[0]&65472)===65152)return!0;if((J[0]&65472)===65216)return!0;if((J[0]&65280)===65280)return!0;if(J[0]===8193&&J[1]===3512)return!0;if(J[0]===16383&&(J[1]&61440)===0)return!0;if($(6)||$(5)&&J[5]===65535||$(4)&&J[4]===65535&&J[5]===0||J[0]===100&&J[1]===65435&&J[2]===0&&J[3]===0&&J[4]===0&&J[5]===0||J[0]===100&&J[1]===65435&&J[2]===1)return rY(`${J[6]>>8&255}.${J[6]&255}.${J[7]>>8&255}.${J[7]&255}`);return!1}function _C(X){return(J,$,Y)=>{X(J,{...$,all:!0},(G,Q)=>{if(G){Y(G);return}try{let[z]=Q;if(z==null)throw Error(`Hostname ${J} did not resolve to an address`);for(let{address:Z,family:W}of Q)OC({address:Z,family:W,hostname:J});if($.all===!0)Y(null,Q);else Y(null,z.address,z.family)}catch(z){Y(z instanceof Error?z:Error(String(z)))}})}}var AC;function TC(){let X=globalThis.process;return X?.release?.name==="node"&&X.versions?.bun==null&&X.versions?.deno==null&&X.title!=="workerd"&&globalThis.EdgeRuntime==null}async function RC(){if(!TC())return globalThis.fetch;return AC??=Promise.resolve().then(CC)}function CC(){let X=Tq("node:module"),{lookup:J}=Tq("node:dns"),{Agent:$,fetch:Y}=X.createRequire(mq())("undici"),G=new $({connect:{lookup:_C(J)}});return(Q,z)=>Y(Q,{...z,dispatcher:G})}function Tq(X){let J=globalThis.process?.getBuiltinModule?.(X);if(J==null)throw Error(`Node.js built-in module ${X} is unavailable`);return J}function mq(){let X=Error.prepareStackTrace;try{Error.prepareStackTrace=(G,Q)=>Q;let J=Error("Capture current module path");Error.captureStackTrace(J,mq);let[$]=J.stack,Y=$?.getFileName();if(Y==null)throw Error("Unable to determine the current module path");return Y}finally{Error.prepareStackTrace=X}}var EC=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"];function uq(X){let J=new Headers(X);for(let $ of EC)J.delete($);return J}var SC=10,IC=new Set([301,302,303,307,308]);async function bC(X){return X==null||X===globalThis.fetch?await RC():X}async function kC({url:X,headers:J,abortSignal:$,maxRedirects:Y=SC,fetch:G,trustedOrigin:Q}){let z=J===void 0?void 0:uq(J),Z=(B)=>{let H={signal:$,redirect:B};if(z!==void 0)H.headers=new Headers(z);return H},W=X;for(let B=0;B<=Y;B++){let H=Q!==void 0&&sY(W,Q);if(!H)PC(W);let U=H&&G!=null?G:H?globalThis.fetch:await bC(G),j=await U(W,Z("manual"));if(j.type==="opaqueredirect"){if(!FC())throw new q6({url:X,message:`Redirect from ${W} could not be validated and was blocked`});return await U(W,Z("follow"))}let q=j.headers?.get("location");if(IC.has(j.status)&&q){MX(j);let K=new URL(q,W).toString();if(z!==void 0&&!sY(K,W)){let L=z.get("user-agent");z=new Headers(L==null?void 0:{"user-agent":L})}W=K;continue}return j}throw new q6({url:X,message:`Too many redirects (max ${Y})`})}var xC=new Set(["accept","accept-language","baggage","cache-control","idempotency-key","if-match","if-modified-since","if-none-match","if-range","if-unmodified-since","pragma","range","traceparent","tracestate","user-agent","x-correlation-id","x-request-id"]);async function pq({headers:X,credentialedOrigin:J,untrustedFirstHopHeaders:$,...Y}){let G;if(X!==void 0){G=uq(X);let Q=J??Y.trustedOrigin;if(Q===void 0||!sY(Y.url,Q)){let z=new Set([...xC,...($??[]).map((Z)=>Z.toLowerCase())]);G=new Headers([...G].filter(([Z])=>z.has(Z)))}}return kC({...Y,headers:G})}var tY=2147483648;async function cq({response:X,url:J,maxBytes:$=tY}){let Y=X.headers.get("content-length");if(Y!=null){let H=parseInt(Y,10);if(!isNaN(H)&&H>$)throw await MX(X),new q6({url:J,message:`Download of ${J} exceeded maximum size of ${$} bytes (Content-Length: ${H}).`})}let G=X.body;if(G==null)return new Uint8Array(0);let Q=G.getReader(),z=[],Z=0;try{while(!0){let{done:H,value:U}=await Q.read();if(H)break;if(Z+=U.length,Z>$)throw new q6({url:J,message:`Download of ${J} exceeded maximum size of ${$} bytes.`});z.push(U)}}finally{try{await Q.cancel()}catch{}finally{Q.releaseLock()}}let W=new Uint8Array(Z),B=0;for(let H of z)W.set(H,B),B+=H.length;return W}var X6=({prefix:X,size:J=16,alphabet:$="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Y="-"}={})=>{let G=()=>{let Q=$.length,z=Array(J);for(let Z=0;Z<J;Z++)z[Z]=$[Math.random()*Q|0];return z.join("")};if(X==null)return G;if($.includes(Y))throw new VY({argument:"separator",message:`The separator "${Y}" must not be part of the alphabet "${$}".`});return()=>`${X}${Y}${G()}`},lq=X6();function dq(X){return globalThis.Buffer?.isBuffer(X)??!1}function iq(X){if(X.type==="object"||Array.isArray(X.type)&&X.type.includes("object")){let{additionalProperties:$}=X;X.additionalProperties=$!=null&&typeof $!=="boolean"?y9($):!1;let{properties:Y}=X;if(Y!=null)for(let G of Object.keys(Y))Y[G]=y9(Y[G])}if(X.items!=null)X.items=Array.isArray(X.items)?X.items.map(y9):y9(X.items);if(X.anyOf!=null)X.anyOf=X.anyOf.map(y9);if(X.allOf!=null)X.allOf=X.allOf.map(y9);if(X.oneOf!=null)X.oneOf=X.oneOf.map(y9);let{definitions:J}=X;if(J!=null)for(let $ of Object.keys(J))J[$]=y9(J[$]);return X}function y9(X){if(typeof X==="boolean")return X;return iq(X)}var wC=Symbol("Let zodToJsonSchema decide on which parser to use"),Rq={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},vC=(X)=>typeof X==="string"?{...Rq,name:X}:{...Rq,...X};function l6(){return{}}function yC(X,J){let $={type:"array"};if(X.type?._def&&X.type?._def?.typeName!=="ZodAny")$.items=A0(X.type._def,{...J,currentPath:[...J.currentPath,"items"]});if(X.minLength)$.minItems=X.minLength.value;if(X.maxLength)$.maxItems=X.maxLength.value;if(X.exactLength)$.minItems=X.exactLength.value,$.maxItems=X.exactLength.value;return $}function hC(X){let J={type:"integer",format:"int64"};if(!X.checks)return J;for(let $ of X.checks)switch($.kind){case"min":if($.inclusive)J.minimum=$.value;else J.exclusiveMinimum=$.value;break;case"max":if($.inclusive)J.maximum=$.value;else J.exclusiveMaximum=$.value;break;case"multipleOf":J.multipleOf=$.value}return J}function fC(){return{type:"boolean"}}function nq(X,J){return A0(X.type._def,J)}var gC=(X,J)=>{return A0(X.innerType._def,J)};function sq(X,J,$){let Y=$??J.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((G)=>sq(X,J,G))};switch(Y){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return mC(X)}}var mC=(X)=>{let J={type:"integer",format:"unix-time"};for(let $ of X.checks)switch($.kind){case"min":J.minimum=$.value;break;case"max":J.maximum=$.value}return J};function uC(X,J){return{...A0(X.innerType._def,J),default:X.defaultValue()}}function pC(X,J){return J.effectStrategy==="input"?A0(X.schema._def,J):l6()}function cC(X){return{type:"string",enum:Array.from(X.values)}}var lC=(X)=>{if("type"in X&&X.type==="string")return!1;return"allOf"in X};function dC(X,J){let $=[A0(X.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),A0(X.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((G)=>!!G),Y=[];return $.forEach((G)=>{if(lC(G))Y.push(...G.allOf);else{let Q=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:z,...Z}=G;Q=Z}Y.push(Q)}}),Y.length?{allOf:Y}:void 0}function iC(X){let J=typeof X.value;if(J!=="bigint"&&J!=="number"&&J!=="boolean"&&J!=="string")return{type:Array.isArray(X.value)?"array":"object"};return{type:J==="bigint"?"integer":J,const:X.value}}var iY=void 0,j8={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(iY===void 0)iY=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return iY},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function aq(X,J){let $={type:"string"};if(X.checks)for(let Y of X.checks)switch(Y.kind){case"min":$.minLength=typeof $.minLength==="number"?Math.max($.minLength,Y.value):Y.value;break;case"max":$.maxLength=typeof $.maxLength==="number"?Math.min($.maxLength,Y.value):Y.value;break;case"email":switch(J.emailStrategy){case"format:email":q8($,"email",Y.message,J);break;case"format:idn-email":q8($,"idn-email",Y.message,J);break;case"pattern:zod":C6($,j8.email,Y.message,J)}break;case"url":q8($,"uri",Y.message,J);break;case"uuid":q8($,"uuid",Y.message,J);break;case"regex":C6($,Y.regex,Y.message,J);break;case"cuid":C6($,j8.cuid,Y.message,J);break;case"cuid2":C6($,j8.cuid2,Y.message,J);break;case"startsWith":C6($,RegExp(`^${nY(Y.value,J)}`),Y.message,J);break;case"endsWith":C6($,RegExp(`${nY(Y.value,J)}$`),Y.message,J);break;case"datetime":q8($,"date-time",Y.message,J);break;case"date":q8($,"date",Y.message,J);break;case"time":q8($,"time",Y.message,J);break;case"duration":q8($,"duration",Y.message,J);break;case"length":$.minLength=typeof $.minLength==="number"?Math.max($.minLength,Y.value):Y.value,$.maxLength=typeof $.maxLength==="number"?Math.min($.maxLength,Y.value):Y.value;break;case"includes":C6($,RegExp(nY(Y.value,J)),Y.message,J);break;case"ip":if(Y.version!=="v6")q8($,"ipv4",Y.message,J);if(Y.version!=="v4")q8($,"ipv6",Y.message,J);break;case"base64url":C6($,j8.base64url,Y.message,J);break;case"jwt":C6($,j8.jwt,Y.message,J);break;case"cidr":if(Y.version!=="v6")C6($,j8.ipv4Cidr,Y.message,J);if(Y.version!=="v4")C6($,j8.ipv6Cidr,Y.message,J);break;case"emoji":C6($,j8.emoji(),Y.message,J);break;case"ulid":C6($,j8.ulid,Y.message,J);break;case"base64":switch(J.base64Strategy){case"format:binary":q8($,"binary",Y.message,J);break;case"contentEncoding:base64":$.contentEncoding="base64";break;case"pattern:zod":C6($,j8.base64,Y.message,J)}break;case"nanoid":C6($,j8.nanoid,Y.message,J)}return $}function nY(X,J){return J.patternStrategy==="escape"?sC(X):X}var nC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function sC(X){let J="";for(let $=0;$<X.length;$++){if(!nC.has(X[$]))J+="\\";J+=X[$]}return J}function q8(X,J,$,Y){if(X.format||X.anyOf?.some((G)=>G.format)){if(!X.anyOf)X.anyOf=[];if(X.format)X.anyOf.push({format:X.format}),delete X.format;X.anyOf.push({format:J,...$&&Y.errorMessages&&{errorMessage:{format:$}}})}else X.format=J}function C6(X,J,$,Y){if(X.pattern||X.allOf?.some((G)=>G.pattern)){if(!X.allOf)X.allOf=[];if(X.pattern)X.allOf.push({pattern:X.pattern}),delete X.pattern;X.allOf.push({pattern:Cq(J,Y),...$&&Y.errorMessages&&{errorMessage:{pattern:$}}})}else X.pattern=Cq(J,Y)}function Cq(X,J){if(!J.applyRegexFlags||!X.flags)return X.source;let $={i:X.flags.includes("i"),m:X.flags.includes("m"),s:X.flags.includes("s")},Y=$.i?X.source.toLowerCase():X.source,G="",Q=!1,z=!1,Z=!1;for(let W=0;W<Y.length;W++){if(Q){G+=Y[W],Q=!1;continue}if($.i){if(z){if(Y[W].match(/[a-z]/)){if(Z)G+=Y[W],G+=`${Y[W-2]}-${Y[W]}`.toUpperCase(),Z=!1;else if(Y[W+1]==="-"&&Y[W+2]?.match(/[a-z]/))G+=Y[W],Z=!0;else G+=`${Y[W]}${Y[W].toUpperCase()}`;continue}}else if(Y[W].match(/[a-z]/)){G+=`[${Y[W]}${Y[W].toUpperCase()}]`;continue}}if($.m){if(Y[W]==="^"){G+=`(^|(?<=[\r
188
- ]))`;continue}else if(Y[W]==="$"){G+=`($|(?=[\r
189
- ]))`;continue}}if($.s&&Y[W]==="."){G+=z?`${Y[W]}\r
190
- `:`[${Y[W]}\r
191
- ]`;continue}if(G+=Y[W],Y[W]==="\\")Q=!0;else if(z&&Y[W]==="]")z=!1;else if(!z&&Y[W]==="[")z=!0}try{new RegExp(G)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),X.source}return G}function oq(X,J){let $={type:"object",additionalProperties:A0(X.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(X.keyType?._def.typeName==="ZodString"&&X.keyType._def.checks?.length){let{type:Y,...G}=aq(X.keyType._def,J);return{...$,propertyNames:G}}else if(X.keyType?._def.typeName==="ZodEnum")return{...$,propertyNames:{enum:X.keyType._def.values}};else if(X.keyType?._def.typeName==="ZodBranded"&&X.keyType._def.type._def.typeName==="ZodString"&&X.keyType._def.type._def.checks?.length){let{type:Y,...G}=nq(X.keyType._def,J);return{...$,propertyNames:G}}return $}function aC(X,J){if(J.mapStrategy==="record")return oq(X,J);return{type:"array",maxItems:125,items:{type:"array",items:[A0(X.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||l6(),A0(X.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||l6()],minItems:2,maxItems:2}}}function oC(X){let J=X.values,$=Object.keys(X.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),Y=Array.from(new Set($.map((G)=>typeof G)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:$}}function rC(){return{not:l6()}}function tC(){return{type:"null"}}var aY={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function eC(X,J){let $=X.options instanceof Map?Array.from(X.options.values()):X.options;if($.every((Y)=>(Y._def.typeName in aY)&&(!Y._def.checks||!Y._def.checks.length))){let Y=$.reduce((G,Q)=>{let z=aY[Q._def.typeName];return z&&!G.includes(z)?[...G,z]:G},[]);return{type:Y.length>1?Y:Y[0]}}else if($.every((Y)=>Y._def.typeName==="ZodLiteral"&&!Y.description)){let Y=$.reduce((G,Q)=>{let z=typeof Q._def.value;switch(z){case"string":case"number":case"boolean":return[...G,z];case"bigint":return[...G,"integer"];case"object":if(Q._def.value===null)return[...G,"null"];default:return G}},[]);if(Y.length===$.length){let G=Y.filter((Q,z,Z)=>Z.indexOf(Q)===z);return{type:G.length>1?G:G[0],enum:$.reduce((Q,z)=>{return Q.includes(z._def.value)?Q:[...Q,z._def.value]},[])}}}else if($.every((Y)=>Y._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((Y,G)=>[...Y,...G._def.values.filter((Q)=>!Y.includes(Q))],[])};return XE(X,J)}var XE=(X,J)=>{let $=(X.options instanceof Map?Array.from(X.options.values()):X.options).map((Y,G)=>A0(Y._def,{...J,currentPath:[...J.currentPath,"anyOf",`${G}`]})).filter((Y)=>!!Y&&(!J.strictUnions||typeof Y==="object"&&Object.keys(Y).length>0));return $.length?{anyOf:$}:void 0};function JE(X,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(X.innerType._def.typeName)&&(!X.innerType._def.checks||!X.innerType._def.checks.length))return{type:[aY[X.innerType._def.typeName],"null"]};let $=A0(X.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function $E(X){let J={type:"number"};if(!X.checks)return J;for(let $ of X.checks)switch($.kind){case"int":J.type="integer";break;case"min":if($.inclusive)J.minimum=$.value;else J.exclusiveMinimum=$.value;break;case"max":if($.inclusive)J.maximum=$.value;else J.exclusiveMaximum=$.value;break;case"multipleOf":J.multipleOf=$.value}return J}function YE(X,J){let $={type:"object",properties:{}},Y=[],G=X.shape();for(let z in G){let Z=G[z];if(Z===void 0||Z._def===void 0)continue;let W=QE(Z),B=A0(Z._def,{...J,currentPath:[...J.currentPath,"properties",z],propertyPath:[...J.currentPath,"properties",z]});if(B===void 0)continue;if($.properties[z]=B,!W)Y.push(z)}if(Y.length)$.required=Y;let Q=GE(X,J);if(Q!==void 0)$.additionalProperties=Q;return $}function GE(X,J){if(X.catchall._def.typeName!=="ZodNever")return A0(X.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch(X.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function QE(X){try{return X.isOptional()}catch{return!0}}var zE=(X,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return A0(X.innerType._def,J);let $=A0(X.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return $?{anyOf:[{not:l6()},$]}:l6()},ZE=(X,J)=>{if(J.pipeStrategy==="input")return A0(X.in._def,J);else if(J.pipeStrategy==="output")return A0(X.out._def,J);let $=A0(X.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]});return{allOf:[$,A0(X.out._def,{...J,currentPath:[...J.currentPath,"allOf",$?"1":"0"]})].filter((Y)=>Y!==void 0)}};function WE(X,J){return A0(X.type._def,J)}function BE(X,J){let $={type:"array",uniqueItems:!0,items:A0(X.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if(X.minSize)$.minItems=X.minSize.value;if(X.maxSize)$.maxItems=X.maxSize.value;return $}function HE(X,J){if(X.rest)return{type:"array",minItems:X.items.length,items:X.items.map(($,Y)=>A0($._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce(($,Y)=>Y===void 0?$:[...$,Y],[]),additionalItems:A0(X.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:X.items.length,maxItems:X.items.length,items:X.items.map(($,Y)=>A0($._def,{...J,currentPath:[...J.currentPath,"items",`${Y}`]})).reduce(($,Y)=>Y===void 0?$:[...$,Y],[])}}function VE(){return{not:l6()}}function UE(){return l6()}var KE=(X,J)=>{return A0(X.innerType._def,J)},jE=(X,J,$)=>{switch(J){case"ZodString":return aq(X,$);case"ZodNumber":return $E(X);case"ZodObject":return YE(X,$);case"ZodBigInt":return hC(X);case"ZodBoolean":return fC();case"ZodDate":return sq(X,$);case"ZodUndefined":return VE();case"ZodNull":return tC();case"ZodArray":return yC(X,$);case"ZodUnion":case"ZodDiscriminatedUnion":return eC(X,$);case"ZodIntersection":return dC(X,$);case"ZodTuple":return HE(X,$);case"ZodRecord":return oq(X,$);case"ZodLiteral":return iC(X);case"ZodEnum":return cC(X);case"ZodNativeEnum":return oC(X);case"ZodNullable":return JE(X,$);case"ZodOptional":return zE(X,$);case"ZodMap":return aC(X,$);case"ZodSet":return BE(X,$);case"ZodLazy":return()=>X.getter()._def;case"ZodPromise":return WE(X,$);case"ZodNaN":case"ZodNever":return rC();case"ZodEffects":return pC(X,$);case"ZodAny":return l6();case"ZodUnknown":return UE();case"ZodDefault":return uC(X,$);case"ZodBranded":return nq(X,$);case"ZodReadonly":return KE(X,$);case"ZodCatch":return gC(X,$);case"ZodPipeline":return ZE(X,$);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Y)=>{return})(J)}},qE=(X,J)=>{let $=0;for(;$<X.length&&$<J.length;$++)if(X[$]!==J[$])break;return[(X.length-$).toString(),...J.slice($)].join("/")};function A0(X,J,$=!1){let Y=J.seen.get(X);if(J.override){let Z=J.override?.(X,J,Y,$);if(Z!==wC)return Z}if(Y&&!$){let Z=NE(Y,J);if(Z!==void 0)return Z}let G={def:X,path:J.currentPath,jsonSchema:void 0};J.seen.set(X,G);let Q=jE(X,X.typeName,J),z=typeof Q==="function"?A0(Q(),J):Q;if(z)LE(X,J,z);if(J.postProcess){let Z=J.postProcess(z,X,J);return G.jsonSchema=z,Z}return G.jsonSchema=z,z}var NE=(X,J)=>{switch(J.$refStrategy){case"root":return{$ref:X.path.join("/")};case"relative":return{$ref:qE(J.currentPath,X.path)};case"none":case"seen":if(X.path.length<J.currentPath.length&&X.path.every(($,Y)=>J.currentPath[Y]===$))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),l6();return J.$refStrategy==="seen"?l6():void 0}},LE=(X,J,$)=>{if(X.description)$.description=X.description;return $},DE=(X)=>{let J=vC(X),$=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([Y,G])=>[G._def,{def:G._def,path:[...J.basePath,J.definitionPath,Y],jsonSchema:void 0}]))}},FE=(X,J)=>{let $=DE(J),Y=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((W,[B,H])=>({...W,[B]:A0(H._def,{...$,currentPath:[...$.basePath,$.definitionPath,B]},!0)??l6()}),{}):void 0,G=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,Q=A0(X._def,G===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,G]},!1)??l6(),z=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(z!==void 0)Q.title=z;let Z=G===void 0?Y?{...Q,[$.definitionPath]:Y}:Q:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,G].join("/"),[$.definitionPath]:{...Y,[G]:Q}};return Z.$schema="http://json-schema.org/draft-07/schema#",Z},PE=Symbol.for("vercel.ai.schema");function eY(X){let J;return()=>{if(J==null)J=X();return J}}function _X(X,{validate:J}={}){return{[PE]:!0,_type:void 0,get jsonSchema(){if(typeof X==="function")X=X();return X},validate:J}}function OE(X,J){let $=J?.useReferences??!1;return _X(()=>FE(X,{$refStrategy:$?"root":"none"}),{validate:async(Y)=>{let G=await X.safeParseAsync(Y);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function ME(X,J){let $=J?.useReferences??!1;return _X(()=>iq(gj(X,{target:"draft-7",io:"input",reused:$?"ref":"inline"})),{validate:async(Y)=>{let G=await PX(X,Y);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function _E(X){return"_zod"in X}function AX(X,J){if(_E(X))return ME(X,J);else return OE(X,J)}var AE="AI_SerializationError",oc=`vercel.ai.error.${AE}`;var bE="AI_InvalidArgumentError",bl=`vercel.ai.error.${bE}`;var kE="AI_InvalidStreamPartError",kl=`vercel.ai.error.${kE}`;var xE="AI_InvalidToolApprovalError",xl=`vercel.ai.error.${xE}`;var wE="AI_InvalidToolApprovalSignatureError",wl=`vercel.ai.error.${wE}`;var vE="AI_InvalidToolInputError",vl=`vercel.ai.error.${vE}`;var yE="AI_ToolCallNotFoundForApprovalError",yl=`vercel.ai.error.${yE}`;var hE="AI_MissingToolResultsError",hl=`vercel.ai.error.${hE}`;var fE="AI_NoImageGeneratedError",fl=`vercel.ai.error.${fE}`;var gE="AI_NoObjectGeneratedError",gl=`vercel.ai.error.${gE}`;var mE="AI_NoOutputGeneratedError",ml=`vercel.ai.error.${mE}`;var uE="AI_NoSpeechGeneratedError",ul=`vercel.ai.error.${uE}`;var pE="AI_NoTranscriptGeneratedError",pl=`vercel.ai.error.${pE}`;var cE="AI_NoTranslationGeneratedError",cl=`vercel.ai.error.${cE}`;var lE="AI_NoVideoGeneratedError",ll=`vercel.ai.error.${lE}`;var dE="AI_NoSuchToolError",dl=`vercel.ai.error.${dE}`;var iE="AI_StreamProviderError",il=`vercel.ai.error.${iE}`;var nE="AI_ToolCallRepairError",nl=`vercel.ai.error.${nE}`;var sE="AI_ToolChoiceViolationError",sl=`vercel.ai.error.${sE}`;var aE="AI_UIMessageStreamError",al=`vercel.ai.error.${aE}`;var oE="AI_InvalidDataContentError",ol=`vercel.ai.error.${oE}`;var rE="AI_InvalidMessageRoleError",rl=`vercel.ai.error.${rE}`;var tE="AI_MessageConversionError",tl=`vercel.ai.error.${tE}`;var eE="AI_RetryError",el=`vercel.ai.error.${eE}`;var XS="7.0.127",JS=async({url:X,maxBytes:J,abortSignal:$})=>{let Y=X.toString();try{let G=yq({},`ai-sdk/${XS}`,wq()),Q=await pq({url:Y,headers:G,abortSignal:$});if(!Q.ok)throw await MX(Q),new q6({url:Y,statusCode:Q.status,statusText:Q.statusText});return{data:await cq({response:Q,url:Y,maxBytes:J??tY}),mediaType:Q.headers.get("content-type")??void 0}}catch(G){if(q6.isInstance(G))throw G;throw new q6({url:Y,cause:G})}};var V={array:pY,boolean:Vq,custom:_q,discriminatedUnion:Lq,enum:lY,instanceof:Aq,lazy:Mq,literal:Fq,looseObject:qq,never:uY,null:Uq,number:Hq,object:jq,record:Dq,string:Wq,union:cY,unknown:p3},A1=V.lazy(()=>V.union([V.null(),V.string(),V.number(),V.boolean(),V.record(V.string(),A1.optional()),V.array(A1)])),g=V.record(V.string(),V.record(V.string(),A1.optional())),l3=V.union([V.string(),V.instanceof(Uint8Array),V.instanceof(ArrayBuffer),V.custom(dq,{message:"Must be a Buffer"})]),XG=V.record(V.string(),V.string()),rq=V.object({type:V.literal("text"),text:V.string(),providerOptions:g.optional()}),$S=V.object({type:V.literal("image"),image:V.union([l3,V.instanceof(URL),XG]),mediaType:V.string().optional(),providerOptions:g.optional()}),tq=V.discriminatedUnion("type",[V.object({type:V.literal("data"),data:l3}),V.object({type:V.literal("url"),url:V.instanceof(URL)}),V.object({type:V.literal("reference"),reference:XG}),V.object({type:V.literal("text"),text:V.string()})]),YS=V.discriminatedUnion("type",[V.object({type:V.literal("data"),data:l3}),V.object({type:V.literal("url"),url:V.instanceof(URL)})]),eq=V.object({type:V.literal("file"),data:V.union([tq,l3,V.instanceof(URL),XG]),filename:V.string().optional(),mediaType:V.string(),providerOptions:g.optional()}),GS=V.object({type:V.literal("reasoning"),text:V.string(),providerOptions:g.optional()}),QS=V.object({type:V.literal("custom"),kind:V.string().transform((X)=>X),providerOptions:g.optional()}),zS=V.object({type:V.literal("reasoning-file"),data:V.union([YS,l3,V.instanceof(URL)]),mediaType:V.string(),providerOptions:g.optional()}),ZS=V.object({type:V.literal("tool-call"),toolCallId:V.string(),toolName:V.string(),input:V.unknown(),providerOptions:g.optional(),providerExecuted:V.boolean().optional()}),WS=V.discriminatedUnion("type",[V.object({type:V.literal("text"),value:V.string(),providerOptions:g.optional()}),V.object({type:V.literal("json"),value:A1,providerOptions:g.optional()}),V.object({type:V.literal("execution-denied"),reason:V.string().optional(),providerOptions:g.optional()}),V.object({type:V.literal("error-text"),value:V.string(),providerOptions:g.optional()}),V.object({type:V.literal("error-json"),value:A1,providerOptions:g.optional()}),V.object({type:V.literal("content"),value:V.array(V.union([V.object({type:V.literal("text"),text:V.string(),providerOptions:g.optional()}),V.object({type:V.literal("file"),data:tq,mediaType:V.string(),filename:V.string().optional(),providerOptions:g.optional()}),V.object({type:V.literal("file-data"),data:V.string(),mediaType:V.string(),filename:V.string().optional(),providerOptions:g.optional()}),V.object({type:V.literal("file-url"),url:V.string(),mediaType:V.string().optional(),providerOptions:g.optional()}),V.object({type:V.literal("file-id"),fileId:V.union([V.string(),V.record(V.string(),V.string())]),providerOptions:g.optional()}),V.object({type:V.literal("file-reference"),providerReference:V.record(V.string(),V.string()),providerOptions:g.optional()}),V.object({type:V.literal("image-data"),data:V.string(),mediaType:V.string(),providerOptions:g.optional()}),V.object({type:V.literal("image-url"),url:V.string(),providerOptions:g.optional()}),V.object({type:V.literal("image-file-id"),fileId:V.union([V.string(),V.record(V.string(),V.string())]),providerOptions:g.optional()}),V.object({type:V.literal("image-file-reference"),providerReference:V.record(V.string(),V.string()),providerOptions:g.optional()}),V.object({type:V.literal("custom"),providerOptions:g.optional()})]))})]),XN=V.object({type:V.literal("tool-result"),toolCallId:V.string(),toolName:V.string(),output:WS,providerOptions:g.optional()}),BS=V.object({type:V.literal("tool-approval-request"),approvalId:V.string(),toolCallId:V.string(),reason:V.string().optional(),isAutomatic:V.boolean().optional(),signature:V.string().optional(),inputSchemaInput:V.unknown().optional()}),HS=V.object({type:V.literal("tool-approval-response"),approvalId:V.string(),approved:V.boolean(),reason:V.string().optional()}),VS=V.object({role:V.literal("system"),content:V.string(),providerOptions:g.optional()}),US=V.object({role:V.literal("user"),content:V.union([V.string(),V.array(V.union([rq,$S,eq]))]),providerOptions:g.optional()}),KS=V.object({role:V.literal("assistant"),content:V.union([V.string(),V.array(V.union([rq,QS,eq,GS,zS,ZS,XN,BS]))]),providerOptions:g.optional()}),jS=V.object({role:V.literal("tool"),content:V.array(V.union([XN,HS])),providerOptions:g.optional()}),Xd=V.union([VS,US,KS,jS]);var Jd=Symbol("ai-sdk-tool-call-input-schema-input");var $d=X6({prefix:"aitxt",size:24}),Yd=X6({prefix:"call",size:24});var Gd=class extends TransformStream{constructor(){super({transform(X,J){J.enqueue(`data: ${JSON.stringify(X)}
192
-
193
- `)},flush(X){X.enqueue(`data: [DONE]
194
-
195
- `)}})}};var c3=V.record(V.string(),A1.optional()),Qd=eY(()=>AX(V.union([V.looseObject({type:V.literal("text-start"),id:V.string(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("text-delta"),id:V.string(),delta:V.string(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("text-end"),id:V.string(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("error"),errorText:V.string()}),V.looseObject({type:V.literal("tool-input-start"),toolCallId:V.string(),toolName:V.string(),providerExecuted:V.boolean().optional(),providerMetadata:g.optional(),toolMetadata:c3.optional(),dynamic:V.boolean().optional(),title:V.string().optional()}),V.looseObject({type:V.literal("tool-input-delta"),toolCallId:V.string(),inputTextDelta:V.string()}),V.looseObject({type:V.literal("tool-input-available"),toolCallId:V.string(),toolName:V.string(),input:V.unknown(),providerExecuted:V.boolean().optional(),providerMetadata:g.optional(),toolMetadata:c3.optional(),dynamic:V.boolean().optional(),title:V.string().optional()}),V.looseObject({type:V.literal("tool-input-error"),toolCallId:V.string(),toolName:V.string(),input:V.unknown(),providerExecuted:V.boolean().optional(),providerMetadata:g.optional(),toolMetadata:c3.optional(),dynamic:V.boolean().optional(),errorText:V.string(),title:V.string().optional()}),V.looseObject({type:V.literal("tool-approval-request"),approvalId:V.string(),toolCallId:V.string(),approvalDescriptor:V.unknown().optional(),inputSchemaInput:V.unknown().optional(),reason:V.string().optional(),isAutomatic:V.boolean().optional(),signature:V.string().optional()}),V.looseObject({type:V.literal("tool-approval-response"),approvalId:V.string(),approved:V.boolean(),reason:V.string().optional(),providerExecuted:V.boolean().optional(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("tool-output-available"),toolCallId:V.string(),output:V.unknown(),providerExecuted:V.boolean().optional(),providerMetadata:g.optional(),toolMetadata:c3.optional(),dynamic:V.boolean().optional(),preliminary:V.boolean().optional()}),V.looseObject({type:V.literal("tool-output-error"),toolCallId:V.string(),errorText:V.string(),providerExecuted:V.boolean().optional(),providerMetadata:g.optional(),toolMetadata:c3.optional(),dynamic:V.boolean().optional()}),V.looseObject({type:V.literal("tool-output-denied"),toolCallId:V.string()}),V.looseObject({type:V.literal("reasoning-start"),id:V.string(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("reasoning-delta"),id:V.string(),delta:V.string(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("reasoning-end"),id:V.string(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("custom"),kind:V.string().transform((X)=>X),providerMetadata:g.optional()}),V.looseObject({type:V.literal("source-url"),sourceId:V.string(),url:V.string(),title:V.string().optional(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("source-document"),sourceId:V.string(),mediaType:V.string(),title:V.string(),filename:V.string().optional(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("file"),url:V.string(),mediaType:V.string(),providerMetadata:g.optional()}),V.looseObject({type:V.literal("reasoning-file"),url:V.string(),mediaType:V.string(),providerMetadata:g.optional()}),V.looseObject({type:V.custom((X)=>typeof X==="string"&&X.startsWith("data-"),{message:'Type must start with "data-"'}),id:V.string().optional(),data:V.unknown(),transient:V.boolean().optional()}),V.looseObject({type:V.literal("start-step")}),V.looseObject({type:V.literal("finish-step")}),V.looseObject({type:V.literal("reset-step")}),V.looseObject({type:V.literal("start"),messageId:V.string().optional(),messageMetadata:V.unknown().optional()}),V.looseObject({type:V.literal("finish"),finishReason:V.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:V.unknown().optional()}),V.looseObject({type:V.literal("abort"),reason:V.string().optional()}),V.looseObject({type:V.literal("message-metadata"),messageMetadata:V.unknown()})])));var zd=Symbol("streamRetryAttemptBoundary");var Zd=X6({prefix:"aitxt",size:24}),Wd=X6({prefix:"call",size:24});var Bd=X6({prefix:"aitxt",size:24}),Hd=X6({prefix:"call",size:24});var Vd=Symbol("streamRetryBoundary");var x6=V.record(V.string(),A1.optional()),qS=V.record(V.string(),V.string());var Ud=eY(()=>{let X=V.object({id:V.string(),approved:V.never().optional(),descriptor:V.unknown().optional(),requestReason:V.string().optional(),reason:V.never().optional(),isAutomatic:V.boolean().optional(),signature:V.string().optional(),inputSchemaInput:V.unknown().optional()}),J=X.extend({approved:V.boolean(),reason:V.string().optional()}),$=J.extend({approved:V.literal(!0)}),Y=J.extend({approved:V.literal(!1)});return AX(V.array(V.object({id:V.string(),role:V.enum(["system","user","assistant"]),metadata:V.unknown().optional(),parts:V.array(V.union([V.object({type:V.literal("text"),text:V.string(),state:V.enum(["streaming","done"]).optional(),providerMetadata:g.optional()}),V.object({type:V.literal("reasoning"),id:V.string().optional(),text:V.string(),state:V.enum(["streaming","done"]).optional(),providerMetadata:g.optional()}),V.object({type:V.literal("custom"),kind:V.string(),providerMetadata:g.optional()}),V.object({type:V.literal("source-url"),sourceId:V.string(),url:V.string(),title:V.string().optional(),providerMetadata:g.optional()}),V.object({type:V.literal("source-document"),sourceId:V.string(),mediaType:V.string(),title:V.string(),filename:V.string().optional(),providerMetadata:g.optional()}),V.object({type:V.literal("file"),mediaType:V.string(),filename:V.string().optional(),url:V.string(),providerReference:qS.optional(),providerMetadata:g.optional()}),V.object({type:V.literal("reasoning-file"),mediaType:V.string(),url:V.string(),providerMetadata:g.optional()}),V.object({type:V.literal("step-start")}),V.object({type:V.string().startsWith("data-"),id:V.string().optional(),data:V.unknown()}),V.object({type:V.literal("dynamic-tool"),toolName:V.string(),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("input-streaming"),input:V.unknown().optional(),rawInput:V.string().optional(),providerExecuted:V.boolean().optional(),callProviderMetadata:g.optional(),output:V.never().optional(),errorText:V.never().optional(),approval:V.never().optional()}),V.object({type:V.literal("dynamic-tool"),toolName:V.string(),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("input-available"),input:V.unknown(),providerExecuted:V.boolean().optional(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:g.optional(),approval:V.never().optional()}),V.object({type:V.literal("dynamic-tool"),toolName:V.string(),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("approval-requested"),input:V.unknown(),providerExecuted:V.boolean().optional(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:g.optional(),approval:X}),V.object({type:V.literal("dynamic-tool"),toolName:V.string(),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("approval-responded"),input:V.unknown(),providerExecuted:V.boolean().optional(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:g.optional(),approval:J}),V.object({type:V.literal("dynamic-tool"),toolName:V.string(),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("output-available"),input:V.unknown(),providerExecuted:V.boolean().optional(),output:V.unknown(),errorText:V.never().optional(),callProviderMetadata:g.optional(),resultProviderMetadata:g.optional(),preliminary:V.boolean().optional(),approval:$.optional()}),V.object({type:V.literal("dynamic-tool"),toolName:V.string(),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("output-error"),input:V.unknown().optional(),rawInput:V.unknown().optional(),providerExecuted:V.boolean().optional(),output:V.never().optional(),errorText:V.string(),callProviderMetadata:g.optional(),resultProviderMetadata:g.optional(),approval:$.optional()}),V.object({type:V.literal("dynamic-tool"),toolName:V.string(),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("output-denied"),input:V.unknown(),providerExecuted:V.boolean().optional(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:g.optional(),approval:Y}),V.object({type:V.string().startsWith("tool-"),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("input-streaming"),providerExecuted:V.boolean().optional(),callProviderMetadata:g.optional(),input:V.unknown().optional(),rawInput:V.string().optional(),output:V.never().optional(),errorText:V.never().optional(),approval:V.never().optional()}),V.object({type:V.string().startsWith("tool-"),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("input-available"),providerExecuted:V.boolean().optional(),input:V.unknown(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:g.optional(),approval:V.never().optional()}),V.object({type:V.string().startsWith("tool-"),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("approval-requested"),input:V.unknown(),providerExecuted:V.boolean().optional(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:g.optional(),approval:X}),V.object({type:V.string().startsWith("tool-"),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("approval-responded"),input:V.unknown(),providerExecuted:V.boolean().optional(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:g.optional(),approval:J}),V.object({type:V.string().startsWith("tool-"),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("output-available"),providerExecuted:V.boolean().optional(),input:V.unknown(),output:V.unknown(),errorText:V.never().optional(),callProviderMetadata:g.optional(),resultProviderMetadata:g.optional(),preliminary:V.boolean().optional(),approval:$.optional()}),V.object({type:V.string().startsWith("tool-"),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("output-error"),providerExecuted:V.boolean().optional(),input:V.unknown().optional(),rawInput:V.unknown().optional(),output:V.never().optional(),errorText:V.string(),callProviderMetadata:g.optional(),resultProviderMetadata:g.optional(),approval:$.optional()}),V.object({type:V.string().startsWith("tool-"),toolCallId:V.string(),title:V.string().optional(),toolMetadata:x6.optional(),state:V.literal("output-denied"),providerExecuted:V.boolean().optional(),input:V.unknown(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:g.optional(),approval:Y})]))}).superRefine((G,Q)=>{if(G.role!=="assistant"&&G.parts.length===0)Q.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:G.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty"))});var Kd=X6({prefix:"call",size:24});var jd=X6({prefix:"call",size:24});var qd=X6({prefix:"call",size:24});var Nd=X6({prefix:"aiobj",size:24});function JN(X){return({url:J,abortSignal:$})=>JS({url:J,maxBytes:X?.maxBytes,abortSignal:$})}var Ld=X6({prefix:"aiobj",size:24});var Dd=X6({prefix:"call",size:24});var Fd=JN();var Pd=V.object({token:V.string().refine((X)=>X.trim().length>0),url:V.string().refine((X)=>{try{let J=new URL(X);return(J.protocol==="ws:"||J.protocol==="wss:")&&J.hostname!==""}catch{return!1}}),expiresAt:V.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),tools:V.array(V.object({type:V.literal("function"),name:V.string().min(1),description:V.string().optional(),parameters:V.record(V.string(),V.unknown())})).optional()});var NS="AI_NoSuchProviderError",Od=`vercel.ai.error.${NS}`;var Md=X6({prefix:"call",size:24});var _d=X6({prefix:"call",size:24}),Ad=JN();var Td=X6({prefix:"call",size:24});class w6 extends P1{name="ProviderResponseStreamError";constructor(X,J){super({message:X,url:"",requestBodyValues:void 0,cause:J?.cause,isRetryable:J?.retryable??!0})}}var N6={};KY(N6,{toWebSocketUrl:()=>wS,streamResponsesWebSocket:()=>gS,parseRateLimitSignal:()=>i3,normalizeHeaders:()=>vS,markOversizedFrame:()=>UN,isUpgradeFailure:()=>yS,isOversizedFrame:()=>hS,isNonEmittingFrame:()=>jN,isAbortError:()=>QG,connectResponsesWebSocket:()=>fS,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>GG,PROTOCOL_HEADER:()=>BN,OpenAIWebSocket:()=>N6,OVERSIZED_FRAME_MESSAGE:()=>qN});function d3(X){let J=Number(X.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(J)?J:void 0}function TX(X,J,$=!1){let G=Buffer.from(X.slice(0,J)).toString("latin1").split(`\r
196
- `),Q=G[0]??"",z=d3(Q);if(z===void 0||z===101)return;let Z=Object.fromEntries(G.slice(1).flatMap((q)=>{let K=q.indexOf(":");return K===-1?[]:[[q.slice(0,K).trim().toLowerCase(),q.slice(K+1).trim()]]})),W=X.slice(J+4),B=Z["content-length"],H=Number(B);if(!$&&(B===void 0||Number.isFinite(H)&&W.length<H))return;let U=Buffer.from(W).toString("utf8"),j=(()=>{try{let q=JSON.parse(U);return s(q)?q:void 0}catch{return}})();return{message:`WS upgrade failed: ${Q}`,status:z,status_code:z,headers:Z,body:U,...s(j?.error)?{error:j.error}:{}}}var LS="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",$N=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class JG{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(X,J,$){this.url=X,this.sessionID=$?.sessionID,this.connect(X,J)}addEventListener(X,J,$){this.listeners[X]?.add(J)}removeEventListener(X,J){this.listeners[X]?.delete(J)}peerClose;closeEmitted=!1;emitClose(X,J){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:X,reason:J})}emit(X,J){for(let $ of[...this.listeners[X]??[]])try{$(J)}catch{}}async connect(X,J){let $=new URL(X.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Y=$.hostname,G=$.port?Number($.port):$.protocol==="https:"?443:80,Q=`${$.pathname}${$.search}`,z=crypto.getRandomValues(new Uint8Array(16)),Z=Buffer.from(z).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Z+LS));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[j,q]of Object.entries(J))B[j.toLowerCase()]=q;let H=[`GET ${Q} HTTP/1.1`,`Host: ${Y}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Z}`];for(let j of $N)if(B[j]!==void 0)H.push(`${DS(j)}: ${B[j]}`);for(let[j,q]of Object.entries(J))if(!$N.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")H.push(`${j}: ${q}`);let U=`${H.join(`\r
197
- `)}\r
198
- \r
199
- `;try{this.log("connect_start",{host:Y,port:G,tls:$.protocol==="https:"});let j=globalThis.Bun?.connect;if(!j)throw Error("Bun.connect is not available");this.socket=await j({hostname:Y,port:G,tls:$.protocol==="https:"?{serverName:Y}:void 0,socket:{open:(q)=>{this.socket=q,this.enqueueWrite(new TextEncoder().encode(U))},data:(q,K)=>this.onData(K),drain:()=>this.flushWrites(),error:(q,K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let L=K instanceof Error?K.message:String(K);this.log("socket_error",{message:L}),this.emit("error",{message:L})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")}}})}catch(j){this.readyState=3;let q=j instanceof Error?j.message:String(j);this.log("connect_exception",{message:q}),this.emit("error",{message:q})}}onData(X){if(this.rxBuffer=FS(this.rxBuffer,X),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),$=J.indexOf(`\r
200
- \r
201
- `);if($===-1)return;let Y=J.slice(0,$),G=Y.split(`\r
202
- `)[0]??"",Q=Y.match(/sec-websocket-accept:\s*(\S+)/i),z=d3(G);if(z!==101){if(z===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!Q||Q[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:G}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice($+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(X=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let J=Buffer.from(this.rxBuffer).indexOf(`\r
203
- \r
204
- `);if(J===-1)return!1;let $=TX(this.rxBuffer,J,X);if(!$)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:$.status,partial:X}),this.emit("error",$),!0}drainFrames(){for(;;){let X=this.rxBuffer;if(X.length<2)return;let J=X[0],$=X[1],Y=(J&128)!==0,G=J&15,Q=($&128)!==0,z=$&127,Z=2;if(z===126){if(X.length<4)return;z=X[2]<<8|X[3],Z=4}else if(z===127){if(X.length<10)return;z=0;for(let B=0;B<8;B++)z=z*256+X[2+B];Z=10}if(Q)Z+=4;if(X.length<Z+z)return;let W=X.slice(Z,Z+z);this.rxBuffer=X.slice(Z+z),this.handleFrame(Y,G,W)}}handleFrame(X,J,$){if(J===9){this.writeFrame(10,$);return}if(J===10)return;if(J===8){let G=1005,Q="";if($.length>=2)G=$[0]<<8|$[1],Q=Buffer.from($.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:G,reason:Q};try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:Q}),this.emitClose(G,Q);return}if(J===1||J===2)this.fragOpcode=J,this.fragChunks=[$];else if(J===0)this.fragChunks.push($);if(!X)return;let Y=PS(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Y).toString("utf-8");this.emit("message",{data:G})}}send(X){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(X))}writeFrame(X,J){let $=J.length,Y=crypto.getRandomValues(new Uint8Array(4)),G;if($<126)G=[128|X,128|$];else if($<65536)G=[128|X,254,$>>8&255,$&255];else{G=[128|X,255];for(let Z=7;Z>=0;Z--)G.push($/2**(8*Z)&255)}let Q=new Uint8Array($);for(let Z=0;Z<$;Z++)Q[Z]=J[Z]^Y[Z%4];let z=new Uint8Array(G.length+4+$);z.set(G,0),z.set(Y,G.length),z.set(Q,G.length+4);try{this.enqueueWrite(z)}catch{}}enqueueWrite(X){this.writeQueue.push(X),this.flushWrites()}flushWrites(){let X=this.socket;if(!X)return;while(this.writeQueue.length>0){let J=this.writeQueue[0],$=X.write(J);if($<J.length){this.writeQueue[0]=J.slice($),this.log("write_backpressure",{written:$,remaining:J.length-$});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(X,J){return L1({component:"raw-ws-bun",event:X,sessionID:this.sessionID,url:this.url,...J})}}function DS(X){return X}function FS(X,J){let $=new Uint8Array(X.length+J.length);return $.set(X,0),$.set(J,X.length),$}function PS(X){let J=0;for(let G of X)J+=G.length;let $=new Uint8Array(J),Y=0;for(let G of X)$.set(G,Y),Y+=G.length;return $}import{connect as OS}from"node:net";import{connect as MS}from"node:tls";var _S="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",YN=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class $G{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(X,J,$){this.url=X,this.sessionID=$?.sessionID,this.connect(X,J)}addEventListener(X,J,$){this.listeners[X]?.add(J)}removeEventListener(X,J){this.listeners[X]?.delete(J)}peerClose;closeEmitted=!1;emitClose(X,J){if(this.closeEmitted)return;this.closeEmitted=!0,this.emit("close",{code:X,reason:J})}emit(X,J){for(let $ of[...this.listeners[X]??[]])try{$(J)}catch{}}async connect(X,J){let $=new URL(X.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Y=$.hostname,G=$.port?Number($.port):$.protocol==="https:"?443:80,Q=`${$.pathname}${$.search}`,z=crypto.getRandomValues(new Uint8Array(16)),Z=Buffer.from(z).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Z+_S));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[j,q]of Object.entries(J))B[j.toLowerCase()]=q;let H=[`GET ${Q} HTTP/1.1`,`Host: ${Y}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Z}`];for(let j of YN)if(B[j]!==void 0)H.push(`${AS(j)}: ${B[j]}`);for(let[j,q]of Object.entries(J))if(!YN.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")H.push(`${j}: ${q}`);let U=`${H.join(`\r
205
- `)}\r
206
- \r
207
- `;try{this.log("connect_start",{host:Y,port:G,tls:$.protocol==="https:"});let j=()=>{this.socket?.write(U)},q=$.protocol==="https:"?MS({host:Y,port:G,servername:Y},j):OS({host:Y,port:G},j);this.socket=q,q.on("data",(K)=>{this.onData(typeof K==="string"?Buffer.from(K,"binary"):K)}),q.on("error",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let L=K instanceof Error?K.message:String(K);this.log("socket_error",{message:L}),this.emit("error",{message:L})}),q.on("close",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:K}),this.emitClose(this.peerClose?.code??1006,this.peerClose?.reason??"socket closed")})}catch(j){this.readyState=3,this.log("connect_exception",{message:j instanceof Error?j.message:String(j)}),this.emit("error",{message:j instanceof Error?j.message:String(j)})}}onData(X){if(this.rxBuffer=TS(this.rxBuffer,X),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),$=J.indexOf(`\r
208
- \r
209
- `);if($===-1)return;let Y=J.slice(0,$),G=Y.split(`\r
210
- `)[0]??"",Q=Y.match(/sec-websocket-accept:\s*(\S+)/i),z=d3(G);if(z!==101){if(z===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!Q||Q[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:G}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice($+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(X=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let J=Buffer.from(this.rxBuffer).indexOf(`\r
211
- \r
212
- `);if(J===-1)return!1;let $=TX(this.rxBuffer,J,X);if(!$)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:$.status,partial:X}),this.emit("error",$),!0}drainFrames(){for(;;){let X=this.rxBuffer;if(X.length<2)return;let J=X[0],$=X[1],Y=(J&128)!==0,G=J&15,Q=($&128)!==0,z=$&127,Z=2;if(z===126){if(X.length<4)return;z=X[2]<<8|X[3],Z=4}else if(z===127){if(X.length<10)return;z=0;for(let B=0;B<8;B++)z=z*256+X[2+B];Z=10}if(Q)Z+=4;if(X.length<Z+z)return;let W=X.slice(Z,Z+z);this.rxBuffer=X.slice(Z+z),this.handleFrame(Y,G,W)}}handleFrame(X,J,$){if(J===9){this.writeFrame(10,$);return}if(J===10)return;if(J===8){let G=1005,Q="";if($.length>=2)G=$[0]<<8|$[1],Q=Buffer.from($.slice(2)).toString("utf-8");this.readyState=3,this.peerClose={code:G,reason:Q};try{this.socket?.end()}catch{}this.log("close_frame",{code:G,reason:Q}),this.emitClose(G,Q);return}if(J===1||J===2)this.fragOpcode=J,this.fragChunks=[$];else if(J===0)this.fragChunks.push($);if(!X)return;let Y=RS(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(Y).toString("utf-8");this.emit("message",{data:G})}}send(X){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(X))}writeFrame(X,J){let $=J.length,Y=crypto.getRandomValues(new Uint8Array(4)),G;if($<126)G=[128|X,128|$];else if($<65536)G=[128|X,254,$>>8&255,$&255];else{G=[128|X,255];for(let Z=7;Z>=0;Z--)G.push($/2**(8*Z)&255)}let Q=new Uint8Array($);for(let Z=0;Z<$;Z++)Q[Z]=J[Z]^Y[Z%4];let z=new Uint8Array(G.length+4+$);z.set(G,0),z.set(Y,G.length),z.set(Q,G.length+4);try{this.socket?.write(z)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(X,J){return L1({component:"raw-ws-node",event:X,sessionID:this.sessionID,url:this.url,...J})}}function AS(X){return X}function TS(X,J){let $=new Uint8Array(X.length+J.length);return $.set(X,0),$.set(J,X.length),$}function RS(X){let J=0;for(let G of X)J+=G.length;let $=new Uint8Array(J),Y=0;for(let G of X)$.set(G,Y),Y+=G.length;return $}function CS(){return typeof globalThis.Bun?.connect==="function"}var GN=CS()?JG:$G;function RX(X){return process.env[X]??process.env[X.toLowerCase()]}function ES(X){let J=RX("NO_PROXY");if(!J)return!1;let $=X.hostname.toLowerCase(),Y=J.split(",").map((G)=>G.trim().toLowerCase()).filter(Boolean);for(let G of Y){if(G==="*")return!0;if(G.startsWith(".")){if($===G.slice(1)||$.endsWith(G))return!0}else if($===G||$.endsWith(`.${G}`))return!0}return!1}function SS(X){let J=new URL(X);if(ES(J))return;if(J.protocol==="http:")return RX("HTTP_PROXY");if(J.protocol==="https:")return RX("HTTPS_PROXY")??RX("HTTP_PROXY");return}var QN={getProxyForUrl:SS};var IS=Z0("quota"),h9=Z0("transport"),BN="responses_websockets=2026-02-06",zN=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"],bS=new Set([I9,"x-opencode-title"]);function kS(X){let J=new Map;for(let Y of Object.keys(X))J.set(Y.toLowerCase(),Y);let $={};for(let Y of zN){let G=J.get(Y),Q=G===void 0?void 0:X[G];if(G!==void 0&&Q!==void 0)$[G]=Q}for(let[Y,G]of Object.entries(X))if(!zN.includes(Y.toLowerCase()))$[Y]=G;return $}function xS(X){let J={};for(let[$,Y]of Object.entries(X)){if(bS.has($.toLowerCase()))continue;J[$]=Y}return J}function wS(X){return X.replace(/^http/,"ws")}function vS(X){let J={};if(!X)return J;if(X instanceof Headers)return X.forEach(($,Y)=>{J[Y.toLowerCase()]=$}),J;if(Array.isArray(X)){for(let[$,Y]of X)J[$.toLowerCase()]=Y;return J}for(let[$,Y]of Object.entries(X))if(Y!=null)J[$.toLowerCase()]=String(Y);return J}function QG(X){return X instanceof DOMException&&X.name==="AbortError"}var HN=new WeakSet;function yS(X){return typeof X==="object"&&X!==null&&HN.has(X)}var VN=new WeakSet;function hS(X){return typeof X==="object"&&X!==null&&VN.has(X)}function UN(X){return VN.add(X),X}function ZN(X,J){let $=Error(X,J===void 0?void 0:{cause:J});return HN.add($),$}function fS(X){return new Promise((J,$)=>{if(X.signal?.aborted){$(YG(X.signal));return}let Y={...X.headers,"openai-beta":X.headers["openai-beta"]??BN},G=Y[I9]??Y["session-id"];delete Y["content-length"],Y=kS(xS(Y));let Q=typeof Bun>"u"?void 0:QN.getProxyForUrl(X.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),z=!0,Z=X.rawWebSocket?new GN(X.url,Y,{sessionID:G}):new globalThis.WebSocket(X.url,{headers:Y,...Q?{proxy:Q}:{},perMessageDeflate:z}),W=X.timeout?setTimeout(()=>{B(),Z.close(),$(Error("WebSocket connect timed out"))},X.timeout):void 0;function B(){if(W)clearTimeout(W);Z.removeEventListener("open",H),Z.removeEventListener("error",U),Z.removeEventListener("close",j),X.signal?.removeEventListener("abort",q)}function H(){B(),J(Z)}function U(K){B(),$(ZN(n0(K),K))}function j(K){B(),$(ZN(NN("WebSocket closed before open",K.code,K.reason)))}function q(){B(),Z.close(),$(YG(X.signal))}Z.addEventListener("open",H,{once:!0}),Z.addEventListener("error",U,{once:!0}),Z.addEventListener("close",j,{once:!0}),X.signal?.addEventListener("abort",q,{once:!0})})}function gS(X){let J=new TextEncoder,$=X.socket,Y,G=()=>{},Q=!1,z=0,Z=!1,W=!1,B,H=[],U=12,j=[],q=typeof X.body.previous_response_id==="string"?X.body.previous_response_id:void 0,K=typeof X.body.prompt_cache_key==="string"?X.body.prompt_cache_key:void 0,L={sessionID:X.sessionID,codexSessionID:K},F,O=0,_,C=new Set,N={addedItemIds:new Set,reasoningItemIds:new Set,finished:!1,other:!1};function P(){if(B)clearTimeout(B);G(),X.signal?.removeEventListener("abort",c0)}function A(a=$){a.close()}function T(){P(),Y?.enqueue(J.encode(`data: [DONE]
213
-
214
- `)),Y?.close()}function b(a){w(a,a)}function p(){if(!W)return"none";if(N.other)return"other";if(N.finished)return N.reasoningItemIds.size>0?"other":"finished-calls";return N.addedItemIds.size>0?"unfinished-calls":"none"}function i(){Y?.enqueue(J.encode(`data: ${JSON.stringify(nS)}
215
-
216
- `)),T()}function X0(a){let u0={...L,openingFrameTypes:H,openingItemTypes:j,responseID:F,previousResponseID:q,hasContinuation:q!==void 0,framesSinceCreated:O,msSinceLastFrame:_===void 0?void 0:Date.now()-_},t=p();if(t==="finished-calls"){if(Q)return;h9.warn("stream failed after finished function calls only; ended as completed",{reason:a.message,emittedOutput:!0,outputShape:t,...u0}),Q=!0,P(),X.onConnectionInvalid?.(a),i();return}if(t==="other"){let o=GG;h9.warn("stream failed after output; not retried",{reason:a.message,emittedOutput:!0,outputShape:t,...u0}),w(Error(o,{cause:a}),new w6(o,{cause:a}));return}let h=N.reasoningItemIds.size;h9.warn(t==="unfinished-calls"?"stream failed after unfinished function calls only; retryable":h>0?"stream failed after reasoning without text only; retryable":"stream failed before output; retryable",{reason:a.message,emittedOutput:W,outputShape:t,emptyReasoningItems:h,...u0}),b(a)}function w(a,u0){if(Q)return;Q=!0,P(),X.onConnectionInvalid?.(u0),Y?.error(a)}function J0(a){if(Q)return;if(!X.idleTimeout)return;if(B)clearTimeout(B);B=setTimeout(()=>X0(new w6(a)),X.idleTimeout)}async function G0(a){if(Q)return;if(typeof a.data!=="string"){X0(new w6("Unexpected binary WebSocket frame"));return}let u0=a.data,t=(()=>{try{let c=JSON.parse(u0);return typeof c==="object"&&c!==null?c:void 0}catch{return}})();if(t?.type==="codex.rate_limits"){IS.debug("codex.rate_limits frame received",{pid:process.pid}),J0("idle timeout waiting for websocket");let c=Oz(t);X.onQuota?.(c);return}let h=p(),o=h==="none"||h==="unfinished-calls"?i3(t):void 0;if(o&&t){Q=!0,P(),X.onRateLimitReached?.(o.window,o.resetAt),X.onTerminal?.(t),X.onFirstEvent?.(),Y?.error(new w6(`OpenAI account rate limit reached at admission (${o.window})`));return}if(t?.type==="error"&&X.onRetryableTerminal){if(G(),B)clearTimeout(B);B=void 0;try{let c=await X.onRetryableTerminal(t);if(Q){if(c)A(c);return}if(c){r(c);return}}catch(c){X0(new w6(c instanceof Error?c.message:String(c),{cause:c}));return}}let e=pS(t,u0);if(e&&t){if(!Z)X.onFirstEvent?.(e);Q=!0,P(),X.onTerminal?.(t);let c=new P1({message:e.message,url:$.url,requestBodyValues:X.body,statusCode:e.status,responseHeaders:e.headers,responseBody:e.body}),D0=p();if(D0==="none"||D0==="unfinished-calls"){if(D0==="unfinished-calls")h9.warn("protocol error after unfinished function calls only; surfaced as before output",{...L,status:e.status,reason:e.message,outputShape:D0,responseID:F,previousResponseID:q});Y?.error(c);return}if(h9.warn(D0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...L,status:e.status,reason:e.message,outputShape:D0,responseID:F,previousResponseID:q}),D0==="finished-calls"){i();return}Y?.error(Error(GG,{cause:c}));return}if(s(t)&&t.type==="response.failed"){let c=s(t.response)?t.response.failed:void 0,D0=s(c)?c.rate_limit_reached_type:void 0;if(typeof D0==="string"){Q=!0,P(),X.onRateLimitReached?.(D0),X.onTerminal?.(t);let l0=p();if(l0!=="none")h9.warn(l0==="other"?"rate limit reached after output; ended without retry":l0==="finished-calls"?"rate limit reached after finished function calls only; ended as completed":"rate limit reached after unfinished function calls only; retryable",{...L,outputShape:l0,responseID:F,previousResponseID:q});if(l0==="none"||l0==="unfinished-calls")X.onFirstEvent?.(),Y?.error(new w6(`OpenAI account rate limit reached mid-stream (${D0})`));else if(l0==="finished-calls")i();else T();return}}if(!t){if(!Z)X.onFirstEvent?.();J0("idle timeout waiting for websocket");return}if(mS(t,C),!Z)X.onFirstEvent?.();if(Y?.enqueue(J.encode(`${u0.split(/\r?\n/).map((c)=>`data: ${c}`).join(`
217
- `)}
218
-
219
- `)),Z=!0,_=Date.now(),F!==void 0)O++;if(H.length<U)H.push(String(t.type));if(t.type==="response.output_item.added"&&j.length<U)j.push(s(t.item)?String(t.item.type):"unknown");if(t.type==="response.created")F=dS(t),h9.debug("response created",{...L,responseID:F,previousResponseID:q,hasContinuation:q!==void 0});if(!jN(t.type))W=!0,iS(t,N);if(J0("idle timeout waiting for websocket"),t.type==="response.completed"||t.type==="response.done"){Q=!0,uS(t,C),X.onComplete?.(t,C),X.onTerminal?.(t),T();return}if(t.type==="response.failed"||t.type==="response.incomplete"||t.type==="error")Q=!0,X.onTerminal?.(t),T()}function L0(a){X0(new w6(n0(a),{cause:a}))}function m(a){if(Q)return;let u0=a.code===1009,t=new w6(u0?qN:NN("WebSocket closed before response.completed",a.code,a.reason),{retryable:!u0});if(u0)h9.warn("websocket peer refused the request size",{...L,requestBytes:z,reason:a.reason.toString()});X0(u0?UN(t):t)}function c0(){let a=YG(X.signal);if(Q)return;Q=!0,P(),A(),X.onAbort?.(a),Y?.error(a)}function m0(a){if(Q)return;Q=!0,P(),A(),X.onAbort?.(cS(a))}function r(a){G(),$=a,$.addEventListener("message",G0),$.addEventListener("error",L0,{once:!0}),$.addEventListener("close",m,{once:!0}),G=()=>{$.removeEventListener("message",G0),$.removeEventListener("error",L0),$.removeEventListener("close",m)};let{background:u0,...t}=X.body;J0("idle timeout sending websocket request");try{let h=JSON.stringify({type:"response.create",...t});z=h.length,$.send(h),J0("idle timeout waiting for websocket")}catch(h){if(Q)return;b(new w6(h instanceof Error?h.message:String(h),{cause:h}))}}return new Response(new ReadableStream({start(a){if(Y=a,X.signal?.addEventListener("abort",c0,{once:!0}),X.signal?.aborted){c0();return}r($)},cancel(a){m0(a)}}),{status:200,headers:{"content-type":"text/event-stream"}})}function mS(X,J){if(X.type!=="response.output_item.done")return;if(!s(X.item))return;KN(X.item,J)}function uS(X,J){let $=X.response;if(!s($)||!Array.isArray($.output))return;for(let Y of $.output)if(s(Y))KN(Y,J)}function KN(X,J){if(X.type!=="function_call"&&X.type!=="custom_tool_call")return;let $=typeof X.call_id==="string"?X.call_id:typeof X.id==="string"?X.id:void 0;if($)J.add($)}function pS(X,J){if(X?.type!=="error")return;let $=X.status??X.status_code;if(typeof $!=="number"||$>=200&&$<300)return;return{status:$,headers:s(X.headers)?Object.fromEntries(Object.entries(X.headers).flatMap(([Y,G])=>typeof G==="string"||typeof G==="number"||typeof G==="boolean"?[[Y,String(G)]]:[])):void 0,body:J,message:s(X.error)&&typeof X.error.message==="string"?X.error.message:`${$}`}}function i3(X){if(typeof X==="string")try{return i3(JSON.parse(X))}catch{return}if(!s(X))return;let J=i3(X.cause);if(J)return J;let $=i3(X.body);if($)return $;let Y=s(X.error)?X.error:X,G=typeof Y.type==="string"?Y.type:void 0,Q=X.status??X.status_code;if(G!=="usage_limit_reached"&&Q!==429)return;let{resets_at:z,resets_in_seconds:Z}=Y,W=typeof z==="number"&&Number.isFinite(z)&&z>0?z*1000:typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Date.now()+Z*1000:void 0;return{window:G??"primary",resetAt:W}}function cS(X){if(QG(X))return X;if(X instanceof Error)return X;return new DOMException(typeof X==="string"?X:"Aborted","AbortError")}function YG(X){let J=X?.reason;if(QG(J))return J;if(lS(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function lS(X){return X instanceof Error&&(X.name==="ProviderHeaderTimeoutError"||X.name==="ProviderResponseStreamError")}function dS(X){let J=X.response;if(!s(J))return;return typeof J.id==="string"?J.id:void 0}function iS(X,J){let $=s(X.item)?X.item:void 0;switch(X.type){case"response.output_item.added":if($?.type==="function_call"&&typeof $.id==="string"){J.addedItemIds.add($.id);return}if(WN($)&&typeof $?.id==="string"){J.reasoningItemIds.add($.id);return}break;case"response.function_call_arguments.delta":case"response.function_call_arguments.done":if(typeof X.item_id==="string"&&J.addedItemIds.has(X.item_id))return;break;case"response.output_item.done":if($?.type==="function_call"&&$.status==="completed"&&typeof $.id==="string"&&typeof $.call_id==="string"&&typeof $.name==="string"&&typeof $.arguments==="string"){J.finished=!0;return}if(WN($)&&typeof $?.id==="string"&&J.reasoningItemIds.has($.id))return;break}J.other=!0}function WN(X){if(X?.type!=="reasoning")return!1;let J=($)=>$===void 0||$===null||Array.isArray($)&&$.length===0;return J(X.summary)&&J(X.content)}var nS={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function jN(X){return X==="response.created"||X==="response.in_progress"||X.startsWith("codex.")}var GG="The response ended early after part of it had already been shown. It was not sent again, because repeating it would duplicate that output and re-run any tools it had started. The transport log records what ended it.",qN="The request was larger than the websocket would carry, so it was sent over HTTP instead. Resending it unchanged over the same socket cannot succeed. The transport log records the size.";function NN(X,J,$){let Y=[`code ${J}`];if($.length>0)Y.push($.toString());return`${X} (${Y.join(": ")})`}var ZG="x-opencode-title",CX="x-openai-auth-quota-account",zG=new Set([ZG,I9,CX,"x-opencode-session"]),aS=15000,oS=300000,rS=3300000,LN="websocket_connection_limit_reached";function tS(X){let J=typeof X["chatgpt-account-id"]==="string"?X["chatgpt-account-id"]:"",$=typeof X.authorization==="string"&&X.authorization.startsWith("Bearer ")?X.authorization.slice(7):"",Y=J?`acct:${J}`:`tok:${$}`;return sS("sha256").update(Y).digest("hex").slice(0,12)}function eS(X){let J=X?.httpFetch??globalThis.fetch,$=new Map,Y=X?.connectTimeout??aS,G=X?.idleTimeout??oS,Q=X?.maxConnectionAge??rS,z=X?.streamRetries??5,Z=X?.firstEventGraceMs??250,W=X?.rawWebSocket??!1,B=X?.onQuota,H=X?.onRateLimitReached,U=setInterval(()=>L(),Math.min(G,60000));if(typeof U==="object"&&"unref"in U&&typeof U.unref==="function")U.unref();function j(_,C,N,P){if(!C||!N)return N;WG(_,DN(C),void 0,P);let A=new Headers(N.headers),T=A.get("x-codex-turn-metadata");if(!T)return N;let b=RN(T,_.turnID,_.turnStartedAt);if(!b)return N;return A.set("x-codex-turn-metadata",b),{...N,headers:A}}async function q(_,C){let N=_ instanceof URL?_.toString():typeof _==="string"?_:_.url,P=N6.normalizeHeaders(C?.headers),A=bN(C),T=o7(A);if(C?.method!=="POST"||!new URL(N).pathname.endsWith("/responses"))return J(_,T);let b=(()=>{try{if(typeof C?.body!=="string")return;let r=JSON.parse(C.body);return typeof r==="object"&&r!==null?r:void 0}catch{return}})();if(!b?.stream)return J(_,T);if(P[ZG]==="true")return J(_,T);let p=P[I9]??P["x-session-affinity"]??P["session-id"],i=p;if(!p)return J(_,T);let X0=N6.normalizeHeaders(A?.headers),w=tS(X0),J0=`${p}:${w}:conversation`,G0=typeof P[CX]==="string"?P[CX]:void 0,L0=H?(r,a)=>H(r,G0,a):void 0,m=$.get(J0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};$.set(J0,m);let c0=DN(b),m0;if(m.fallback)return J(_,j(m,b,T,m0));if(m.busy)return J(_,j(m,b,T,m0));m.busy=!0,m.lastUsedAt=Date.now();try{m0=P4(m,c0);let r=N6.normalizeHeaders(A?.headers),a=typeof r.authorization==="string"&&r.authorization.startsWith("Bearer ")?r.authorization.slice(7):"",u0=typeof r["chatgpt-account-id"]==="string"?r["chatgpt-account-id"]:void 0,t=B?(p0)=>B(p0,a,G0,u0):void 0,h=!m.socket&&!m.continuation?WI(r):r;if(m.socket=await YI(m,X?.url??N,h,Y,Q,W,C?.signal),VI(m,c0,m0))await GI(m,c0,G,{signal:C?.signal??void 0,sessionID:i,url:X?.url??N,headers:A?.headers,onRateLimitReached:L0});let o=()=>{},e=()=>{},c=new Promise((p0,N8)=>{o=p0,e=N8}),D0=HI(m,c0,m0),l0=n3(TN(m,D0,c0,m0)),d6=typeof l0.previous_response_id==="string";await U4({sessionID:i,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(l0),url:X?.url??N,method:A?.method,headers:A?.headers});let s0=N6.streamResponsesWebSocket({socket:m.socket,body:l0,sessionID:i??void 0,idleTimeout:G,signal:C?.signal??void 0,onQuota:t,onRateLimitReached:L0,onFirstEvent:(p0)=>o(p0??!0),onComplete:(p0,N8)=>{let O4=ON(p0);L1({component:"ws-pool",event:"main_completed",sessionID:i,responseID:PN(p0),usage:O4}),AN(m,c0,p0,N8,d6,m0)},onTerminal:(p0)=>{if(m.busy=!1,m.lastUsedAt=Date.now(),m.streamFailures=0,p0.type!=="response.completed"&&p0.type!=="response.done")m.continuation=void 0,V9(m)},onConnectionInvalid:(p0)=>{if(m.busy=!1,m.lastUsedAt=Date.now(),N6.isOversizedFrame(p0))m.fallback=!0;if(!m.fallback)K(m);m.continuation=void 0,V9(m),o(!1)},onAbort:(p0)=>{m.busy=!1,m.lastUsedAt=Date.now(),m.streamFailures=0,m.continuation=void 0,V9(m),e(p0)},onRetryableTerminal:async(p0)=>{let N8=FN(p0);if(!N8)return;throw m.fallback=!0,N8}}),D6=await XI(c,Z);if(D6!==!1){if(D6===!0||D6.status<200||D6.status>599)return s0;return new Response(D6.body,{status:D6.status,headers:{"content-type":"application/json",...D6.headers}})}let v6=()=>J(_,j(m,b,T,m0));if(!m.fallback)return JI(s0,v6);return v6()}catch(r){if(m.busy=!1,m.lastUsedAt=Date.now(),N6.isAbortError(r))throw m.streamFailures=0,m.continuation=void 0,V9(m),r;let a=N6.parseRateLimitSignal(r);if(a)L0?.(a.window,a.resetAt);if(N6.isUpgradeFailure(r)&&!W)m.fallback=!0;if(K(m),m.continuation=void 0,V9(m),m.fallback)return J(_,j(m,b,T,m0));return $I(new w6(r instanceof Error?r.message:String(r),{cause:r}))}}function K(_){if(_.streamFailures++,_.streamFailures>z)_.fallback=!0}function L(){let _=Date.now();for(let[C,N]of $){if(N.busy)continue;if(_-N.lastUsedAt<G)continue;V9(N),$.delete(C)}}function F(){clearInterval(U);for(let _ of $.values())V9(_);$.clear()}function O(_){let C=`${_}:`;for(let[N,P]of $){if(!N.startsWith(C))continue;V9(P),$.delete(N)}}return Object.assign(q,{close:F,remove:O})}function FN(X){if(X.type!=="error"||!s(X.error)||X.error.code!==LN)return;return Error(typeof X.error.message==="string"?X.error.message:LN)}async function XI(X,J){if(J<=0)return!1;return new Promise(($,Y)=>{let G=setTimeout(()=>$(!1),J);X.then((Q)=>{clearTimeout(G),$(Q)},(Q)=>{clearTimeout(G),Y(Q)})})}function JI(X,J){let $=X.body;if(!$)return X;let Y=!1,G=new ReadableStream({async start(Q){let z=$.getReader(),Z=async(W)=>{while(!0){let{done:B,value:H}=await W.read();if(B)return;if(H&&H.length>0)Y=!0,Q.enqueue(H)}};try{await Z(z),Q.close()}catch(W){if(Y||!N6.isOversizedFrame(W)){Q.error(W);return}try{let B=await J();if(!B.ok){Q.error(new w6(`HTTP fallback after an oversized WebSocket frame failed with ${B.status}`));return}if(B.body)await Z(B.body.getReader());Q.close()}catch(B){Q.error(B)}}},cancel(Q){$.cancel(Q)}});return new Response(G,{status:X.status,headers:X.headers})}function $I(X){return new Response(new ReadableStream({start(J){J.error(X)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function YI(X,J,$,Y,G,Q,z){if(X.socket?.readyState===WebSocket.OPEN&&X.connectedAt&&Date.now()-X.connectedAt<G)return X.socket;V9(X);let Z=await N6.connectResponsesWebSocket({url:N6.toWebSocketUrl(J),headers:$,timeout:Y,rawWebSocket:Q,signal:z??void 0});return X.connectedAt=Date.now(),Z}function V9(X){if(X.socket)X.socket.close(),X.socket=void 0;X.connectedAt=void 0,X.continuation=void 0}async function GI(X,J,$,Y){if(!X.socket||!Array.isArray(J.input)||J.input.length===0)return;let G=zI(J);await U4({sessionID:Y.sessionID,transport:"websocket",phase:"prewarm",bodyText:()=>JSON.stringify(G),url:Y.url,method:"POST",headers:Y.headers});let Q=N6.streamResponsesWebSocket({socket:X.socket,body:G,sessionID:Y.sessionID,idleTimeout:$,signal:Y.signal,onRateLimitReached:Y.onRateLimitReached,onComplete:(z,Z)=>{L1({component:"ws-pool",event:"prewarm_completed",sessionID:Y.sessionID,responseID:PN(z),usage:ON(z)}),AN(X,G,z,Z,!1,{input:D1([]),signature:SN(G),priorInputs:new Map})},onTerminal:(z)=>{if(z.type!=="response.completed"&&z.type!=="response.done")X.continuation=void 0},onConnectionInvalid:()=>{X.continuation=void 0},onAbort:()=>{X.continuation=void 0},onRetryableTerminal:async(z)=>{let Z=FN(z);if(!Z)return;throw X.fallback=!0,Z}});await QI(Q)}function PN(X){let J=X.response;if(!s(J))return;return typeof J.id==="string"?J.id:void 0}function ON(X){let J=X.response;if(!s(J))return;return s(J.usage)?J.usage:void 0}async function QI(X){let J=X.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function zI(X){return n3({...X,generate:!1,input:[],previous_response_id:void 0,client_metadata:ZI(X.client_metadata)})}function MN(X){return JSON.stringify({session_id:X.session_id,thread_id:X.thread_id,thread_source:X.thread_source,turn_id:"",sandbox:X.sandbox,request_kind:"prewarm",window_id:X.window_id})}function ZI(X){if(!s(X))return X;if(typeof X["x-codex-turn-metadata"]!=="string")return X;try{let J=JSON.parse(X["x-codex-turn-metadata"]);if(!s(J))return X;return{...X,"x-codex-turn-metadata":MN(J),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return X}}function WI(X){let J=X["x-codex-turn-metadata"];if(!J)return X;try{let $=JSON.parse(J);if(!s($))return X;return{...X,"x-codex-turn-metadata":MN($)}}catch{return X}}var _N=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function DN(X){let J={...X};if(Array.isArray(X.input))J.input=X.input.map(BI);return J}function n3(X){let J={};for(let $ of _N)if($ in X)J[$]=X[$];for(let $ of Object.keys(X))if(!($ in J))J[$]=X[$];return J}function BI(X){if(!s(X))return X;if(typeof X.type==="string")return X;if(typeof X.role!=="string")return X;if(!("content"in X))return X;return{...X,type:"message"}}function AN(X,J,$,Y,G,Q=P4(X,J)){let z=$.response,Z=s(z)&&typeof z.id==="string"?z.id:void 0;if(!Z||!Array.isArray(J.input)){X.continuation=void 0;return}let W=G?new Set(X.continuation?.finalizedCallIds):new Set;for(let B of Y)W.add(B);X.continuation={responseID:Z,input:J.input,signature:Q.signature,canonical:S3(Q.input),finalizedCallIds:W}}function WG(X,J,$=J,Y=P4(X,{...$,input:Array.isArray($.input)?$.input:J.input})){let G=Array.isArray(J.input)?J.input:[],Q=Array.isArray($.input)?$.input:G,z=Y.signature,Z=X.turnInput&&X.turnSignature===z?I3(CN(Y,X.turnInput),Y.input):void 0,W=Z===void 0?G:Q.slice(Z);if(W.length>0&&W.some(EN)||!X.turnID)X.turnID=F1(),X.turnStartedAt=Date.now();X.turnInput=Q.slice(),Y.priorInputs.set(X.turnInput,Y.input),X.turnSignature=z,X.turnCanonical=S3(Y.input)}function TN(X,J,$=J,Y=P4(X,{...$,input:Array.isArray($.input)?$.input:J.input})){WG(X,J,$,Y);let G=J.client_metadata;if(!s(G)||typeof G["x-codex-turn-metadata"]!=="string")return J;let Q=RN(G["x-codex-turn-metadata"],X.turnID,X.turnStartedAt);if(!Q)return J;return{...J,client_metadata:{...G,"x-codex-turn-metadata":Q}}}function RN(X,J,$){let Y;try{Y=JSON.parse(X)}catch{return}if(!s(Y))return;return JSON.stringify({session_id:Y.session_id,thread_id:Y.thread_id,thread_source:Y.thread_source,turn_id:J,sandbox:Y.sandbox,turn_started_at_unix_ms:$,request_kind:"turn",window_id:Y.window_id})}function P4(X,J){let $=Array.isArray(J.input)?J.input:[],Y=new Map;if(X.turnInput&&X.turnCanonical)Y.set(X.turnInput,X.turnCanonical);if(X.continuation?.canonical)Y.set(X.continuation.input,X.continuation.canonical);let G=D1($,X.turnCanonical??X.continuation?.canonical);return Y.set($,G),{input:G,signature:SN(J),priorInputs:Y}}function CN(X,J){let $=X.priorInputs.get(J);if(!$){for(let[Y,G]of X.priorInputs)if(Y.length===J.length&&Y.every((Q,z)=>Q===J[z])){$=G;break}$??=D1(J),X.priorInputs.set(J,$)}return $}function HI(X,J,$=P4(X,J)){let Y=Array.isArray(J.input)?J.input:void 0;if(!Y||!X.continuation)return J;if(X.continuation.signature!==$.signature)return X.continuation=void 0,J;if(!IN(X.continuation,$))return X.continuation=void 0,J;if(X.continuation.input.length===0)return{...J,previous_response_id:X.continuation.responseID};let G=Y.slice(X.continuation.input.length),Q=UI(G,X.continuation.finalizedCallIds);if(Q.length===0)return J;return{...J,previous_response_id:X.continuation.responseID,input:Q}}function VI(X,J,$=P4(X,J)){let Y=Array.isArray(J.input)?J.input:void 0;if(!X.continuation)return!0;if(!Y)return!1;if(!IN(X.continuation,$))return!0;return Y.slice(X.continuation.input.length).some(EN)}function EN(X){if(!s(X))return!1;if(!(X.type==="message"||("role"in X)))return!1;return X.role==="user"||X.role==="developer"}function UI(X,J){return X.filter(($)=>{if(!s($))return!0;if(typeof $.type==="string"&&$.type.endsWith("_output"))return!0;if($.type==="function_call_output"||$.type==="custom_tool_call_output")return!0;if($.type==="function_call"||$.type==="custom_tool_call"){let Y=typeof $.call_id==="string"?$.call_id:typeof $.id==="string"?$.id:void 0;return Y?!J.has(Y):!0}if($.type==="message")return $.role!=="assistant";if(typeof $.role==="string")return $.role!=="assistant";return!1})}function SN(X){return q4(KI(Object.fromEntries(Object.entries(X).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function KI(X){if(!s(X.client_metadata))return X;let J=Object.fromEntries(Object.entries(X.client_metadata).filter(([$])=>$!=="x-codex-turn-metadata"&&$!=="x-codex-ws-stream-request-start-ms"));return{...X,client_metadata:J}}function IN(X,J){if(X.input.length>=J.input.texts.length)return!1;return I3(CN(J,X.input),J.input)!==void 0}function bN(X){if(!X?.headers)return X;if(X.headers instanceof Headers){let J=new Headers(X.headers);for(let $ of zG)J.delete($);return{...X,headers:J}}if(Array.isArray(X.headers))return{...X,headers:X.headers.filter((J)=>!zG.has(J[0].toLowerCase()))};return{...X,headers:Object.fromEntries(Object.entries(X.headers).filter(([J])=>!zG.has(J.toLowerCase())))}}var MI=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),_I=new Set(["gpt-5.6","gpt-6","gpt-6.1"]);function AI(X){if(MI.has(X))return!0;if(_I.has(X))return!1;let $=X.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return $?parseFloat($)>5.4:!1}function TI(X){if(X.includes("gpt-5.5"))return{context:400000,input:272000,output:128000};if(X.includes("gpt-6-astra"))return{context:872000,input:744000,output:128000};if(X.includes("gpt-5.6")||X.includes("gpt-6-sol")||X.includes("gpt-6-luna")||X.includes("gpt-6.1-sol"))return{context:372000,input:244000,output:128000};return}var RI="Refusing to send a request with no access token. This is a defect in the plugin, not a problem with the provider or the account; the transport log names the account and the path that produced it.",CI=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),EI="opencode-oauth-dummy-key",SI="terminal_resize_reflow",KG="0.159.0",II=`codex_exec/${KG} (Debian 12.0.0; aarch64) unknown (codex_exec; ${KG})`,bI="seccomp",si=()=>h8,kI=120000,xI=90000,wI=4000,kN=50,xN=3,vI=25,yI=60000,hI="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",jG=!1,bX;function ai(){return bX}function oi(){jG=!1,bX=void 0}var wN=Z0("models"),vN=!1,yN=!1;class NG extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(X){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:X});this.name="AuthPersistError"}}class L6 extends Error{code;constructor(X,J){super(J);this.name="ResetTargetResolutionError",this.code=X}}function HG(X,J,$,Y){let G=($?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!X||!J||J-Y<=G}function fI(X,J){let $=X==="main",Y=J.row,G=()=>new L6("token_unavailable",$?"Main OpenAI account has no usable access token.":`Fallback account ${X} has no usable access token.`);if(!Y){if($)throw G();throw new L6("unknown_account",`Fallback account ${X} was not found.`)}if(!Y.enabled)throw new L6("disabled_account",`${$?"Main":"Fallback"} account ${X} is disabled.`);if(Y.type!=="oauth")throw new L6("non_oauth_account",`${$?"Main":"Fallback"} account ${X} is not an OAuth account.`);if(!J.token)throw G();let Q=H6(J.token);return{accountKey:X,label:$?"Main account":Y.label??X,accessToken:J.token,chatgptAccountId:Y.identity??(Q?V6(Q):void 0)}}function gI(X){async function J(){let $=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath}),Y=G9($);if(!$||!Y||T0(Y))throw new L6("token_unavailable","Main OpenAI account has no usable access token.");let G=Y;if(HG(G.access,G.expires,$,X.now()))G=await(X.refreshPoolMainRow??X.refreshFallbackAccount)(G,$);if(!G.access)throw new L6("token_unavailable","Main OpenAI account has no usable access token.");let Q=H6(G.access);return{accountKey:"main",label:"Main account",accessToken:G.access,chatgptAccountId:G.accountId??(Q?V6(Q):void 0)}}return async($)=>{let Y=await X.poolAccess?.($);if(Y)return fI($,Y);if($==="main"){let H=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath}),U=await X.getAuth();if(R6(U))return J();if(U.type!=="oauth")throw new L6("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(HG(U.access,U.expires,H,X.now()))try{U={type:"oauth",...await X.refreshMainWithLease()}}catch(L){if(L instanceof q1)return J();throw L}if(!U.access)throw new L6("token_unavailable","Main OpenAI account has no usable access token.");let j=H6(U.access),q=j?V6(j):void 0,K=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath});return{accountKey:$,label:"Main account",accessToken:U.access,chatgptAccountId:q??K?.mainAccountId}}let G=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath}),Q=G?.accounts.find((H)=>H.id===$);if(!G||!Q)throw new L6("unknown_account",`Fallback account ${$} was not found.`);if(Q.enabled===!1)throw new L6("disabled_account",`Fallback account ${$} is disabled.`);if(!v0(Q))throw new L6("non_oauth_account",`Fallback account ${$} is not an OAuth account.`);let z=()=>new L6("token_unavailable",`Fallback account ${$} has no usable access token.`);if(T0(Q))throw z();let Z=Q;if(HG(Z.access,Z.expires,G,X.now()))Z=await X.refreshFallbackAccount(Z,G);if(!Z.access)throw z();let W=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath}),B=W?.accounts.find((H)=>H.id===$);if(!W||!B)throw new L6("unknown_account",`Fallback account ${$} was not found.`);if(B.enabled===!1)throw new L6("disabled_account",`Fallback account ${$} is disabled.`);if(!v0(B))throw new L6("non_oauth_account",`Fallback account ${$} is not an OAuth account.`);return{accountKey:$,label:Z.label??$,accessToken:Z.access,chatgptAccountId:B.accountId}}}function mI(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function VG(X){return X instanceof NG}function hN(){throw Error(hI)}async function uI(X,J={}){let $=M0(V0());if(k$($.configPath)){await V1(Z4($),J.holdsMainRefreshLock?void 0:z9($),(Y)=>{if(J.canWrite&&!J.canWrite())throw Error(N1["vault-refused"]);X(Y)});return}await j7((Y)=>{return X(Y),Y},$,{canWrite:J.canWrite})}var $L=null;function ri(){return $L}function pI(X){return Math.floor(Math.random()*X)}var cI=!0;function lI(X){if(typeof X!=="string")return;try{let J=JSON.parse(X);return typeof J==="object"&&J!==null&&!Array.isArray(J)?J:void 0}catch{return}}function dI(X,J,$){let Y=X.get(J);if(Y)return Y;let G=F1(),Q={threadID:G,turnID:F1(),windowID:`${G}:0`};return X.set(J,Q),$?.(),Q}function YL(){return OI(I7(),"openai-auth-sessions.json")}function iI(){let X=new Map;try{let J=JSON.parse(LI(YL(),"utf8"));if(!s(J.sessions))return X;for(let[$,Y]of Object.entries(J.sessions)){if(!s(Y)||typeof Y.threadID!=="string")continue;X.set($,{threadID:Y.threadID,turnID:F1(),windowID:`${Y.threadID}:0`})}}catch{}return X}function nI(X){let J=YL(),$=`${J}.tmp-${process.pid}`;try{NI(I7(),{recursive:!0});let Y={version:1,sessions:Object.fromEntries([...X.entries()].map(([G,Q])=>[G,{threadID:Q.threadID}]))};PI($,`${JSON.stringify(Y,null,2)}
220
- `,"utf8"),DI($,J)}catch{}}function kX(X,J){return s(X)&&(X.type==="message"||("role"in X))&&X.role===J}function sI(X,J,$){if(!X.input)return J.length>0;let Y=X.canonicalInput??D1(X.input);if(I3(Y,$)===void 0)return!0;return J.slice(X.input.length).some((Q)=>kX(Q,"user")||kX(Q,"developer"))}function aI(X,J){let $=Array.isArray(J?.input)?J.input:void 0,Y=$?D1($,X.canonicalInput):void 0;if($&&Y&&(sI(X,$,Y)||!X.turnID))X.turnID=F1(),X.turnStartedAt=Date.now();else if(!X.turnStartedAt)X.turnStartedAt=Date.now();if($&&Y)X.input=$.slice(),X.canonicalInput=S3(Y)}function oI(X){let J=X.headers.get(xX);if(X.headers.delete(xX),!X.metadata)return{init:X.init};let $=lI(X.init?.body);if(!X.websocket)aI(X.metadata,$);else if(!X.metadata.turnStartedAt)X.metadata.turnStartedAt=Date.now();if(!X.metadata.turnStartedAt)X.metadata.turnStartedAt=Date.now();let Y=JSON.stringify({session_id:X.metadata.threadID,thread_id:X.metadata.threadID,thread_source:"user",turn_id:X.metadata.turnID,sandbox:bI,turn_started_at_unix_ms:X.metadata.turnStartedAt,request_kind:"turn",window_id:X.metadata.windowID});if(X.headers.set("originator","codex_exec"),X.websocket)X.headers.delete("accept"),X.headers.delete("content-type");else X.headers.set("accept","text/event-stream");if(X.headers.set("session-id",X.metadata.threadID),X.headers.delete("x-session-id"),X.headers.delete("x-session-affinity"),X.headers.set("thread-id",X.metadata.threadID),X.headers.set("x-codex-window-id",X.metadata.windowID),X.headers.set("x-client-request-id",X.metadata.threadID),X.headers.set("x-codex-beta-features",SI),X.headers.set("x-codex-turn-metadata",Y),X.headers.set("user-agent",II),X.headers.set("version",KG),X.dumpSessionID)X.headers.set(I9,X.dumpSessionID);let G=$;if(!G)return{init:X.init};let Q=X.responsesLite&&typeof G.model==="string"&&CI.has(G.model);if(Q&&!X.websocket)X.headers.set("x-openai-internal-codex-responses-lite","true");if(G.prompt_cache_key=X.metadata.threadID,G.parallel_tool_calls??=!0,Array.isArray(G.tools))G.tools=G.tools.map($b);if(Xb(G,X.metadata,J),Q)Jb(G);let z={...typeof G.client_metadata==="object"&&G.client_metadata!==null?G.client_metadata:{},"x-codex-installation-id":X.installationID,"x-codex-window-id":X.metadata.windowID};if(X.websocket){if(z["x-codex-turn-metadata"]=Y,z["x-codex-ws-stream-request-start-ms"]=String(Date.now()),Q)z.ws_request_header_x_openai_internal_codex_responses_lite="true"}return G.client_metadata=z,X.headers.delete("content-length"),X.headers.delete("Content-Length"),{init:{...X.init,body:JSON.stringify(n3(G))}}}function rI(X,J){return X.find(($)=>$.enabled!==!1&&v0($)&&($.id===J||$.accountId===J))}function fN(X,J){if(!J)return X;let $={...X};for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let G=J[Y];if($[Y]===void 0&&G!==void 0)$[Y]=G}if($.spendControl===void 0&&$.spendControlCleared!==!0&&J.spendControl!==void 0)$.spendControl=J.spendControl;return $}function EX(X,J){if(!X)return X;if(typeof X.checkedAt==="number"&&Number.isFinite(X.checkedAt))return X;return{...X,checkedAt:J}}function GL(X,J,$=Date.now(),Y=J.mainAccountId){let G=X.getMain(),Q=G?.quota;return{main:{quota:Q?{...Q,checkedAt:G.checkedAt,primary:EX(Q.primary,G.checkedAt),secondary:EX(Q.secondary,G.checkedAt)}:null,...typeof Y==="string"?{mainAccountId:Y}:{},killed:!1,...Q?.resetCreditsAvailable!==void 0?{resetCredits:Q.resetCreditsAvailable}:{}},fallbacks:J.accounts.filter((z)=>z.enabled).map((z)=>{let Z=X.getFallback(z.id),W=Z?.quota;return{id:z.id,label:z.label,accountId:Z?.accountId??z.accountId,quota:W?{...W,checkedAt:Z.checkedAt,primary:EX(W.primary,Z.checkedAt),secondary:EX(W.secondary,Z.checkedAt)}:null,killed:!1,enabled:!0,...W?.resetCreditsAvailable!==void 0?{resetCredits:W.resetCreditsAvailable}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:$}}function ti(X,J,$,Y=Date.now()){return{...GL(X,J,Y),activeId:$}}function gN(X,J){if(J?.headers!==void 0)return new Headers(J.headers);if(X instanceof Request)return new Headers(X.headers);return new Headers}async function UG(X,J){if(!(X instanceof Request))return J;let $=new Request(X,J),Y=$.method.toUpperCase(),G=Y==="GET"||Y==="HEAD"||$.body===null?void 0:await $.text();return{method:$.method,headers:new Headers($.headers),body:G,signal:$.signal,cache:$.cache,credentials:$.credentials,integrity:$.integrity,keepalive:$.keepalive,mode:$.mode,redirect:$.redirect,referrer:$.referrer,referrerPolicy:$.referrerPolicy}}function mN(X){return X.get("x-session-affinity")??X.get("x-opencode-session")??X.get("x-session-id")??X.get("session-id")??void 0}function qG(X){if(Array.isArray(X)){let $=X;for(let Y=0;Y<X.length;Y++){let G=qG(X[Y]);if(G===X[Y])continue;if($===X)$=X.slice();$[Y]=G}return $}if(!s(X))return X;let J=X;for(let $ of Object.keys(X)){if(X.type==="input_image"&&$==="detail"){if(J===X)J={...X};delete J[$];continue}let Y=qG(X[$]);if(Y===X[$])continue;if(J===X)J={...X};J[$]=Y}return J}var tI=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),xX="x-openai-auth-agent",eI=new Set(["title","compaction","summary"]);function Xb(X,J,$){if($!==null&&eI.has($))return;let Y=typeof X.model==="string"?X.model:"";if(!tI.has(Y))return;let G=s(X.reasoning)?X.reasoning:void 0,Q=typeof G?.effort==="string"?G.effort:void 0;if(!Q)return;let z=Array.isArray(X.input)?X.input:void 0;J.effortUpdates??=[];let Z=J.effortUpdates,W=(j)=>jI("sha256").update(q4(j)).digest("hex").slice(0,16);if(J.pinnedEffort===void 0||Z.some((j)=>!z||!kX(z[j.anchor],"user")||W(z[j.anchor])!==j.fingerprint)){J.pinnedEffort=Q,J.effortUpdates=[];return}if(!z||z.length===0)return;let B=z.findLastIndex((j)=>kX(j,"user")),H=Z.at(-1),U=H?.effort??J.pinnedEffort;if(B>=0&&Q!==U)if(H?.anchor===B){let j=Z.at(-2)?.effort??J.pinnedEffort;if(Q===j)Z.pop();else H.effort=Q}else Z.push({anchor:B,fingerprint:W(z[B]),effort:Q});else if(B<0&&Q!==U)return;if(Z.some((j,q)=>q>0&&j.anchor<=(Z[q-1]?.anchor??-1))){J.pinnedEffort=Q,J.effortUpdates=[];return}X.reasoning={...G,effort:J.pinnedEffort};for(let j=Z.length-1;j>=0;j--){let q=Z[j];if(!q)continue;z.splice(q.anchor,0,{type:"configuration_update",reasoning:{effort:q.effort}})}}function Jb(X){let J=s(X.reasoning)?{...X.reasoning}:{};J.context="all_turns",X.reasoning=J,X.parallel_tool_calls=!1;let $=qG(Array.isArray(X.input)?X.input:[]),G=[{type:"additional_tools",role:"developer",tools:Array.isArray(X.tools)?X.tools.filter((Q)=>!(s(Q)&&Q.type==="web_search")):[]}];if(typeof X.instructions==="string"&&X.instructions.length>0)G.push({type:"message",role:"developer",content:[{type:"input_text",text:X.instructions}]});X.input=[...G,...$],delete X.tools,delete X.instructions}function $b(X){if(!s(X))return X;if(X.type!=="function")return X;let J=s(X.parameters)&&"$schema"in X.parameters?(()=>{let{$schema:W,...B}=X.parameters;return B})():X.parameters,{type:$,name:Y,description:G,strict:Q,parameters:z,...Z}=X;return{type:$,name:Y,description:G,strict:Q??!1,parameters:J,...Z}}async function Yb(X,J={}){let $=J.codexApiEndpoint??u6().codexApiEndpoint,Y=crypto.randomUUID(),G=iI(),Q=()=>nI(G),z=!1,Z=!1,W=[],B=null,H=GH(X.client),U=new Map,j=new Map,q,K=!1,L,F=new Map,O,_,C=HV({host:"opencode",stateDir:J.vault?.stateDir??gW(M0(V0()).statePath),...X.directory?{projectRoot:X.directory}:{},reservedRouteIds:()=>i?.peek().rows.map((h)=>h.id)??[],...J.vault?.connectionFile?{connectionFile:J.vault.connectionFile}:{},...J.vault?.connectScoped?{connectScoped:J.vault.connectScoped}:{},...J.vault?.connectEnrollment?{connectEnrollment:J.vault.connectEnrollment}:{},...J.vault?.pollIntervalMs!==void 0?{pollIntervalMs:J.vault.pollIntervalMs}:{},fetchImpl:()=>fetch},M0(V0())),N=C.vault;await N.authority();let P=C.firstRoster,A=Promise.withResolvers(),T=Promise.race([P,A.promise]),b=J.vault?.firstRosterWaitMs??l$,p,i,{enabled:X0,...w}=J.poolMigration??{},J0=X0??cI;if(J0&&"reason"in H)(w.log??Z0("pool")).warn("account pool migration is off for this OpenCode client",{reason:H.reason});let G0=J0&&"slot"in H?pH({paths:()=>M0(V0()),slot:H.slot,version:S9,...w,runDeps:{vaultServes:()=>N.serves(),...w.runDeps},paused:async()=>await N.authority()!=="local",migrate:async(h)=>{let o=await(w.migrate??g7)(h);return i?.load(),o},adopt:async(h)=>{if(!await T3(T,b))return{status:"retry",reason:"vault-roster-pending"};let o=await(w.adopt??m7)(h);return i?.load(),o}}):void 0,L0=(h,o="")=>h?async()=>{let e=await h();return{url:e.url,instructions:e.instructions??o,method:"auto",callback:async()=>{try{let c=await e.tokens;return{type:"success",refresh:c.refresh_token,access:c.access_token,expires:Date.now()+(c.expires_in??3600)*1000,accountId:z8(c)}}finally{e.cleanup?.()}}}}:void 0,m=new h$(J.backgroundQuota),c0,m0=qH({client:X.client,getAuth:async()=>c0?.(),fetchImpl:fetch,dependencies:{...J.login?.authorize?{authorizeBrowser:L0(J.login.authorize.browser,"Complete authorization in your browser. This window will close automatically."),authorizeHeadless:L0(J.login.authorize.headless)}:{}},vault:N,onMainSlotWritten:async()=>{await G0?.requestAdoption()}}),r=(h)=>async(o)=>{let e=await h(o);if(e.method!=="auto")return e;return{...e,callback:async()=>{let c=await e.callback();if(c.type==="success"&&"refresh"in c)a(c.refresh);return c}}};async function a(h){if(!G0||!("slot"in H))return;let o=J.login?.sleep??((e)=>Bun.sleep(e));for(let e=0;e<5000;e+=100){try{let c=await H.slot.get({path:{id:"openai"}});if(s(c)&&c.refresh===h){await G0.requestAdoption();return}}catch{}await o(100)}}let u0=m0.map((h)=>h.type==="oauth"?{...h,authorize:r(h.authorize)}:h);async function t(h,o){let e=X.client.session;if(typeof e?.promptAsync==="function"){let c=await wV(X.client,h),D0={noReply:!0,parts:[{type:"text",text:o,ignored:!0}]};if(c?.agent)D0.agent=c.agent;if(c?.model)D0.model=c.model;if(c?.variant)D0.variant=c.variant;await e.promptAsync({path:{id:h},body:D0});return}}return{async dispose(){C.release(),G0?.dispose(),i?.dispose(),m.stop(),_?.stop(),q?.stopBackgroundRefresh(),q=void 0;for(let e of W)e.close();W.length=0;let h=globalThis;for(let[e,c]of U)if(h.__openaiAuthCacheKeepManagers?.get(e)===c)c.stop(),h.__openaiAuthCacheKeepManagers.delete(e);U.clear();for(let e of j.values())await e.release().catch(()=>{});j.clear();let o=p;p=void 0,await(await o)?.release()},async event(h){if(h.event.type!=="session.deleted")return;let o=h.event.properties.info,e=G.get(o.id);if(e)B?.cacheKeepManager?.remove(e.threadID);if(G.delete(o.id))Q();let c=m8(o.id);if(F.delete(c),_?.cancel(`pin:${c}`),L){let D0=(await b0(M0(V0())))?.accounts;await aN(o.id,D0,L).catch(()=>{})}for(let D0 of W)D0.remove(o.id)},provider:{id:"openai",async models(h,o){if(o.auth?.type!=="oauth")return h.models;let e=await b0(M0(V0())),c=!e||YW(e),D0=c?null:await IV();if(!c&&D0&&!vN)vN=!0,wN.debug("restoring OAuth model costs from models.dev catalog");if(!c&&!D0&&!yN)yN=!0,wN.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(h.models).filter(([,l0])=>l0.options.reasoningMode!=="pro"&&AI(l0.api.id)).map(([l0,d6])=>[l0,{...d6,cost:c?{input:0,output:0,cache:{read:0,write:0}}:D0?.[d6.api.id]??D0?.[l0]??d6.cost,limit:TI(d6.id)??d6.limit}]))}},auth:{provider:"openai",async loader(h){await N.authority(),c0=h,p??=ZV({version:S9,logger:Z0("heartbeat")}),await p,G0?.start();let o=await h();if(o.type!=="oauth")return A.resolve(),{};let e=O3(o).kind==="tombstone";C.start();let c=X.directory?await pN(X.directory):void 0,D0=c?.dir??V0();async function l0(D,M={}){if(await N.authority()!=="local")return;return uI(D,{...M,canWrite:()=>!N.enrolled()})}let d6=await N.authority()!=="local";if(!e&&!d6)await KW({type:"oauth",access:o.access??"",refresh:o.refresh??"",expires:o.expires??0},M0(V0()));let s0=await b0(M0(V0())).catch(async(D)=>{if(await N.authority()!=="local")return null;let M=V0();throw Error(`OpenAI auth store at ${M} is corrupt or unreadable: ${D instanceof Error?D.message:String(D)}. Fix or remove it to continue.`,{cause:D})});if(!d6&&await f7(M0(V0()),o)){if(G0)G0.noticePlaceholderWithoutMain();else if(!K)K=!0,Z0("pool-migration").warn(W4,{reason:"placeholder-without-main"})}let D6,v6=s0;async function p0(){let D=V0(),M;try{M=FI(D)}catch{M=void 0}if(M&&D6?.path===D&&D6.mtimeMs===M.mtimeMs&&D6.size===M.size)return D6.storage;if(!M)D6=void 0;let R=b0(M0(D)).catch(async(I)=>{if(await N.authority()!=="local")return v6;throw I}).then((I)=>{if(M)D6={path:D,mtimeMs:M.mtimeMs,size:M.size,storage:I};return v6=I,I});return e7(R,t7,()=>v6)}function N8(){D6=void 0}if(s0&&o.access&&!e&&!d6){let D=z8({id_token:"",access_token:o.access,refresh_token:o.refresh??""});if(D&&D!==s0.mainAccountId)await l0((M)=>{M.mainAccountId=D}),s0.mainAccountId=D,N8()}let O4=s0?.logging?.level;if(O4&&typeof O4==="string")s7(O4);let M4=Z0("transport"),e6=Z0("quota"),s3=Z0("refresh"),L8=Z0("accounts");M4.info("codex auth loader ready",{codexApiEndpoint:$,transport:u6().rawWebSocket?"raw-websocket":u6().webSockets?"websocket":"http"});let U0=new S8({storage:s0,configPath:V0(),fetchQuotaFn:void 0}),_4,A4=0;i?.dispose();let d0=new d$({paths:()=>M0(V0()),refreshProvider:async(D)=>{let M=await X3({refreshToken:D.refresh,fetchImpl:fetch,now:Date.now}),R=z8({id_token:"",access_token:M.access,refresh_token:M.refresh});return{...M,...R?{identity:R}:{}}},pullQuota:async(D)=>{let M=D.credential;if(M.type!=="oauth"||!M.access)throw Error("the row holds no access token to poll with");let R=await E8({accessToken:M.access,fetchImpl:fetch,now:Date.now,...D.identity?{accountId:D.identity}:{},accountKey:D.id,logger:e6}),I=Date.now(),S={quota:R,refreshAfter:I+300000,checkedAt:I};if(D.id==="main")U0.setMain(M.access,S,D.identity,!0);else U0.setFallback(D.id,S,M.access,!0,D.identity);return C9(R,I,!0)},vaultIdentities:()=>N.identities(),vaultMode:()=>N.enrolled(),vaultAuthority:()=>N.authority(),vaultFirstRoster:P,vaultFirstRosterBackgroundWaitMs:b,log:Z0("pool")});if(i=d0,!d6)await d0.load();let i6=new nJ({paths:M0(V0()),refreshFn:async(D)=>{if(await N.authority()!=="local")throw Error(N1["vault-refused"]);return X3({refreshToken:D.refreshToken,fetchImpl:D.fetchImpl,now:D.now})},quotaManager:U0,canWrite:()=>!N.enrolled(),onFallbackStorageChanged:N8,backgroundRefreshPaused:async()=>N.enrolled()||await d0.active()});if(s0&&s0.accounts.length>0)i6.startBackgroundRefresh();function wX(D){if(T0(D))return;return D.access||void 0}function a3(D={}){let{readSidebarState:M,respectBackoff:R,skipFresherThanMs:I}=D;return{getAuth:h,codexRefreshFn:X3,refreshMainWithLease:CG,fallbackManager:i6,quotaManager:U0,loadAccounts:b0,writeSidebarState:D8,client:X.client,fetchImpl:fetch,now:Date.now,paths:M0(V0()),readSidebarState:M??(()=>lN(E6)),storageMainAccountId:s0?.mainAccountId,isOAuthAccountFn:v0,whamFn:E8,...R===void 0?{}:{respectBackoff:R},...I===void 0?{}:{skipFresherThanMs:I}}}async function LG(D){return(await d0.pollRows(await b0(M0(V0())),D?{ids:D}:{})).map((R)=>({account:R.id,ok:R.ok,...R.error!==void 0?{error:R.error}:{}}))}async function DG(D){return d0.accessFor(D,await b0(M0(V0())))}let FG=Z0("cachekeep"),o3=q7(s0),PG=o3?.enabled===!0,OG=o3?.subagents===!0,MG=o3?.sustain===!0,_G=wH(s0?{...s0,cachekeep:o3}:s0),r3;async function QL(D){await new Promise((M)=>setTimeout(M,D))}async function zL(D){let M;for(let R=1;R<=xN;R++){if(await N.authority()!=="local")throw Error(N1["vault-refused"]);try{await X.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:D.refresh,access:D.access,expires:D.expires}});return}catch(I){if(M=I,R<xN)await QL(vI*R)}}throw new NG(M)}async function t3(D){await l0((M)=>{M.refresh=M.refresh??{},D(M)},{holdsMainRefreshLock:!0}),N8()}async function vX(D){let M=Date.now()+wI;while(Date.now()<M){await new Promise((S)=>setTimeout(S,kN+pI(kN)));let R=await h();if(R6(R))throw new q1;if(R.type!=="oauth"||!R.access)continue;if((R.access!==D.access||R.refresh!==D.refresh||(R.expires??0)>(D.expires??0)+60000)&&(!R.expires||R.expires>Date.now()))return s3.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:R.expires?R.expires-Date.now():void 0}),{access:R.access,refresh:R.refresh??D.refresh??"",expires:R.expires??0}}return null}function AG(D){if(R6(D))throw new q1;if(D.type!=="oauth")throw Error("not oauth");if(T0(D))throw new $1;if(!D.refresh)throw Error("Token refresh failed: missing refresh token");return D.refresh}async function yX(){if(!r3)r3=(async()=>{let D=await h(),M=AG(D);if(D.type!=="oauth")throw Error("not oauth");let R=Q8(M),I=await b0(M0(V0())),S=I?.refresh?.mainLastRefreshError;if(S&&t0(S,M,Date.now()))throw Error(r8(S,Date.now()));if(I?.refresh?.mainRefreshLeaseUntil&&I.refresh.mainRefreshLeaseUntil>Date.now()&&I.refresh.mainRefreshLeaseTokenHash===R){let d=await vX(D);if(d)return d;throw Error("Codex OAuth refresh is already in progress")}let f=await g0({name:h8,ttlMs:kI,path:V0(),renew:!0});if(!f){let d=await vX(D);if(d)return d;throw Error("Codex OAuth refresh is already in progress")}let k;try{let d=await h(),H0=AG(d);if(d.type!=="oauth")throw Error("not oauth");if(H0!==M){if(d.access&&(d.expires??0)>Date.now())return s3.debug("main token rotated while awaiting the lock",{pid:process.pid}),await f.release().catch(()=>{}),{access:d.access,refresh:H0,expires:d.expires??0};let Z6=(await b0(M0(V0())))?.refresh?.mainLastRefreshError;if(Z6&&t0(Z6,H0,Date.now()))throw Error(r8(Z6,Date.now()))}k={...d,refresh:H0}}catch(d){throw await f.release().catch(()=>{}),d}await uB(M0(V0()),k.refresh,k.access!==void 0?{slotAccess:k.access}:{}).catch(()=>!1);let v=Q8(k.refresh),n=crypto.randomUUID(),z0=v;try{await t3((F0)=>{if(mB(V0(),k.refresh))throw new y7;F0.refresh=F0.refresh??{},F0.refresh.mainRefreshLeaseId=n,F0.refresh.mainRefreshLeaseUntil=Date.now()+xI,F0.refresh.mainRefreshLeaseTokenHash=v});let d=await b0(M0(V0()));if(d?.refresh?.mainRefreshLeaseId!==n||d.refresh.mainRefreshLeaseTokenHash!==v)throw Error("Codex OAuth refresh is already in progress");if(await N.authority()!=="local")throw Error(N1["vault-refused"]);let H0=await X3({refreshToken:k.refresh,fetchImpl:fetch,now:Date.now});return await zL(H0),await t3((F0)=>{if(F0.refresh=F0.refresh??{},F0.refresh.mainLastRefreshError=void 0,F0.refresh.mainRefreshLeaseId===n)F0.refresh.mainRefreshLeaseId=void 0,F0.refresh.mainRefreshLeaseUntil=void 0,F0.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),z0=void 0,H0}catch(d){if(!(d instanceof y7)){if(!VG(d))await t3((H0)=>{H0.refresh=H0.refresh??{},H0.refresh.mainLastRefreshError=m1({error:d,now:Date.now(),refreshToken:k.refresh,previous:H0.refresh.mainLastRefreshError})}).catch(()=>{});throw d}}finally{if(z0)await t3((d)=>{if(d.refresh?.mainRefreshLeaseId===n&&d.refresh.mainRefreshLeaseTokenHash===z0)d.refresh.mainRefreshLeaseId=void 0,d.refresh.mainRefreshLeaseUntil=void 0,d.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await f.release().catch(()=>{})}let l=await vX(k);if(l)return l;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{r3=void 0});return r3}function TG(D){return QH({storage:D,now:Date.now,refreshAccount:(M,R)=>i6.refreshAccount(M,R,{asPoolMain:!0}),warn:(M,R)=>s3.warn(M,{pid:process.pid,...R})})}async function RG(){let D=await TG(await b0(M0(V0())));if(!D)throw Error("The main OpenAI account has no usable token in the account pool");return{access:D.token,refresh:D.account.refresh,expires:D.account.expires??0}}async function CG(){try{return await yX()}catch(D){if(D instanceof q1)return RG();throw D}}let EG=globalThis,hX=EG.__openaiAuthCacheKeepManagers??new Map;EG.__openaiAuthCacheKeepManagers=hX,hX.get(D0)?.stop();let T4=hH({fetchImpl:fetch,vault:N,getMainToken:async()=>{if(await N.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await d0.active()){let M=await DG("main");if(!M)throw Error("main pool row has no usable token");return M.token}let D=await h();if(await N.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(R6(D))return(await RG()).access;if(D.type!=="oauth")throw Error("not oauth");if(!D.access||(D.expires??0)<Date.now())try{return(await CG()).access}catch(M){if(VG(M))throw M;if(D.access)return D.access;throw Error("main token refresh failed")}return D.access},refreshFallback:async(D)=>{if(await N.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await d0.active()){let k=await DG(D);if(!k)throw Error(`no access token for ${D}`);return{token:k.token}}let M=await p0(),R=M?rI(M.accounts,D):void 0;if(!R)throw Error(`fallback account ${D} not found`);let I=M??{version:1,accounts:[R]},S=T0(R)?R:await i6.refreshAccount(R,I),f=wX(S);if(!f)throw Error(`no access token for ${D}`);return{token:f}},codexResponsesUrl:$,activeAccount:async(D)=>yH(T1(await f9.read(),F),D),logger:FG,now:Date.now,getWindow:()=>_G,getSustain:()=>MG});hX.set(D0,T4),U.set(D0,T4);function R1(D,M,R,I,S=!1){try{ZL(D,M,R,I,S)}catch(f){e6.warn("quota push failed",{pid:process.pid,accountId:R??"main",error:n0(f)})}}function ZL(D,M,R,I,S){if(Object.keys(D).length===0&&!S)return;let f=Date.now(),k=D,v={quota:k,refreshAfter:f+300000,checkedAt:f},n;if(R&&R!=="main"){let l=M?H6(M):null,d=l?V6(l):void 0,H0=U0.peekFallbackForPolicy(R)?.quota,F0=fN(k,H0);v={...v,quota:F0},U0.setFallback(R,v,M,S,d)}else{if(n=I,!n&&M){let H0=H6(M);n=H0?V6(H0):void 0}if(n&&_4&&n!==_4){e6.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:n,currentMainIdentity:_4});return}let l=U0.peekMainForPolicy(n)?.quota,d=fN(k,l);v={...v,quota:d},U0.setMain(M,v,n,S)}e6.debug("quota pushed",{pid:process.pid,accountId:R??"main",snapshot:v.quota}),d0.recordSnapshot(R&&R!=="main"?R:"main",D,M,S);let z0=Boolean(R&&R!=="main");p8.enqueue("machine-state","quota",()=>{let l=v6;return D8(U0,l,z0?l?.mainAccountId:n)})}function WL(D,M,R){let I=b8(N.routes().find((S)=>S.id===D)?.quota)??(D==="main"?U0.peekMainForPolicy()?.quota:U0.peekFallbackForPolicy(D)?.quota);return nZ(I,M,Date.now(),yI,R)}let e3=new Map,R4=new Map;function SG(){if(!N.enrolled())return;p8.enqueue("machine-state","quota",()=>D8(U0,v6))}let C1=J.experimentalWebSockets?U9.createWebSocketFetch({httpFetch:fetch,rawWebSocket:u6().rawWebSocket,onQuota:(D,M,R,I)=>{let S=R?e3.get(R):void 0;if(S){N.recordSnapshot(S.id,D,!0,S.receipt).then(SG);return}R1(D,M,R,!R||R==="main"?I:void 0,!0)},onRateLimitReached:(D,M,R)=>{if(!M)e6.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:D});let I=M?e3.get(M):void 0,S=I?.id??M??"main",f=WL(S,D,R);if(U0.markRateLimited(S,f),I)R4.set(S,Math.max(R4.get(S)??0,f));else d0.markRateLimited(S,f);e6.debug("mid-stream rate limit mark",{pid:process.pid,accountId:S,window:D})}}):void 0;if(C1)W.push(C1),z=!0;let E6=cN();L=E6;async function D8(D,M,R=M?.mainAccountId){if(N.enrolled()){await SX(JV(N.snapshot()?.rows??[],new Set(N.routes().map((S)=>S.id)),M,Date.now()),E6,{canWrite:()=>N.enrolled()});return}let I=await d0.current();if(I.active){await SX($V(I.rows,M,Date.now(),(S)=>(S==="main"?D.getMain():D.getFallback(S))?.quota?.resetCreditsAvailable),E6,{canWrite:()=>!N.enrolled()});return}if(!M)return;await SX(GL(D,M,Date.now(),R),E6,{canWrite:()=>!N.enrolled()})}let f9=eN(E6);f9.read(),_?.stop();let p8=JL({logger:M4,onWritten:()=>f9.refreshInBackground()});if(_=p8,O!==E6)F.clear(),O=E6;function fX(D,M,R,I,S,f,k=!1){let v={canWrite:()=>N.enrolled()===k},n={activeId:R,route:I,updatedAt:Date.now()};if(!D){p8.enqueue("routing:legacy","routing",()=>sN(n,E6,v));return}if(p8.enqueue(`routing:${D}`,"routing",()=>IX({sessionId:D,...n},S,E6,v)),!M||M===D)return;if(I==="sticky-balanced"){let z0=f.stickyAssignments?.[m8(M)]?.accountId,l=S===void 0||z0==="main"||S.some((d)=>d.enabled!==!1&&d.id===z0);if(!z0||!l)return;p8.enqueue(`routing:${M}`,"routing",()=>IX({sessionId:M,activeId:z0,route:I,updatedAt:Date.now()},S,E6,v));return}p8.enqueue(`routing:${M}`,"routing",()=>IX({sessionId:M,...n},S,E6,v))}q?.stopBackgroundRefresh(),q=i6;let C4=M0(V0());if(B=$L={accountStoragePath:C4.configPath,accountStatePath:C4.statePath,packageVersion:S9,quotaManager:U0,loadAccounts:b0,beginAccountLogin:I2,store:()=>Z4(C4),migration:async()=>{if(await p7(C4,Z4(C4))!==void 0)return{migrated:!0};let D=await(w.fence??(()=>H4({currentVersion:S9})))();return{migrated:!1,blockers:D.open?[]:D.blockers.map((M)=>({pid:M.pid,version:M.version}))}},afterWrite:()=>d0.load(),vault:N,resolveResetTarget:gI({getAuth:h,refreshMainWithLease:yX,refreshFallbackAccount:(D,M)=>i6.refreshAccount(D,M),refreshPoolMainRow:(D,M)=>i6.refreshAccount(D,M,{asPoolMain:!0}),poolAccess:async(D)=>d0.rowAccess(D,await b0(M0(V0()))),loadAccounts:b0,accountStoragePath:V0(),accountStatePath:A$(V0()),now:Date.now}),...mI(),cacheKeepManager:T4,setCacheKeepEnabled:(D)=>{PG=D},setCacheKeepSubagents:(D)=>{OG=D},setCacheKeepSustain:(D)=>{MG=D},setCacheKeepWindow:(D)=>{_G=D},clearStickyRouting:async(D)=>{let M=m8(D),R=F.delete(M);return p8.cancel(`pin:${M}`),await tN(D,E6)||R},getStickyRouting:async(D)=>nN(T1(await f9.read(),F),D),refreshSidebar:async()=>{let D=await b0(M0(V0()));await D8(U0,D)},refreshAllQuota:async()=>{if(await N.authority(),N.enrolled()){let D=await N.pollStale(0);return await D8(U0,v6),D.map((M)=>({account:M.id,ok:M.ok,...M.error!==void 0?{error:M.error}:{}}))}if(await d0.active()){let[D,M]=await Promise.all([LG(),N.pollStale(0)]);return await D8(U0,v6),[...D,...M.map((R)=>({account:R.id,ok:R.ok,...R.error!==void 0?{error:R.error}:{}}))]}return J4(a3())},refreshResetTargetQuota:async(D)=>{if(await N.authority(),N.enrolled())return{account:D,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};if(await d0.active()){let[R]=await LG([D]);return R??{account:D,ok:!1,error:"targeted quota refresh returned no result"}}return(await J4(a3({respectBackoff:!1}),{accountKey:D})).find((R)=>R.account===D)??{account:D,ok:!1,error:"targeted quota refresh returned no result"}}},c){let D=c;try{let M=await uN(yV,D.dir,()=>hV({dir:D.dir,secureDir:D.secureDir,sweepRoot:D.sweepRoot,drain:PH,apply:async(R)=>{let I=_5(R);if(!I)throw Error("not an /openai apply request");return RH(B,I)}}));j.set(D.dir,M)}catch{}}async function E1(D,M,R,I,S="main",f){if(!R.trim())throw M4.warn("refusing to send a request with no access token",{account:S,accountId:I}),Error(RI);if(!f&&await N.authority()!=="local")return Response.json({error:{message:N1["vault-refused"]}},{status:400});let k=gN(D,M);if(k.delete("x-api-key"),k.delete("api-key"),k.set("authorization",`Bearer ${R}`),I)k.set("ChatGPT-Account-Id",I);k.set(U9.QUOTA_ACCOUNT_HEADER,S);let v=mN(k),n=v?dI(G,v,Q):void 0,z0=D instanceof URL?D:new URL(typeof D==="string"?D:D.url),l=z0.pathname.includes("/v1/responses")||z0.pathname.includes("/chat/completions")?new URL($):z0,H0=oI({init:{...M,headers:k},headers:k,metadata:n,installationID:Y,websocket:Boolean(C1&&z0.pathname.endsWith("/responses")),responsesLite:J.responsesLite??!1,dumpSessionID:v}).init,F0=PG,Z6=new Headers(H0?.headers),W0=xH({enabled:F0,includeSubagents:OG,headers:Z6,body:H0?.body});if(F0)FG.trace("cachekeep headers",{pid:process.pid,hasParent:Z6.has("x-parent-session-id"),sessionKey:W0?.sessionKey,captured:Boolean(W0),affinity:Z6.get("x-session-affinity"),opencodeSession:Z6.get("x-opencode-session"),sessionId:Z6.get("session-id")});if(C1&&z0.pathname.endsWith("/responses")){if(M4.debug("WS transport",{pid:process.pid,pathname:z0.pathname,accountId:S}),W0)T4.track({sessionKey:W0.sessionKey,bodyText:W0.bodyText,accountId:S,isSubagent:W0.isSubagent,meta:{replayHeaders:W0.replayHeaders,chatgptAccountId:I,routingSessionId:v}});if(!f)try{return await q3(await C1(l,H0),R)}catch(i0){throw U1(i0,R)}let P0=`vault-stream:${qI()}`;e3.set(P0,{id:S,receipt:f});let F8=new Headers(H0?.headers);F8.set(U9.QUOTA_ACCOUNT_HEADER,P0);let F6=()=>e3.delete(P0);try{let i0=await C1(l,{...H0,headers:F8});if(!i0.body)return F6(),i0;let c8=i0.body.getReader();return await q3(new Response(new ReadableStream({async pull(l8){try{let d8=await c8.read();if(d8.done)F6(),l8.close();else l8.enqueue(d8.value)}catch(d8){F6(),l8.error(U1(d8,R))}},cancel(l8){return F6(),c8.cancel(l8)}}),{status:i0.status,statusText:i0.statusText,headers:i0.headers}),R)}catch(i0){throw F6(),U1(i0,R)}}let R0=U9.withoutInternalHeaders(H0);if(typeof R0?.body!=="string")try{return await q3(await fetch(l,R0),R)}catch(P0){throw U1(P0,R)}if(W0)T4.track({sessionKey:W0.sessionKey,bodyText:W0.bodyText,accountId:S,isSubagent:W0.isSubagent,meta:{replayHeaders:W0.replayHeaders,chatgptAccountId:I,routingSessionId:v}});M4.debug("HTTP transport",{pid:process.pid,pathname:z0.pathname,accountId:S});try{let P0=await fetch(l,R0);return await U4({sessionID:v,transport:"http",phase:"http",bodyText:R0.body,accountId:S,url:l.toString(),method:R0.method,headers:R0.headers,status:P0.status}),await q3(P0,R)}catch(P0){throw await U4({sessionID:v,transport:"http",phase:"http",bodyText:R0.body,accountId:S,url:l.toString(),method:R0.method,headers:R0.headers,error:P0 instanceof Error?P0.message:String(P0)}),U1(P0,R)}}function E4(D,M){if((M?.method??(D instanceof Request?D.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof M?.body!=="string")return!1;try{let I=D instanceof URL?D.toString():typeof D==="string"?D:D.url;return new URL(I).pathname.endsWith("/responses")}catch{return!1}}function BL(D){return U0.peekMainForPolicy(D)?.quota}function IG(D,M){for(let R of[D?.primary?.checkedAt,D?.secondary?.checkedAt,D?.checkedAt,M])if(typeof R==="number"&&Number.isFinite(R))return R;return}function S4(D,M,R,I,S){let f=IG(D,M),k=IG(R),v=I===S&&R!=null&&(D===void 0||k!==void 0&&(f===void 0||k>f));return{quota:v?R:D,quotaCheckedAt:v?k:f,source:v?"file":"memory"}}function bG(D,M,R,I,S){let f=D?.quota,k=S4(f,D?.checkedAt,M,I,S),v=k.source,n=k.quota;if(!iN(n,R))return{exhausted:!1};let z0=dN(n,R);if(!z0)return{exhausted:!1};return{exhausted:!0,source:v,...z0}}function kG(D,M){e6.debug("admission skip: exhausted account",{accountId:D,source:M.source,resetsAt:M.resetsAt})}function xG(D,M="killswitch",R,I){let S=Date.now(),f=I?I.main:U0.getMain()?.quota,k=I?I.fallbacks:(D?.accounts??[]).filter((d)=>d.enabled!==!1&&v0(d)).map((d)=>({accountId:d.id,quota:U0.getFallback(d.id)?.quota})),v=UW(f,k,S,D);if(M==="quota-unknown")v=lH;else if(M==="quota-exhausted"&&R!==void 0)v=Math.max(1,Math.ceil((R-S)/1000));else if(M==="mid-stream-rate-limit"&&R!==void 0){let d=Math.max(1,Math.ceil((R-S)/1000));v=Math.min(v,d)}let n=Math.floor(v/60),z0=v%60,l=M==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${n}m ${z0}s.`:M==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${n}m ${z0}s.`:M==="quota-unknown"?`OpenAI quota is not known yet for any available account; checking it now. Retry in ${n}m ${z0}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${n}m ${z0}s.`;return new Response(JSON.stringify({error:{message:l,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(v)}})}function gX(D){let M=D?.resetCreditsAvailable;return typeof M==="number"&&Number.isFinite(M)?M:void 0}async function HL(D){let M=Y9(D.storage),R=Date.now(),I=U0.peekMainForPolicy(D.mainAccountIdentity),S=S4(I?.quota,I?.checkedAt,D.sidebarState.main.quota,D.sidebarState.main.mainAccountId,D.mainAccountIdentity),f=M?Q1(I?.quota,D.storage,void 0,R):void 0,k=D.mainUnavailable?[]:[{accountId:"main",wireAccountId:D.mainAccountIdentity,access:D.primaryAccess,keepwarmAccountKey:"main",quota:S.quota,quotaCheckedAt:S.quotaCheckedAt,reservePercent:n6(D.storage),configuredOrder:0,resetCreditsApplicable:gX(S.quota),killswitchPasses:f}],v=await i6.getUsableFallbackAccounts(D.storage);if(!D.storage)return k;for(let n of v){let z0=wX(n);if(!z0)continue;let l=D.sidebarState.fallbacks.find((Z6)=>Z6.id===n.id),d=U0.peekFallbackForPolicy(n.id,n.accountId),H0=S4(d?.quota,d?.checkedAt,l?.quota,l?.accountId,n.accountId),F0=M?Q1(d?.quota,D.storage,n.id,R):void 0;k.push({accountId:n.id,wireAccountId:n.accountId,access:z0,keepwarmAccountKey:n.id,fallback:n,quota:H0.quota,quotaCheckedAt:H0.quotaCheckedAt,reservePercent:n6(D.storage,n.id),configuredOrder:k.length,resetCreditsApplicable:gX(H0.quota),killswitchPasses:F0})}return k}function wG(D,M,R,I,S){let f=Y9(S)?D.killswitchPasses:void 0;if(D.accountId==="main"){let z0=U0.peekMainForPolicy(D.wireAccountId),l=S4(z0?.quota,z0?.checkedAt,M.main.quota,M.main.mainAccountId,D.wireAccountId);return $Y({quota:l.quota,quotaCheckedAt:l.quotaCheckedAt,status:R,now:I,killswitchPasses:f})}let k=M.fallbacks.find((z0)=>z0.id===D.accountId),v=U0.peekFallbackForPolicy(D.accountId,D.wireAccountId),n=S4(v?.quota,v?.checkedAt,k?.quota,k?.accountId,D.wireAccountId);return $Y({quota:n.quota,quotaCheckedAt:n.quotaCheckedAt,status:R,now:I,killswitchPasses:f})}function VL(D){return D.accountId==="main"?"main":D.keepwarmAccountKey}function vG(D){return U0.isRateLimited(VL(D))}function mX(D){let M=D.candidates.filter((f)=>!vG(f)),R=new Map(M.map((f)=>[f.accountId,f])),I=new Set(D.excludeAccountIds),S=yG({sessionId:D.sessionId,requestBytes:D.requestBytes,sidebarSnapshot:D.sidebarSnapshot,now:D.now,validPinnedAccountIds:[...R.keys()],excludeAccountIds:D.excludeAccountIds??[],quotaCheckedAtByAccount:Object.fromEntries(M.map((f)=>[f.accountId,f.quotaCheckedAt])),wireAccountIdByAccount:Object.fromEntries(M.map((f)=>[f.accountId,f.wireAccountId])),select:(f)=>{let k=M.filter((v)=>!I.has(v.accountId));if(k.length===0)return;return NV({candidates:k,pendingBytes:f,requestBytes:D.requestBytes,now:D.now,onEmptyWeightedSet:()=>{L8.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return S?R.get(S.accountId):void 0}function yG(D){let M=void 0,R=D.validPinnedAccountIds,I=oN(T1(D.sidebarSnapshot,F),{sessionId:D.sessionId,requestBytes:D.requestBytes,now:D.now,validPinnedAccountIds:R,excludeAccountIds:D.excludeAccountIds,quotaCheckedAtByAccount:D.quotaCheckedAtByAccount,wireAccountIdByAccount:D.wireAccountIdByAccount,choose:(f)=>{let k=D.select(f);if(!k)return;return M={accountId:k.accountId,source:k.source,pendingBytes:f.get(k.accountId)??0},k}}),S=I.assignment;if(!D.persist)return S;if(M&&S?.accountId===M.accountId)L8.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:m8(D.sessionId),accountId:M.accountId,source:M.source,requestBytes:D.requestBytes,pendingBytes:M.pendingBytes});if(S&&I.next!==void 0){let f=m8(D.sessionId),k=XL(F,f,S);p8.enqueue(`pin:${f}`,"sticky-pin",async()=>{await rN({sessionId:D.sessionId,assignment:S,validPinnedAccountIds:R},E6),k.persistedAt=Date.now()})}return S}async function UL(D,M){let R=await i6.getUsableFallbackAccounts(D),I=[];if(!D)return{current:[],retained:[],skipped:[]};for(let l of R){let d=wX(l);if(!d)continue;I.push({access:d,accountId:l.accountId,keepwarmAccountKey:l.id,quotaAccountId:l.id,fallback:l})}let S=I.filter((l)=>!U0.isRateLimited(l.quotaAccountId)),f=Y9(D)?S.filter((l)=>Q1(U0.peekFallbackForPolicy(l.quotaAccountId,l.accountId)?.quota,D,l.quotaAccountId,Date.now())):S,k=new Map(M.fallbacks.map((l)=>[l.id,{quota:l.quota,accountId:l.accountId}])),v=[],n=[],z0=Date.now();for(let l of f){let d=k.get(l.quotaAccountId),H0=bG(U0.peekFallbackForPolicy(l.quotaAccountId,l.accountId),d?.quota,z0,d?.accountId,l.accountId);if(H0.exhausted)n.push({candidate:l,decision:H0});else v.push(l)}return{current:f,retained:v,skipped:n}}function hG(D,M){if(D.retained.length===0&&!M)return D.current;for(let{candidate:R,decision:I}of D.skipped)kG(R.quotaAccountId,I);return D.retained}function fG(D,M){try{let R=s9(D.headers);R1(R,M.access,M.quotaAccountId,void 0,c1(D.headers))}catch{}}async function KL(D,M,R,I){for(let S of I){let f;try{f=await E1(D,M,S.access,S.accountId,S.keepwarmAccountKey)}catch(k){if(k instanceof DOMException&&k.name==="AbortError")throw k;if(M?.signal?.aborted)throw k;throw L8.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:S.quotaAccountId}),k}if(!z3(f.status,R))return i6.markUsed(S.fallback),{response:f,accessToken:S.access,quotaAccountId:S.quotaAccountId,activeId:S.keepwarmAccountKey};fG(f,S),f.body?.cancel().catch(()=>{})}return}async function jL(D,M,R,I,S){if(!E4(D,M))return{response:R};if(!S.length)return{response:R};let f=R,k;for(let v of S){let n;try{n=await E1(D,M,v.access,v.accountId,v.keepwarmAccountKey)}catch(z0){if(z0 instanceof DOMException&&z0.name==="AbortError")throw z0;if(M?.signal?.aborted)throw z0;return L8.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:v.quotaAccountId}),{response:f,...k}}if(f.body?.cancel().catch(()=>{}),f=n,k={accessToken:v.access,accountId:v.quotaAccountId},!z3(n.status,I))return i6.markUsed(v.fallback),{response:n,...k};fG(n,v)}return{response:f,...k}}if(s0){let D=[];for(let M of s0.accounts)if(v0(M))D.push(M);U0.seedFallbacksFromAccounts(D)}if(!jG)if(jG=!0,D8(U0,s0).catch(()=>{}),P.then(()=>N.enrolled()?D8(U0,v6):void 0).catch(()=>{}),!N.enrolled()&&!await d0.active())bX=J4(a3({respectBackoff:!0})).catch((D)=>e6.warn("boot quota seed failed",{pid:process.pid,error:n0(D)}));else bX=Promise.resolve();m.start(async()=>{if(await N.authority(),N.enrolled()){await D8(U0,v6);return}if(await d0.active()){let R=await bH(d0,await b0(M0(V0())),()=>y$(V0()));if(R.length>0)await D8(U0,v6);let I=R.filter((S)=>!S.ok);if(I.length>0)e6.warn("background pool quota poll completed with failures",{pid:process.pid,failures:I});return}let M=(await SH(a3({readSidebarState:async()=>(await f9.read()).state}))).filter((R)=>!R.ok);if(M.length>0)e6.warn("background quota refresh completed with failures",{pid:process.pid,failures:M})},(D)=>{e6.warn("background quota refresh failed",{pid:process.pid,error:D instanceof Error?D.message:String(D)})});async function uX(D,M,R,I,S,f){let k=R?.routing?.mode??"main-first",v=N.enrolled(),n=v?void 0:d0.peek().rows.find((W0)=>W0.id==="main"),z0=!n&&!v?await h():void 0,l=!n&&z0?.type==="oauth"&&T0(z0),d=!n&&!v&&await f7(M0(V0()),z0);if(f===A4)_4=n?.identity;let H0=await f9.get(),{response:F0,servedId:Z6}=await XV({source:d0,...v?{vault:{routes:()=>N.routes(),awaitRoster:async()=>{await T3(P,c$)},noRouteCause:()=>uW(N),send:(W0,R0)=>N.send(W0,R0,{site:"model",...M?.signal?{signal:M.signal}:{}}),requestReading:(W0)=>N.requestReading(W0),rateLimitMarks:()=>{for(let[W0,R0]of R4)if(R0<=Date.now())R4.delete(W0);return R4}}}:{},storage:R,mode:k,sessionId:I,body:typeof M?.body==="string"?M.body:void 0,replayable:E4(D,M),now:Date.now,send:(W0,R0,P0)=>E1(D,M,R0,W0.identity,W0.id,P0),recordQuota:(W0,R0,P0,F8)=>{try{let F6=s9(W0.headers),i0=c1(W0.headers);if(!R0.row){if(F8)N.recordSnapshot(R0.id,F6,i0,F8).then(SG);return}R1(F6,P0,R0.id==="main"?void 0:R0.id,R0.id==="main"?R0.identity:void 0,i0)}catch{}},placePin:(W0)=>yG({...W0,sidebarSnapshot:H0}),blocked:(W0,R0,P0)=>{if(W0.reason==="no-credential"){if(d&&!r$(P0))throw Error(W4);return new Response(N1[r$(P0)?P0:l?"missing-main":P0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return xG(R,W0.reason,W0.resetAtMs,R0)},resetCredits:(W0)=>gX(W0==="main"?U0.peekMainForPolicy(n?.identity)?.quota:U0.peekFallbackForPolicy(W0)?.quota),isAbort:(W0)=>W0 instanceof DOMException&&W0.name==="AbortError"||Boolean(M?.signal?.aborted),log:L8});return fX(I,S,Z6,k,v?N.routes().map((W0)=>({id:W0.id})):R?.accounts,T1(H0,F),v),F0}return Z=!0,{apiKey:EI,async fetch(D,M){let R=await N.authority(),I=gN(D,M),S=mN(I),f=I.get("x-parent-session-id")?.trim()||void 0,k=await p0();if(R!=="local")return M=await UG(D,M),uX(D,M,k,S,f,++A4);let v=await h();if(await N.authority()!=="local")return M=await UG(D,M),uX(D,M,k,S,f,++A4);let n=++A4;if(v.type!=="oauth")return I.delete(xX),fetch(D,{...M,headers:I});M=await UG(D,M);let z0=(await d0.current()).active;if(R6(v)&&z0)return uX(D,M,k,S,f,n);if(z0)N.assertHostSlot(v);let l="",d=!1,H0,F0=R6(v);if(G0?.migrated()&&!F0&&v.refresh?.trim()&&O3(v).kind==="real")G0.noticeRealSlot(v.refresh);let Z6=async(C0=k)=>{if(F0=!0,H0=await TG(C0),H0)l=H0.token;else l="",d=!0,L8.warn("main account in the pool has no usable token",{pid:process.pid})};if(F0)await Z6();else if(T0(v))d=!0;else{if(!v.access||(v.expires??0)<Date.now()){s3.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(v.access),expiresInMs:v.expires?v.expires-Date.now():void 0});try{let C0=await yX();v.access=C0.access,v.refresh=C0.refresh,v.expires=C0.expires}catch(C0){if(VG(C0))throw C0;if(C0 instanceof q1)await Z6(await b0(M0(V0())))}}if(!F0)l=v.access??""}let W0=F0?lJ(k):k,R0=v,P0=H0?.account.accountId??(F0?void 0:R0.accountId)??(l?V6(H6(l)??{}):void 0);if(n===A4)_4=P0;let F8=k?.routing?.mode??"main-first",F6=await f9.get(),i0=F6.state;if(F8==="sticky-balanced"&&S&&E4(D,M)&&typeof M?.body==="string"){let C0=Buffer.byteLength(M.body,"utf8"),J6=await HL({storage:W0,sidebarState:i0,primaryAccess:l,mainAccountIdentity:P0,mainUnavailable:d}),r0=mX({sessionId:S,requestBytes:C0,candidates:J6,sidebarSnapshot:F6,now:Date.now()});if(r0){let lG=vG(r0)?{action:"migrate",reason:"exhausted"}:wG(r0,i0,void 0,Date.now(),k);if(lG.action==="migrate"){let y6=mX({sessionId:S,requestBytes:C0,candidates:J6,sidebarSnapshot:F6,excludeAccountIds:[r0.accountId],now:Date.now()});if(y6)L8.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:m8(S),fromAccountId:r0.accountId,toAccountId:y6.accountId,reason:lG.reason}),r0=y6}let P8=await E1(D,M,r0.access,r0.wireAccountId,r0.keepwarmAccountKey),dG=(y6,g9)=>{try{let qL=s9(y6.headers);R1(qL,g9.access,g9.accountId==="main"?void 0:g9.accountId,g9.accountId==="main"?g9.wireAccountId:void 0,c1(y6.headers))}catch{}};dG(P8,r0);let iG=wG(r0,i0,P8.status,Date.now(),k);if((P8.status===401||P8.status===403||P8.status===429)&&iG.action==="migrate"){let y6=mX({sessionId:S,requestBytes:C0,candidates:J6,sidebarSnapshot:F6,excludeAccountIds:[r0.accountId],now:Date.now()});if(y6){L8.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:m8(S),fromAccountId:r0.accountId,toAccountId:y6.accountId,reason:iG.reason});let g9=P8;P8=await E1(D,M,y6.access,y6.wireAccountId,y6.keepwarmAccountKey),g9.body?.cancel().catch(()=>{}),r0=y6,dG(P8,r0)}}if(r0.fallback&&!z3(P8.status,k))i6.markUsed(r0.fallback);return fX(S,f,r0.accountId,F8,k?.accounts,T1(F6,F)),P8}}let c8=bG(U0.peekMainForPolicy(P0),i0.main.quota,Date.now(),i0.main.mainAccountId,P0),l8=Y9(k)&&!Q1(BL(P0),k,void 0,Date.now()),d8=U0.isRateLimited("main"),gG,pX=()=>{return gG??=UL(W0,i0),gG},i8,S1,mG=!1,X2;if(F8==="fallback-first"&&E4(D,M)){mG=!0;let C0=await pX();X2=hG(C0,!l8&&!d8&&!c8.exhausted);let J6=await KL(D,M,k,X2);if(J6)i8=J6.response,S1={accessToken:J6.accessToken,accountId:J6.quotaAccountId,activeId:J6.activeId}}if(!i8){let C0=c8.exhausted&&E4(D,M)&&(await pX()).retained.length>0;if(l8||d8||C0){let J6=l8?"killswitch":d8?"mid-stream-rate-limit":"quota-exhausted";if(J6==="quota-exhausted"&&c8.exhausted)kG("main",c8);L8.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:J6}),i8=xG(k,J6,J6==="quota-exhausted"&&c8.exhausted?c8.resetAtMs:d8?U0.rateLimitedUntil("main"):void 0)}else i8=d?new Response(null,{status:401}):await E1(D,M,l,P0,"main")}let cX=Boolean(S1),I4=i8,uG=S1?.accessToken??l,pG=S1?.accountId,cG=S1?.activeId??"main";if(!S1&&!mG&&z3(i8.status,k)){L8.debug("reactive fallback triggered",{pid:process.pid,status:i8.status}),X2??=hG(await pX(),!1);let C0=await jL(D,M,i8,k,X2),J6=C0.response;if(J6!==i8){if(cX=!0,I4=J6,uG=C0.accessToken??l,pG=C0.accountId,C0.accountId)cG=C0.accountId}}if(F0&&d&&!cX&&await f7(M0(V0()),await h()))throw Error(W4);try{let C0=s9(I4.headers);if(cX)R1(C0,uG,pG,void 0,c1(I4.headers));else R1(C0,l,void 0,P0,c1(I4.headers))}catch{}return fX(S,f,cG,F8,k?.accounts,T1(F6,F)),I4}}},methods:u0},"chat.headers":async(h,o)=>{if(h.model.providerID!=="openai")return;if(o.headers.originator="opencode",o.headers["User-Agent"]=`${E2(S9)} (${BG.platform()} ${BG.release()}; ${BG.arch()})`,o.headers["session-id"]=h.sessionID,Z)o.headers[xX]=h.agent;if(z&&h.agent==="title")o.headers[U9.TITLE_HEADER]="true"},"chat.params":async(h,o)=>{if(h.model.providerID!=="openai")return;o.maxOutputTokens=void 0},config:async(h)=>{Z0("commands").info("registering commands",{existing:Object.keys(h.command??{}).length,pid:process.pid}),h.command={...h.command??{},[m6]:{template:m6,description:"OpenAI accounts: quota, routing, limits, cache keep-warm, diagnostics and reset credits."}}},"command.execute.before":async(h)=>{if(Z0("commands").info("command hook entered",{command:h.command,hasCmdCtx:B!==null,pid:process.pid}),h.command!==m6)return;if(!B)Z0("commands").warn("command rejected: context not loaded",{command:h.command,pid:process.pid}),await t(h.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),hN();let o=await TH(B,h.sessionID);if(OH(h.sessionID))i7(o,h.sessionID);else await t(h.sessionID,CH(o.menu));hN()}}}var Gb=async(X)=>{let J=u6();return Yb(X,{codexApiEndpoint:J.codexApiEndpoint,experimentalWebSockets:J.webSockets,responsesLite:J.responsesLite})},ei={id:"cortexkit-openai-auth",server:Gb};
221
- export{sX as c,LL as d,H6 as e,V6 as f,z8 as g,I2 as h,s9 as i,c1 as j,Oz as k,r4 as l,T0 as m,X3 as n,E8 as o,nZ as p,b0 as q,Z3 as r,Y9 as s,n6 as t,Q1 as u,V8 as v,C9 as w,b8 as x,gW as y,eJ as z,uW as A,R7 as B,$4 as C,U1 as D,jM as E,q3 as F,V0 as G,u6 as H,M0 as I,kM as J,f7 as K,g7 as L,m7 as M,y8 as N,z4 as O,u7 as P,k$ as Q,W4 as R,H4 as S,S9 as T,c$ as U,l$ as V,T3 as W,d$ as X,pH as Y,p6 as Z,dH as _,nH as $,s$ as aa,aH as ba,oH as ca,KA as da,ZV as ea,HV as fa,i3 as ga,jN as ha,MI as ia,_I as ja,AI as ka,TI as la,RI as ma,CI as na,KG as oa,II as pa,si as qa,kI as ra,xI as sa,ai as ta,oi as ua,NG as va,L6 as wa,gI as xa,mI as ya,ri as za,cI as Aa,rI as Ba,fN as Ca,GL as Da,ti as Ea,mN as Fa,tI as Ga,Jb as Ha,Yb as Ia,Gb as Ja,ei as Ka};