@cortexkit/opencode-openai-auth 1.0.2 → 1.0.3

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,4 +1,4 @@
1
- import{Ab as $X,Bb as YX,Cb as BL,Db as HL,Eb as C1,Fb as VL,La as tG,Ma as eG,Na as G6,Oa as B7,Pa as m8,Qa as Vz,Ra as A7,Sa as T8,Ta as f0,Ua as G2,Va as XQ,Wa as sX,Ya as QY,_a as pH,ab as p8,bb as eN,eb as XL,ib as AV,jb as JL,kb as $L,lb as YL,qb as xX,rb as wX,sb as GL,tb as QL,wb as zL,xb as ZL,yb as WL}from"./index-eqh53k8v.js";import{Kb as _Q,Lb as M6,Mb as AQ,Nb as q5,Ob as g0,Pb as W2,Qb as TQ,Rb as lZ}from"./index-jyr8y8k4.js";import{Tb as RH,Ub as CH,Vb as EH,Wb as dV,Xb as rN,Yb as s7}from"./index-rv08jmd4.js";import{dc as T2,ec as t7,gc as Z0,hc as yB,jc as uJ,kc as pJ,lc as e0,nc as AH}from"./index-bmd7x5aq.js";import{pc as SH,rc as tN}from"./index-766sfrh5.js";import{uc as DY}from"./index-b3q3j39x.js";import{createHash as mI,randomUUID as uI}from"node:crypto";import{mkdirSync as pI,readFileSync as cI,renameSync as lI,statSync as dI,writeFileSync as iI}from"node:fs";import jG from"node:os";import{join as nI}from"node:path";function JQ(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 RL(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(XQ);for(let Q of G)if(sX(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=sX(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 p9(X){let J=X.scope??tG,$=X.requiredLabels??eG,Y=[],G=[],Q=[];for(let j of X.rows){let q=JQ(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),N=RL(j.id,K,$,X.now);if(N){G.push(N);continue}Q.push({id:j.id,kind:j.kind,projection:K})}let z=new Map(Q.flatMap((j)=>{let q=G2(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 Q2="main";function aX(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 k1(X,J,$=Q2){if(J==="roster"||!X.includes($))return[...X];let Y=X.filter((G)=>G!==$);return J==="main-first"?[$,...Y]:[...Y,$]}function oX(X){let J=p9(X),$=new Set(J.admitted.map((G)=>G.id));return{order:k1(X.rows.map((G)=>G.id),X.placement??"roster",X.formerMainId).filter((G)=>$.has(G)&&X.killswitch?.get(G)!==!1),admission:J}}function rX(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 tX(X,J,$){if(!J.has(X.accountId))return!1;return!(typeof X.wireIdentity==="string"&&typeof $==="string"&&X.wireIdentity!==$)}function CL(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 J5=900000,YQ=0.016666666666666666,eX=0.000001;function z2(X,J){for(let $ of[X?.checkedAt,J])if(typeof $==="number"&&Number.isFinite($))return $;return}function GQ(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 QQ(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 $5(X){let J=(X.classifyStatus??GQ)(X.status);if(J==="permanent")return{action:"migrate",reason:"permanent"};if(!X.quota)return{action:"retain",reason:"unknown"};let $=z2(X.quota,X.quotaCheckedAt);if($===void 0||!Number.isFinite($)||X.now-$>J5)return{action:"retain",reason:"stale"};if(X.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let G of QQ(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=G2(X.quota,X.now);if(Y)return{action:"migrate",reason:"exhausted",resetsAt:Y.resetsAt};return{action:"retain",reason:J}}function X5(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,YQ);return Y/Q}function $Q(X,J){if(X<J)return-1;if(X>J)return 1;return 0}function EL(X,J){if(!X.quota)return;let $=z2(X.quota,X.quotaCheckedAt);if($===void 0||J-$>J5)return;let Y=QQ(X.quota).map((z)=>X5({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(X5({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 zQ(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)=>EL(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,eX),W=((X.pendingBytes.get(z.candidate.accountId)??0)+X.requestBytes)/Math.max(z.weight,eX);return Z-W||Q.candidate.configuredOrder-z.candidate.configuredOrder||$Q(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||$Q(G.accountId,Q.accountId)})[0];if(!Y)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Y.accountId,quotaCheckedAt:z2(Y.quota,Y.quotaCheckedAt),source:"mode-fallback"}}function Y5(X){let J=p9(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&&tX(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,N)=>({row:K,configuredOrder:N})).filter(({row:K})=>!G.has(K.id)).map(({row:K,configuredOrder:N})=>{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:N,...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=zQ({candidates:U,pendingBytes:X.pendingBytes??new Map,requestBytes:X.requestBytes,now:X.now,...X.onEmptyWeightedSet?{onEmptyWeightedSet:X.onEmptyWeightedSet}:{}});if(!K)break;let N=Y.get(K.accountId);if(N){j.push(N),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 Z2 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 x1="identity-contradicted: ",G5="duplicate-identity";function q9(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 w4(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 w1(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))q9(X,G.id,"duplicate-identity"),Y.push(G.id);return Y}function c9(X,J,$){let Y=X.rosterRow(J);if(!Y)return[];return Y.accountId=$,w1(X,$)}import{readFile as iL}from"node:fs/promises";import{setTimeout as nL}from"node:timers/promises";import{AsyncLocalStorage as SL}from"node:async_hooks";var ZQ=new SL;function B6(X){if(ZQ.getStore()!==void 0)throw new Z2(X)}function _8(X,J){return ZQ.run(X,async()=>await J())}async function WQ(X,J,$,Y,G){if(!J)return;try{await _8(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 Q5=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function IL(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,...bL(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 W2({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 bL(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 N9{defaults;env;held=[];constructor(X,J){this.defaults=X,this.env=J}async acquire(X){let J=await IL(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 l9(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 v4}from"node:crypto";var E0="commonAuthPool",L9=1,J8="rows",B2="retiredEpochs",y4=1,z5=300000,_0=E0;function kL(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 d9(X){return v4("sha256").update(kL(X)).digest("hex")}function BQ(X){if(!y(X)||Object.keys(X).length!==1||typeof X.reservation!=="string"||!X.reservation)return;return{reservation:X.reservation}}function xL(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 O6="commonAuthProviderState";function y(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}var wL=new Set(["__proto__","constructor","prototype"]);function v1(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(wL.has(X))return"id is a reserved object key";return}function Z5(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 HQ(X){return X.type==="oauth"?`oauth\x00${X.refresh}`:`api\x00${X.apiKey}`}function $8(X){return v4("sha256").update(HQ(X)).digest("hex")}function A8(X){return v4("sha256").update(`credential-stamp\x00${HQ(X)}`).digest("hex")}function a8(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 v4("sha256").update(`credential-dispatch\x00${JSON.stringify(J)}`).digest("hex")}function W5(X,J,$,Y={}){return{credentialEpoch:J,digest:A8(X),dispatch:a8(X),binding:{...$},...Y.replace?{replace:!0}:{},...Y.providerState!==void 0?{providerState:Y.providerState}:{}}}function y1(X,J){let $=X?.credentialBound?X.credentialBound(J):J;return v4("sha256").update(`provider-state\x00${JSON.stringify($??null)}`).digest("hex")}function h4(X,J,$,Y){if(!J||$===void 0)return;if(!y(X)||!Object.hasOwn(X,O6))return;let G=I6(X[_0]);if(!G||G.providerState===void 0||G.digest!==A8(J)||G.credentialEpoch!==$||G.binding?.identity!==Y)return;return G.providerState}function Y6(X){return Number.isSafeInteger(X)&&X>=1}function I6(X){if(!y(X))return;let J=X.credentialEpoch;if(!Y6(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?xL(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&&!Z5(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 vL(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 yL(X,J,$,Y){if(!X)return"none";if(!y(Y)||!Object.hasOwn(Y,_0))return"missing";let G=I6(Y[_0]);if(!G)return"malformed";if(G.digest!==A8(X))return"mismatched";if(G.dispatch===void 0)return"legacy";if(G.credentialEpoch!==J)return"mismatched";if(!G.binding||!vL(G.binding,X,$))return"mismatched";if(G.dispatch!==a8(X))return"mismatched";return"bound"}function VQ(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>L9)return{status:"error",reason:`${E0}.schemaVersion ${Y} is newer than ${L9}`};if(J8 in $&&!y($[J8]))return{status:"error",reason:`${E0}.${J8} is not an object`};return{status:"ready",exists:!0,config:J}}function UQ(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 h1(X){return Array.isArray(X.accounts)?X.accounts:[]}function KQ(X){let J=X[E0];if(!y(J))return{};let $=J[J8];return y($)?$:{}}function hL(X){return y(X.accounts)?X.accounts:{}}function fL(X){if(!y(X))return"not an object";let J=v1(X.id);if(J)return J;if(X.type==="api")return Z5(X.baseURL)?void 0:"invalid baseURL";if(X.type==="oauth")return;return"unknown type"}function gL(X,J){if(!y(X))return;let $=X.credentialEpoch;if(!Y6($))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&&!BQ(X.staged))return;return{credentialEpoch:$,needsFirstReading:X.needsFirstReading===!0,...typeof X.disabledReason==="string"?{disabledReason:X.disabledReason}:{},..."quota"in X?{quota:X.quota}:{}}}function mL(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 H2(X,J){return h1(X).find(($)=>y($)&&$.id===J)}function jQ(X){if(!y(X[E0]))X[E0]={};return X[E0]}function B5(X){let J=jQ(X);if(!y(J[J8]))J[J8]={};return J[J8]}function D9(X,J){let $=KQ(X),Y=Object.hasOwn($,J)?$[J]:void 0;return y(Y)?Y:void 0}function V2(X,J,$){Object.defineProperty(B5(X),J,{value:$,enumerable:!0,writable:!0,configurable:!0})}function qQ(X,J){let $=X[E0];if(!y($))return;let Y=$[B2];if(!y(Y)||!Object.hasOwn(Y,J))return;let G=Y[J];return Y6(G)?G:void 0}function NQ(X,J){let $=D9(X,J)?.credentialEpoch;return Y6($)?$:void 0}function U2(X,J){return Math.max(qQ(X,J)??0,NQ(X,J)??0)+1}function LQ(X,J){let $=[...J];if($.length===0)return;let Y=jQ(X),G=y(Y[B2])?Y[B2]:{},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(Y6(W))z(Z,W);for(let Z of $)z(Z,Math.max(qQ(X,Z)??0,NQ(X,Z)??1));Y[B2]=Q}function F9(X,J,$,Y){let G=KQ(X),Q=hL(J),z=new Set,Z=[];for(let W of h1(X)){let B=fL(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?BQ(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",N=Object.hasOwn(G,H),F=N?gL(G[H],$):void 0,O=mL(W,Q[H]),_=W.enabled!==!1,C=F?F.credentialEpoch:N?void 0:1,L=typeof W.accountId==="string"&&W.accountId?W.accountId:void 0,P={id:H,type:K,enabled:_,needsFirstReading:F?F.needsFirstReading:K==="oauth",hasEntry:N,candidate:!1,...typeof W.label==="string"?{label:W.label}:{},...typeof W.addedAt==="number"?{addedAt:W.addedAt}:{},...L!==void 0?{identity:L}:{},...O?{credential:O,fingerprint:$8(O)}:{},...F?{credentialEpoch:F.credentialEpoch}:{},...q?{staged:q}:{},...F?.disabledReason!==void 0?{disabledReason:F.disabledReason}:{},...F&&"quota"in F?{quota:F.quota}:{},...uL(Q[H],O,C,L,Y),stamp:yL(O,C,L,Q[H])};if(N&&!F)P.invalid="entry";else P.candidate=_&&O!==void 0&&!j;Z.push(P)}return Z}function uL(X,J,$,Y,G){if(!y(X)||!Object.hasOwn(X,O6))return{};let Q=h4(X,J,$,Y);if(Q===void 0)return{providerStateDropped:"uncovered"};let z=X[O6];if(!G?.validate(z))return{providerStateDropped:"invalid"};if(y1(G,z)!==Q)return{providerStateDropped:"uncovered"};return{providerState:z}}function x0(X){return X.identity??X.id}function f4(X,J){if(X===void 0||X>J+z5)return J;return Math.max(J,X+1)}function H5(X,J){return f4(X,J)>J+z5}function f1(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 DQ(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 FQ(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 PQ(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)&&!Z5(X.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var K2="transition",OQ="transitionMark";function pL(X){if(!y(X))return;let J=X[K2];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 g4(X,J,$){if($.enabled)w4(X,J);else q9(X,J,$.reason??"");if(!X.rosterRow(J))return;let Y=X.entry(J)??{credentialEpoch:1,needsFirstReading:!0};if(X.setEntry(J,{...Y,[OQ]:$.mark}),!$.enabled)return;let G=X.rows().find((Q)=>Q.id===J);if(G?.type==="oauth"&&G.identity!==void 0)w1(X,G.identity)}function cL(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 lL(X){if(!X.binding)return!1;return X.replace===!0||X.dispatch===void 0}function dL(X,J,$,Y={}){let G=y(J.accounts)?J.accounts:{},Q=new Map;for(let z of F9(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=I6(Z[_0]);if(!W?.binding)continue;if(W.digest!==A8(z.credential))continue;let B=z.credentialEpoch??1;if(W.credentialEpoch>B){if(!lL(W))continue;if(Y.requireCredentialStamps){if(W.dispatch===void 0)continue;if(W.dispatch!==a8(cL(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===a8(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!==a8(z.credential))continue;let H=pL(Z[_0]);if(H&&D9(X,z.id)?.[OQ]!==H.mark)Q.set(z.id,{kind:"transition",transition:H})}}return Q}function V5(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(x1))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 U5(X,J,$,Y={}){let G=dL(X,J,$,Y);if(G.size===0)return{config:X,torn:[]};let Q=structuredClone(X),z={rows:()=>F9(Q,J,$),rosterRow:(Z)=>H2(Q,Z),entry:(Z)=>D9(Q,Z),setEntry:(Z,W)=>V2(Q,Z,W)};for(let[Z,W]of G)if(W.kind==="replace")V5(z,Z,W.stamp.credentialEpoch,W.stamp.binding);for(let[Z,W]of G)if(W.kind==="identity")c9(z,Z,W.identity);else if(W.kind==="transition")g4(z,Z,W.transition);else if(W.stamp.binding.identity!==void 0)w1(z,W.stamp.binding.identity);return{config:Q,torn:[...G.keys()]}}function K5(X,J,$,Y={}){let{config:G,torn:Q}=U5(X,J,$,Y),z=F9(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 j5(X){try{return await iL(X,"utf8")}catch(J){if(J.code==="ENOENT")return;throw J}}function MQ(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 _6(X){for(let J=0;J<3;J++){let $=await j5(X.configPath),Y=await j5(X.statePath),G=await j5(X.configPath);if($!==G){if(J<2)await nL(2+Math.floor(Math.random()*4));continue}let Q=VQ(MQ($));if(Q.status==="error")return{status:"error",file:"config",reason:Q.reason};let z=UQ(MQ(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:K5(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 Y8(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 RQ{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 K5(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){l9(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(),H2(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 B5(this.config)}entry(X){return this.entries(),D9(this.config,X)}setEntry(X,J){V2(this.config,X,J)}async completeTorn(){let{config:X,torn:J}=U5(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 h1(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);LQ(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:y4,accounts:J,[E0]:{...z,schemaVersion:L9,[J8]: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:y4,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 q5(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 q5(this.ctx.configPath)}async write(X,J,$,Y=!0,G=!1,Q){await AQ(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 CQ(X,J){let $=new N9(X.lockDefaults,X.lockEnv),Y={writes:0};try{for(let Z of X.storeLocks)await $.acquire(Z);let G=await _6(X);if(G.status==="error")throw Y8(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=y4,Q[E0]={schemaVersion:L9,[J8]:{}};let z={operation:"initialize",rowId:void 0};return await M6(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 g1(G,"initialize",void 0,Y)}finally{await $.releaseAll()}}async function s0(X,J,$,Y,G,Q={}){let z=J.held.length;try{for(let B of X.storeLocks)await J.acquire(B);let Z=await _6(X);if(Z.status!=="ready")throw Y8(Z,Y.operation,Y.rowId,$.writes>0?"after-first-write":"before-first-write");let W=new RQ(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 g1(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 _Q)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 TQ)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 W2)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 H6(X,J,$,Y,G){let Q=new N9(X.lockDefaults,X.lockEnv),z={writes:0};try{return await G(Q,z)}catch(Z){let W=g1(Z,J,$,z);if(W.kind!=="after-persist-hook")await WQ(J,Y,$,W,X.logger);throw W}finally{await Q.releaseAll()}}function f6(X,J){return{...X.rowLockOptions,name:`row-${encodeURIComponent(x0(J))}`,path:X.ctx.statePath}}async function o8(X,J,$){let Y=await _6(X.ctx);if(Y.status!=="ready")throw Y8(Y,J,$);let G=Y.rows.find((B)=>B.id===$),Q=D9(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"))l9(J,$,Q.staged);if(!G&&y(W)&&Object.hasOwn(W,"staged"))l9(J,$,W.staged);if(!G)throw G8(J,$);return{result:Y,row:G}}function G8(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 A6(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 j2(X,J,$,Y){let{ctx:G}=X,Q=new N9(G.lockDefaults,G.lockEnv),z={writes:0};try{if(!Y6($?.credentialEpoch))throw x("pull",J,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await s0(G,Q,z,{operation:"pull",rowId:J},async(Z)=>{Z.assertNotStaged(J);let W=Z.row(J);if(!W)throw G8("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`);A6("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 g1(Z,"pull",J,z)}finally{await Q.releaseAll()}}function r8(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 m4(X,J,$,Y,G){if(Y===void 0||!X?.merge)return{kind:"set",value:G};return{kind:"set",value:r8(X,J,$,X.merge(structuredClone(Y),structuredClone(G)),"the merged provider state")}}function EQ(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:r8(X,"replace",J.id,z,"the provider state onReplace returned")}}function SQ(X,J,$,Y,G){if(J.kind==="set")return y1(X,J.value);if(J.kind==="clear")return;return h4($,Y?.credential,G,Y?.identity)}async function IQ(X,J,$,Y,G={}){B6("updateProviderState");let{ctx:Q}=X,z="updateProviderState";return H6(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(!Y6(H))throw x(z,J,"invalid-input","the credential epoch the provider state was read at is required");let{row:U}=await o8(X,z,J);await Z.acquire(f6(X,U));for(let j of G.extraLocks??[])await Z.acquire(j);return s0(Q,Z,W,{operation:z,rowId:J},async(j)=>{let q=j.row(J);if(!q)throw G8(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(A6(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 N=await N5(j,B,z,q,Y);if(N.kind!=="changed")return{id:J,outcome:"unchanged",...N.kind==="unchanged"&&N.value!==void 0?{providerState:N.value}:{}};return j.setStateAccount(J,N.account),await j.commitState(),N.value===void 0?{id:J,outcome:"cleared"}:{id:J,outcome:"updated",providerState:N.value}})})}var bQ=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function N5(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=I6(H);if(!y(H)||!U?.binding||U.digest!==A8(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 _8($,()=>G(j,Y));if(Q&&q===bQ)return{kind:"declined"};let K=q===void 0?void 0:r8(J,$,z,q,"the provider state the mutator returned"),N=B!==void 0&&Object.hasOwn(B,O6);if(K===void 0?!N: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[O6];let O={...H};delete O.providerState,F[_0]=O}else{F[O6]=K;let O=y1(J,K);if(U.providerState!==O)F[_0]={...H,providerState:O}}return{kind:"changed",...K!==void 0?{value:K}:{},account:F}}import{randomUUID as kQ}from"node:crypto";async function D2(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:N,invalid:F}=Q;return{id:z,type:Z,label:W,enabled:B,disabledReason:H,identity:U,credentialEpoch:j,stamp:q,staged:K,torn:N,invalid:F}}),G=await _8(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 sL=["access","refresh","expires","lastRefreshedAt","apiKey"];function aL(X){return{baseURL:String(X.baseURL).trim(),authHeader:X.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function oL(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"}:aL(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 xQ(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 q2(X,J,$,Y,G={}){let Q=oL(J,$,Y),z=J.stateAccount($),Z=G.providerState??{kind:"keep"},W=J.row($)?.credentialEpoch??J.entry($)?.credentialEpoch,B=typeof W==="number"?W:1,H=SQ(X.ctx.providerState,Z,z,z&&Object.hasOwn(z,O6)?J.row($):void 0,B),U=typeof z?.lastRefreshedAt==="number"?z.lastRefreshedAt:void 0,j=Q.type==="oauth"?G.stamp??f4(U,X.ctx.now()):void 0,q={...z??{}};for(let F of sL)delete q[F];if(G.clearErrors)delete q.lastRefreshError,delete q.lastQuotaRefreshError,delete q.quota;if(Z.kind==="clear")delete q[O6];else if(Z.kind==="set")q[O6]=Z.value;let K=FQ(Q,j),N={...q,...DQ(Q,j),[_0]:{...G.staged?{staged:G.staged}:{},...G.transition!==void 0?{[K2]:G.transition}:{},...W5(K,B,G.binding??xQ(J,$,K,G.identity),{replace:G.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:K,account:N}}async function N2(X,J,$){return X.setStateAccount(J,$.account),await X.commitState($.stored),$.stored}async function F2(X,J,$,Y,G={}){return N2(J,$,q2(X,J,$,Y,G))}async function rL(X,J,$){if(!J.credential||J.stamp!=="bound")return;let Y=X.stateAccount(J.id),G=h4(Y,J.credential,J.credentialEpoch??1,J.identity);X.setStateAccount(J.id,{...Y??{},[_0]:W5(J.credential,J.credentialEpoch??1,xQ(X,J.id,J.credential,$),G!==void 0?{providerState:G}:{})}),await X.commitState()}function D5(X,J,$){let Y=X==="add"?v1(J):void 0;if(Y)throw x(X,J,"invalid-input",Y);let G=PQ($,{baseURLOptional:X==="rotate"});if(G)throw x(X,J,"invalid-input",G)}function P2(X,J,$,Y){if(!$)throw G8(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 u1(X,J,$){if($!==void 0&&!Y6(y($)?$.credentialEpoch:void 0))throw x(X,J,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function O2(X,J,$,Y){if(!$)throw G8(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 L2(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 u4(X,J){return x(X,J,"row-key-changed",`row ${J}'s wire identity changed while its lock was being taken`,!0)}function tL(X,J,$,Y){let{id:G,credential:Q,identity:z}=$;if(!X.ctx.requireCredentialStamps||J.rosterRow(G)||!m1(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=I6(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]=F9({accounts:[f1({id:G,credential:H,identity:B.binding.identity,addedAt:0})],[E0]:{rows:{[G]:{credentialEpoch:U2(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(A8(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(a8(Q)!==B.dispatch)return Z();if(B.providerState!==void 0&&U.providerState===void 0)return Z();if(Y!==void 0&&y1(X.ctx.providerState,Y)!==B.providerState)return Z();return U}function eL(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=I6(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:d9(Y),K=H?.[O6],N=K===void 0?void 0:d9(K);if(j.providerState!==q||j.providerState!==N)return B();if(A8(Q)!==U.digest||a8(Q)!==U.dispatch)return B();let F=W?J.config:{accounts:[{...f1({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=F9(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(U2(J.config,G)!==U.credentialEpoch)return B();return J.roster().push({...f1({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 wQ(X,J,$={}){B6("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 H6(Y,"add",G,$.onFailure,async(H,U)=>{D5("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:r8(Y.providerState,"add",G,J.providerState);if(await H.acquire(f6(X,{id:G,identity:z})),Q.type==="oauth")await H.acquire($.providerLock??X.providerLock);for(let K of $.extraLocks??[])await H.acquire(K);return s0(Y,H,U,{operation:"add",rowId:G},async(K)=>{await D2(K,G,$.protect);let N=y(K.state.accounts)?K.state.accounts:{},F=Object.entries(N).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)||m1(K.state,G)))return eL(X,K,J,q);if(j==="rotate"){K.assertNotStaged(G);let X0=K.rows().find((w)=>w.fingerprint===$8(Q));if(X0)K.assertNotStaged(X0.id)}if(j==="refuse"){let X0=K.rows().find((L0)=>L0.fingerprint===$8(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||m1(K.state,G))throw x("add",G0,"credential-exists",`row ${G0} already holds this secret or id`)}if(j==="stage-duplicate"&&(K.rosterRow(G)||m1(K.state,G)))throw x("add",G,"id-exists",`row ${G} already exists`);let O=tL(X,K,J,q),_=K.rows(),C=$8(Q),L=j==="rotate"&&!O&&_.find((X0)=>X0.invalid===void 0&&X0.fingerprint===C);if(L){if(K.assertNotStaged(L.id),A6("add",L),z!==void 0&&L.identity!==void 0&&z!==L.identity)throw L2("add",L.id);let X0=q2(X,K,L.id,Q,{...q!==void 0?{providerState:m4(Y.providerState,"add",L.id,L.providerState,q)}:{}});await K.completeTorn(),K.assertNotStaged(L.id);let w=await N2(K,L.id,X0);return{id:L.id,outcome:"rotated",credential:w,credentialEpoch:L.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(A6("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 L2("add",G);if(!P.hasEntry)K.setEntry(G,{credentialEpoch:1,needsFirstReading:Q.type==="oauth"});let X0=q2(X,K,G,Q,{clearErrors:!0,...q!==void 0?{providerState:{kind:"set",value:q}}:{}});await K.completeTorn();let w=await N2(K,G,X0);if(!P.hasEntry)await K.commitConfig();return{id:G,outcome:"completed",credential:w,credentialEpoch:P.credentialEpoch??1}}let A=U2(K.config,G);if(!Y6(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(f1({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 k="added";if(J.disabled)q9(K,G,J.disabled.reason),k="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))q9(K,G,G5),k="added-disabled"}if(O?.credential)return await K.commitConfig(),{id:G,outcome:k,credential:O.credential,credentialEpoch:O.credentialEpoch??A};K.dropStateAccount(G);let p=q2(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:d9(q)}:{}}}:{},...q!==void 0?{providerState:{kind:"set",value:q}}:{}});if(j==="rotate")await K.completeTorn();let i=await N2(K,G,p);return await K.commitConfig(),{id:G,outcome:k,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 vQ(X,J,$,Y={},G={}){B6("replace");let{ctx:Q}=X,z=await H6(Q,"replace",J,G.onFailure,async(Z,W)=>{D5("replace",J,$),u1("replace",J,G.attribution);let B=Y.providerState===void 0?void 0:r8(Q.providerState,"replace",J,Y.providerState),{row:H}=await o8(X,"replace",J);if(await Z.acquire(f6(X,H)),$.type==="oauth")await Z.acquire(G.providerLock??X.providerLock);for(let U of G.extraLocks??[])await Z.acquire(U);return s0(Q,Z,W,{operation:"replace",rowId:J},async(U)=>{if(G.attribution!==void 0)O2("replace",J,U.row(J),G.attribution),await U.completeTorn();let j=P2("replace",J,U.row(J),$);if(x0(j)!==x0(H))throw u4("replace",J);let q=U.entry(J)?.credentialEpoch,K=(typeof q==="number"?q:1)+1;if(!Y6(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 N=EQ(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(V5(U,J,K,F),Y.identity!==void 0)w1(U,Y.identity);let O=await F2(X,U,J,$,{clearErrors:!0,binding:F,providerState:N});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 yQ(X,J,$,Y={},G={}){B6("rotate");let{ctx:Q}=X;return H6(Q,"rotate",J,G.onFailure,async(z,Z)=>{D5("rotate",J,$),u1("rotate",J,G.attribution);let W=Y.providerState===void 0?void 0:r8(Q.providerState,"rotate",J,Y.providerState),{row:B}=await o8(X,"rotate",J);if(await z.acquire(f6(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 s0(Q,z,Z,{operation:"rotate",rowId:J},async(H)=>{if(G.attribution!==void 0)O2("rotate",J,H.row(J),G.attribution),await H.completeTorn();let U=P2("rotate",J,H.row(J),$);if(x0(U)!==x0(B))throw u4("rotate",J);if(A6("rotate",U),Y.identity!==void 0&&U.identity!==void 0&&Y.identity!==U.identity)throw L2("rotate",J);let j=Y.identity!==void 0&&U.identity===void 0?Y.identity:void 0,q=await F2(X,H,J,$,{identity:j,...W!==void 0?{providerState:m4(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)c9(H,J,Y.identity),K=!0;if(K)await H.commitConfig();return{id:J,credential:q}},{completeTorn:G.attribution===void 0})})}async function hQ(X,J,$,Y,G){B6(J);let{ctx:Q}=X,z=Q.providerState,Z=G.attribution,W=G.providerState;return H6(Q,J,$,G.onFailure,async(B,H)=>{if(u1(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 o8(X,J,$);await B.acquire(f6(X,U));for(let j of G.extraLocks??[])await B.acquire(j);return s0(Q,B,H,{operation:J,rowId:$},async(j)=>{await D2(j,$,G.protect),j.assertNotStaged($);let q=j.row($),K=Y.enabled?P2("enable",$,q):q;if(!K||!j.rosterRow($))throw G8(J,$);if(x0(K)!==x0(U))throw u4(J,$);if(Z!==void 0)O2(J,$,K,Z);if(Y.enabled&&K.disabledReason?.startsWith(x1))throw x("enable",$,"identity-contradicted",`row ${$} needs an identity-validated credential replacement before it can be enabled`);let N=!Y.enabled||!K.enabled||K.disabledReason!==void 0;if(Y.enabled&&N&&K.type==="oauth"){let L=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(L)throw x("enable",$,"duplicate-identity",`row ${L.id} is enabled with the same identity as row ${$}`)}if(W===void 0||z===void 0){if(await j.completeTorn(),!N)return{id:$};if(Y.enabled)w4(j,$);else q9(j,$,Y.reason);return await j.commitConfig(),{id:$}}if(!K.credential)throw x(J,$,"no-credential",`row ${$} holds no credential`);A6(J,K);let F=await N5(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(N){if(Y.enabled)w4(j,$);else q9(j,$,Y.reason);await j.commitConfig()}return O}if(!N)return j.setStateAccount($,F.account),await j.commitState(),O;let _=Y.enabled?{mark:kQ(),enabled:!0}:{mark:kQ(),enabled:!1,reason:Y.reason},C=F.account[_0];return j.setStateAccount($,{...F.account,[_0]:{...C,[K2]:_}}),await j.commitState(),g4(j,$,_),await j.commitConfig(),O},{completeTorn:!1})})}function fQ(X,J,$,Y={}){return hQ(X,"disable",J,{enabled:!1,reason:$},Y)}function gQ(X,J,$={}){return hQ(X,"enable",J,{enabled:!0},$)}async function mQ(X,J,$={}){B6("remove");let{ctx:Y}=X;return H6(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(u1("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 _6(Y);if(Z.status!=="ready")throw Y8(Z,"remove",J);let W=Z.rows.find((H)=>H.id===J);if(!W&&!m1(Z.state,J))throw G8("remove",J);let B=x0(W??{id:J});await G.acquire(f6(X,W??{id:J}));for(let H of $.extraLocks??[])await G.acquire(H);return s0(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=m1(H.state,J);if(!j&&!q)throw G8("remove",J);if(x0(j??{id:J})!==B)throw u4("remove",J);if(z!==void 0)if(j)M2(J,j,z);else XD(X,H,J,z);let K=$.protect;if(K){let N={row:j,config:H.snapshot.config,state:H.snapshot.state},F=await _8("remove",()=>K(J,N));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 M2(X,J,$,Y="remove"){if(O2(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 XD(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=I6(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]=F9({accounts:[f1({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 m1(X,J){let $=X.accounts;return y($)&&Object.hasOwn($,J)}function L5(X){return y(X)&&typeof X.id==="string"?X.id:void 0}function JD(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=L5(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 $D(X,J){let $=new Map;for(let Q of X){let z=L5(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)=>L5(Q)===void 0?Q:Y[G++])}async function uQ(X,J,$={}){B6("reorder");let{ctx:Y}=X,G=$.onFailure;return H6(Y,"reorder",void 0,G&&((Q,z)=>G(z)),async(Q,z)=>{for(let Z of $.extraLocks??[])await Q.acquire(Z);return s0(Y,Q,z,{operation:"reorder",rowId:void 0},async(Z)=>{let W=Z.roster(),B=JD(W,J);if(B)throw new K0({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:B});let H=[...J],U=$D(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 pQ(X,J,$,Y,G={}){return B6("recordIdentity"),H6(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(!Y6(Z))throw x("recordIdentity",J,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:W}=await o8(X,"recordIdentity",J);await Q.acquire(f6(X,W)),await Q.acquire(G.providerLock??X.providerLock);for(let B of G.extraLocks??[])await Q.acquire(B);return s0(X.ctx,Q,z,{operation:"recordIdentity",rowId:J},async(B)=>{let H=P2("recordIdentity",J,B.row(J));if(x0(H)!==x0(W))throw u4("recordIdentity",J);if(A6("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 L2("recordIdentity",J);if(H.identity===void 0)await rL(B,H,$);let U=c9(B,J,$);return await B.commitConfig(),{id:J,disabled:U}})})}function lQ(X){let J=X[E0];return y(J)&&y(J.publications)?J.publications:{}}function dQ(X,J){let $=lQ(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"||!Y6(G.credentialEpoch))||Y.finalized.some((G)=>!y(G)||typeof G.id!=="string"||!Y6(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 iQ(X,J){let $=await _6(X.ctx);if($.status!=="ready")throw Y8($,"publishRoster",J);return dQ($.config,J)}function YD(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"||v1(G.id)||Y.has(G.id)||!G.attribution)$();if(Y.add(G.id),u1("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"||v1(G))||new Set(J.order).size!==J.order.length)$()}function nQ(X,J){X.entries();let $=X.config[E0],Y={...lQ(X.config)};Object.defineProperty(Y,J.operationId,{value:J,enumerable:!0,writable:!0,configurable:!0}),$.publications=Y,delete $.publicationOrder}function GD(X,J,$){let Y=new Set;for(let z of h1(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 cQ(X,J){await X.assertAll();for(let Y of J.removed)if(I6(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=I6(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 nQ(X,$),await X.commitConfig({durable:!0}),$}async function sQ(X,J,$={}){return B6("publishRoster"),H6(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=d9(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 _6(X.ctx);if(W.status!=="ready")throw Y8(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(f6(X,{id:U}));await Y.acquire($.providerLock??X.providerLock);for(let U of $.extraLocks??[])await Y.acquire(U);let H=await s0(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=dQ(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 cQ(U,q)}}YD(X,J);let K=GD(U,J,j),N=[];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(M2(P.id,A,P.attribution,"publishRoster"),!A.credential||P.fingerprint!==void 0&&$8(A.credential)!==P.fingerprint)throw x("publishRoster",P.id,"attribution","the removed secret no longer matches");N.push(A)}let F=[];for(let P of J.finalize){let A=j.find((w)=>w.id===P.id),T=I6(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 k=U.stateAccount(P.id),p=U.rosterRow(P.id),i=k?.[O6],X0=i===void 0?void 0:d9(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");M2(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&&N.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 D2(U,J.operationId,$.protect);let C={operationId:J.operationId,planDigest:Q,phase:"committed",removed:N.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 L=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)),...L],nQ(U,C),await U.syncState(),await U.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await cQ(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 F5{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 N9(Y.lockDefaults,Y.lockEnv),Q={writes:0};try{let z=await s0(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)A6("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 j2($,X,{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},Z)}catch(z){this.firedAtLoad.delete(X);let Z=g1(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 QD}from"node:crypto";function P5(X,J){if(l9("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 aQ(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 oQ(X,J,$,Y={}){B6("refresh");let{ctx:G}=X;return H6(G,"refresh",J,Y.onFailure,async(Q,z)=>{let{row:Z}=await o8(X,"refresh",J);P5(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(f6(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 s0(G,Q,{writes:0},{operation:"refresh",rowId:J},async(O)=>{let _=P5(J,O.row(J));if(A6("refresh",_),!_.hasEntry)O.setEntry(J,{credentialEpoch:1,needsFirstReading:!0}),await O.commitConfig(),_=P5(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(H5(H.credential.lastRefreshedAt,G.now()))throw aQ(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:r8(G.providerState,"refresh",J,U.providerState,"the provider state the provider returned"),q=await s0(G,Q,z,{operation:"refresh",rowId:J},async(K)=>{let N=K.row(J),F=K.entry(J);if(!N||N.invalid||!F||F.credentialEpoch!==H.credentialEpoch||N.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`});A6("refresh",N);let O=await Y.refuse?.(N);if(O!==void 0)return{refused:O};let _=G.now(),C=N.credential?.type==="oauth"?N.credential.lastRefreshedAt:void 0;if(H5(C,_))throw aQ(J);let L={type:"oauth",access:U.access,refresh:U.refresh,expires:U.expires},P=N.identity!==void 0&&U.identity!==void 0&&N.identity!==U.identity?{expectedIdentity:N.identity,returnedIdentity:U.identity}:void 0,A=P?{mark:QD(),enabled:!1,reason:`${x1}${JSON.stringify(P)}`}:void 0,T=N.identity===void 0&&U.identity?U.identity:void 0,k=await F2(X,K,J,L,{stamp:f4(C,_),transition:A,identity:T,...j!==void 0?{providerState:m4(G.providerState,"refresh",J,N.providerState,j)}:{}});if(A!==void 0)g4(K,J,A),await K.commitConfig();let p=N.identity;if(T!==void 0)c9(K,J,T),p=T,await K.commitConfig();return{stored:k,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 _8("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 zD}from"node:util";var A2=Object.freeze(["version","accounts",E0]);function O5(X){let J={};for(let[$,Y]of Object.entries(X))if(!A2.includes($))_2(J,$,Y);return J}function _2(X,J,$){Object.defineProperty(X,J,{value:$,enumerable:!0,writable:!0,configurable:!0})}function ZD(X,J){let $={};for(let[Y,G]of Object.entries(X))if(A2.includes(Y))_2($,Y,G);else if(Object.hasOwn(J,Y))_2($,Y,J[Y]);for(let[Y,G]of Object.entries(J))if(!Object.hasOwn(X,Y))_2($,Y,G);return $}function rQ(X){return new K0({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:X})}async function tQ(X){let J=await _6(X.ctx);if(J.status==="error")return J;return{status:J.status,settings:O5(J.config)}}async function eQ(X,J,$={}){B6("updateSettings");let{ctx:Y}=X,G=$.onFailure;return H6(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 _6(Y);if(W.status!=="ready")throw Y8(W,"updateSettings",void 0);let B=O5(W.config),H=structuredClone(B),U=await _8("updateSettings",()=>J(H)),j=U===void 0?H:U;if(!y(j))throw rQ("the settings mutator must produce an object");let q=A2.filter((F)=>Object.hasOwn(j,F));if(q.length>0)throw rQ(`settings cannot set the pool-owned key(s) ${q.join(", ")}`);if(zD(j,B))return{settings:B,outcome:"unchanged"};let K=ZD(W.config,j),N={operation:"updateSettings",rowId:void 0};return await M6(Y.configPath,K,{beforeRename:async()=>{await Y.onStep?.("before-config-write",N),await Q.assertAll()}}),z.writes++,await Y.onStep?.("after-config-write",N),{settings:O5(K),outcome:"updated"}}finally{await Q.releaseTo(Z)}})}var Xz=new Map;function WD(X){let J=Xz.get(X);if(!J)J={removedIds:new Set,firedAtLoad:new Set},Xz.set(X,J);return J}function Jz(X){if(X.status==="ready")return{status:"ready",schemaVersion:L9,rows:X.rows};if(X.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(X.config.accounts)?X.config.accounts:[]};return X}function Q8(X){let J=WD(X.configPath),$={...Q5,...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 F5(()=>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 _6(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 Jz(z)},async read(){return Jz(await _6(Y))},async initialize(z={}){return{status:await CQ(Y,z.dropKeys??[])}},add:(z,Z)=>wQ(Q,z,Z),publishRoster:(z,Z)=>sQ(Q,z,Z),publication:(z)=>iQ(Q,z),replace:(z,Z,W,B)=>vQ(Q,z,Z,W,B),rotate:(z,Z,W,B)=>yQ(Q,z,Z,W,B),updateProviderState:(z,Z,W,B)=>IQ(Q,z,Z,W,B),disable:(z,Z,W)=>fQ(Q,z,Z,W),enable:(z,Z)=>gQ(Q,z,Z),remove:(z,Z)=>mQ(Q,z,Z),reorder:(z,Z)=>uQ(Q,z,Z),readSettings:()=>tQ(Q),updateSettings:(z,Z)=>eQ(Q,z,Z),recordIdentity:(z,Z,W,B)=>pQ(Q,z,Z,W,B),refresh:(z,Z,W)=>oQ(Q,z,Z,W),recordQuota:(z,Z,W)=>j2(Q,z,Z,W),requestReading:(z)=>G.fire(z,"admission"),pullsSettled:()=>G.settled()}}var BD=[/\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 A5(X={}){let{redactStrings:J}=T2({...X,extraValuePatterns:[...BD,...X.extraValuePatterns??[]]});return($)=>J($)}class b6 extends Error{code;constructor(X,J,$){super(J,$);this.name="CommandError",this.code=X}}var $z=/^[a-z][a-z0-9-]{0,63}$/,M5={code:"action-failed",text:"That action failed."},HD=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 p4(X){if(X instanceof b6)return{code:$z.test(X.code)?X.code:M5.code,text:X.message};if(X instanceof K0)return{code:`pool-${X.kind}`,text:HD.has(X.kind)?X.message:`The account pool could not do that (${X.kind}).`};return M5}var Yz="This cannot be undone. Continue?",VD=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function UD(X){let J=X.toLowerCase().replace(/[-_]/g,"");return VD.has(J)||J.endsWith("token")||J.endsWith("key")||J.endsWith("secret")}function KD(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function _5(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)=>_5(G,`${J}[${Q}]`,$));if(!KD(X))return X;let Y={};for(let[G,Q]of Object.entries(X)){if(UD(G)){$.dropped.push(`${J}.${G}`);continue}Object.defineProperty(Y,G,{value:_5(Q,`${J}.${G}`,$),enumerable:!0,writable:!0,configurable:!0})}return Y}function Gz(X,J,$){let Y={redact:$.redact,dropped:[],redacted:[]},G=_5(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 jD(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(jD),...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 T5(X){if(X.irreversible===!0)return{message:X.confirm||Yz,irreversible:!0};if(X.confirm)return{message:X.confirm,irreversible:!1};return}function Qz(X){let J=T5(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 ND(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 LD(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:ND(X.account)}:{},...X.facts!==void 0?{facts:X.facts}:{},actions:(X.actions??[]).map(Qz)}}function DD(X){let{content:J}=X;return{id:X.id,slot:X.slot,title:X.title,lines:(J.lines??[]).map(String),items:(J.items??[]).map(LD),actions:(J.actions??[]).map(Qz),...J.facts!==void 0?{facts:J.facts}:{}}}function zz(X,J,$){return{command:X,title:J,sections:$.map(DD)}}function Zz(X,J,$,Y){return Gz({command:X,menu:zz(X,J,$)},X,Y)}function Wz(X,J,$,Y,G){return Gz({command:X,ok:Y.ok,text:String(Y.text),...!Y.ok&&Y.code!==void 0?{code:$z.test(Y.code)?Y.code:"refused"}:{},...Y.needsConfirmation?{needsConfirmation:!0}:{},menu:zz(X,J,$)},X,G)}var Uz="disabled from the command menu";function FD(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function t8(X){return FD(X)?{...X}:{}}function PD(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 OD(X,J){return X.label??J??X.id}function R2(X,J){return G6(X.quota)?f0(X.quota,J):void 0}function Kz(X,J){return`${X} ${J}${X===1?"":"s"}`}var c4="Actions";function MD(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 Bz(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 Hz(X){return p4(X).text}async function _D(X){let J=await X.read(),$=await X.readSettings();return{load:J,rows:PD(J),settings:$.status==="error"?{}:$.settings}}function C2(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:OD(X,$)}}function AD(X,J){let{store:$,extraLocks:Y}=X,G=Y?{extraLocks:Y}:{},Q=J.rows.map((U)=>U.id),z=MD(J.load),Z=J.rows.filter((U)=>U.enabled).length,W=J.rows.map((U,j)=>{let{account:q,name:K}=C2(U,X),N=[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,Uz,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),L=Q.filter((A)=>A!==U.id);return L.splice(C-1,0,U.id),(await $.reorder(L,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:N,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:c4,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 Bz(q.account.label??K.id,K)}return q.completion.then(async(K)=>{if(!K){j.notify("Login cancelled.","warning");return}let N=await $.add(K,G);j.notify(Bz(K.label??N.id,N))},(K)=>{j.notify(`Adding the account failed: ${Hz(K)}`,"error")}).catch((K)=>{j.notify(`Adding the account failed: ${Hz(K)}`,"error")}),q.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:z?[z]:[J.rows.length===0?"No accounts yet":`${Kz(J.rows.length,"account")}, ${Z} enabled`],items:z?[]:W,actions:H}}}function TD(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}=C2(H,X),q=R2(H,$);return{id:H.id,label:j,group:G,status:T8(q,{now:Y,form:"compact"}),detail:T8(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}=C2(H,X),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",q=T8(R2(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:c4,run:async({invocation:H})=>{let U=z.map((j)=>j.id);return await Q(U,H),`Checked quota for ${Kz(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 RD(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=t8(J.settings.routing).mode,Z=typeof z==="string"&&Q.some((K)=>K.value===z)?z:"ordered",W=aX(Z),B=J.rows.map((K)=>K.id),H=k1(B,W.placement,X.routing?.formerMainId??Q2),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:c4,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:Q,value:Z}],run:async({values:K})=>{let N=String(K.mode);return await $.updateSettings((F)=>{F.routing={...t8(F.routing),mode:N};return},G),`Routing mode set to ${Q.find((F)=>F.value===N)?.label??N}.`}}];if(B.length>1)q.push({id:"order",label:"Set order",group:c4,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:B.join(", "),required:!0}],run:async({values:K})=>{let N=String(K.order).split(/[\s,]+/).filter((O)=>O.length>0),F=await $.reorder(N,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 CD(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 R2(G,$)?.limits??[])if(!Y.includes(Q.label))Y.push(Q.label);return Y.length>0?Y:["primary"]}function ED(X,J){let $=X.quota?.scope??"all",Y=new Map;for(let G of J.rows)for(let Q of R2(G,$)?.limits??[])if(Q.windowMinutes!==void 0&&!Y.has(Q.label))Y.set(Q.label,Vz(Q));return(G)=>Y.get(G)??G}function SD(X,J){let{store:$,extraLocks:Y}=X,G=Y?{extraLocks:Y}:{},Q=t8(J.settings.killswitch),z=Q.enabled===!0,Z=t8(Q.accounts),W=CD(X,J),B=ED(X,J),H=z?"on":"off",U=J.rows.map((j)=>{let{account:q,name:K}=C2(j,X),N=t8(Z[j.id]),F=W.filter((O)=>typeof N[O]==="number");return{id:j.id,label:K,group:`Floors · killswitch ${H}`,status:F.length===0?"no floors":F.map((O)=>`${B(O)} ≥${N[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 N[O]==="number"?{value:N[O]}:{}})),run:async({values:O})=>{return await $.updateSettings((_)=>{let C=t8(_.killswitch),L=t8(C.accounts),P=t8(L[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)L[j.id]=P;else delete L[j.id];if(Object.keys(L).length>0)C.accounts=L;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:c4,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!z}],run:async({values:j})=>{let q=j.enabled===!0;return await $.updateSettings((K)=>{K.killswitch={...t8(K.killswitch),enabled:q};return},G),`Killswitch ${q?"on":"off"}.`}}]}}}async function jz(X){let J=await _D(X.store);return[AD(X,J),TD(X,J),RD(X,J),SD(X,J)]}var ID=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),R5=["accounts","quota","routing","limits"];function qz(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 bD(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 kD(X,J){let $={};for(let Y of X){let G=J&&Object.hasOwn(J,Y.id)?J[Y.id]:void 0,Q=bD(Y,G);if("problem"in Q)return Q;$[Y.id]=Q.value}return{values:$}}function xD(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 i9(X){let J=X.logger??Z0("commands"),$=A5(X.redaction),Y={logger:J,redact:$},G=X.now??Date.now,Q=X.extras??[],z=X.replace??{},Z=R5.filter((j)=>!z[j]);for(let j of R5)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(ID.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,N){try{return{id:j,slot:q,title:K.title,content:await K.build(N)}}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 jz({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 N of R5){let F=z[N];if(F)K.push(await H(N,N,F,j));else{let O=q.find((_)=>_.slot===N);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 N of Q)K.push(await H(N.id,"extra",N,j));return K}return{command:X.command,async open(j){let q=qz(j,$);return Zz(X.command,X.title,await U(q),Y)},async apply(j,q){let K=qz(q,$),N=async(L)=>Wz(X.command,X.title,await U(K),L,Y),F=j.command===X.command?xD(await U(K),j):void 0;if(!F)return N({ok:!1,code:"unavailable",text:"That action is no longer available."});let O=T5(F);if(O&&j.confirmed!==!0)return N({ok:!1,code:"needs-confirmation",text:O.message,needsConfirmation:!0});let _=kD(F.knobs??[],j.values);if("problem"in _)return N({ok:!1,code:"invalid-input",text:_.problem});let C;try{let L=await F.run({values:_.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:K});C=typeof L==="string"?{ok:!0,text:L}:{ok:L.ok,text:L.text,...L.ok?{}:{code:L.code??"refused"}}}catch(L){let P=p4(L);J.warn("command menu action failed",{command:X.command,section:j.sectionId,action:j.actionId,code:P.code,error:$(L instanceof Error?L.message:String(L))}),C={ok:!1,...P}}return N(C)}}}function wD(X){return X===null||typeof X==="string"||typeof X==="boolean"||typeof X==="number"&&Number.isFinite(X)}function C5(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(!wD(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 oP,randomUUID as rP}from"node:crypto";import{setTimeout as tP}from"node:timers/promises";import{createHash as vD}from"node:crypto";var E5=86400000,yD=300000,hD=3600000,fD=60000,gD=900000,mD=300000;function S5(X){return X instanceof Error?X.message:String(X)}function I5(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 b5(X){let J=S5(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 z8(X){return vD("sha256").update(X).digest("hex")}function p1(X){let J=z8(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(I5(X.error))G=Math.min(hD,yD*2**Math.min(Y-1,6));else G=E5;return{message:S5(X.error),checkedAt:X.now,nextRetryAt:X.now+G,retryCount:Y,tokenHash:J}}function r0(X,J,$){if(!X?.nextRetryAt||X.nextRetryAt<=$)return!1;if(!J)return!0;return X.tokenHash===z8(J)}function e8(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 l4(X){let $=(X.previous?.retryCount??0)+1,Y,G=X.error?.retryAfter;if(typeof G==="number"&&G>0)Y=G*1000;else if(b5(X.error))Y=Math.min(gD,fD*2**Math.min($-1,6));else Y=mD;return{message:S5(X.error),checkedAt:X.now,nextRetryAt:X.now+Y,retryCount:$}}function c1(X,J){if(!X?.nextRetryAt||X.nextRetryAt<=J)return!1;return!0}function k5(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 Nz}from"node:http";import{setTimeout as uD}from"node:timers/promises";var I2="app_EMoamEEZ73f0CkXaXp7hrann",a9="https://auth.openai.com",i4=1455,pD=3000,cD="cortexkit-opencode-openai-auth";function b2(X){return`${cD}/${X}`}var Dz="main",lD=`"${Dz}" is a reserved account id; choose a different label.`;function k2(X){let J=new Uint8Array(X),$=String.fromCharCode(...J);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function w5(){let J=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((Y)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[Y%66]).join(""),$=k2(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(J)));return{verifier:J,challenge:$}}function V6(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 U6(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=V6(X.id_token),$=J&&U6(J);if($)return $}if(X.access_token){let J=V6(X.access_token);return J?U6(J):void 0}return}function dD(X){return typeof X==="string"&&X.toLowerCase()===Dz}function x5(X){if(dD(X))throw Error(lD);return X}function v5(X,J,$){let Y=new URLSearchParams({response_type:"code",client_id:I2,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`${a9}/oauth/authorize?${Y.toString()}`}async function iD(X,J,$){let Y=await fetch(`${a9}/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:I2,code_verifier:$.verifier}).toString()});if(!Y.ok)throw Error(`Token exchange failed: ${Y.status}`);return await Y.json()}function nD(X){return X.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var sD=`<!doctype html>
1
+ import{Ab as YX,Bb as GX,Cb as LL,Db as DL,Eb as C1,Fb as FL,La as $Q,Ma as YQ,Na as G6,Oa as V7,Pa as m8,Qa as Nz,Ra as R7,Sa as R8,Ta as f0,Ua as z2,Va as GQ,Wa as oX,Ya as BY,_a as rH,ab as p8,bb as ZL,eb as WL,ib as kV,jb as BL,kb as HL,lb as VL,qb as vX,rb as yX,sb as UL,tb as KL,wb as jL,xb as NL,yb as qL}from"./index-sjx8t1nr.js";import{Kb as CQ,Lb as M6,Mb as EQ,Nb as L5,Ob as g0,Pb as H2,Qb as SQ,Rb as sZ}from"./index-jyr8y8k4.js";import{Tb as vH,Ub as yH,Vb as hH,Wb as eV,Xb as QL,Yb as o7}from"./index-rv08jmd4.js";import{dc as C2,ec as XX,gc as Z0,hc as dB,jc as cJ,kc as lJ,lc as e0,nc as xH}from"./index-bmd7x5aq.js";import{pc as fH,rc as zL}from"./index-766sfrh5.js";import{uc as MY}from"./index-b3q3j39x.js";import{createHash as sI,randomUUID as aI}from"node:crypto";import{mkdirSync as oI,readFileSync as rI,renameSync as tI,statSync as eI,writeFileSync as Xb}from"node:fs";import DG from"node:os";import{join as Jb}from"node:path";function QQ(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 wL(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(GQ);for(let Q of G)if(oX(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=oX(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 a8(X){let J=X.scope??$Q,$=X.requiredLabels??YQ,Y=[],G=[],Q=[];for(let j of X.rows){let N=QQ(j.id,X,X.now);if(N){Y.push(N);continue}if(j.kind==="api-key"){Q.push({id:j.id,kind:j.kind});continue}let K=f0(j.quota,J),q=wL(j.id,K,$,X.now);if(q){G.push(q);continue}Q.push({id:j.id,kind:j.kind,projection:K})}let z=new Map(Q.flatMap((j)=>{let N=z2(j.projection,X.now);return N?[[j.id,N]]:[]})),Z=z.size>0&&z.size===Q.length,W=[];for(let j of Q){let N=z.get(j.id);if(N===void 0)W.push(j);else if(Z)W.push({...j,lastPath:!0});else G.push({id:j.id,stage:2,reason:"budget-spent",...N})}let B=new Map(X.rows.map((j,N)=>[j.id,N])),H=(j,N)=>(B.get(j.id)??0)-(B.get(N.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 Z2="main";function rX(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 k1(X,J,$=Z2){if(J==="roster"||!X.includes($))return[...X];let Y=X.filter((G)=>G!==$);return J==="main-first"?[$,...Y]:[...Y,$]}function tX(X){let J=a8(X),$=new Set(J.admitted.map((G)=>G.id));return{order:k1(X.rows.map((G)=>G.id),X.placement??"roster",X.formerMainId).filter((G)=>$.has(G)&&X.killswitch?.get(G)!==!1),admission:J}}function eX(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 v4(X,J,$){if(!J.has(X.accountId))return!1;return!(typeof X.wireIdentity==="string"&&typeof $==="string"&&X.wireIdentity!==$)}function X5(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 Y5=900000,ZQ=0.016666666666666666,J5=0.000001;function W2(X,J){for(let $ of[X?.checkedAt,J])if(typeof $==="number"&&Number.isFinite($))return $;return}function WQ(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 BQ(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 G5(X){let J=(X.classifyStatus??WQ)(X.status);if(J==="permanent")return{action:"migrate",reason:"permanent"};if(!X.quota)return{action:"retain",reason:"unknown"};let $=W2(X.quota,X.quotaCheckedAt);if($===void 0||!Number.isFinite($)||X.now-$>Y5)return{action:"retain",reason:"stale"};if(X.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let G of BQ(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=z2(X.quota,X.now);if(Y)return{action:"migrate",reason:"exhausted",resetsAt:Y.resetsAt};return{action:"retain",reason:J}}function $5(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,ZQ);return Y/Q}function zQ(X,J){if(X<J)return-1;if(X>J)return 1;return 0}function vL(X,J){if(!X.quota)return;let $=W2(X.quota,X.quotaCheckedAt);if($===void 0||J-$>Y5)return;let Y=BQ(X.quota).map((z)=>$5({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($5({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 HQ(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)=>vL(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,J5),W=((X.pendingBytes.get(z.candidate.accountId)??0)+X.requestBytes)/Math.max(z.weight,J5);return Z-W||Q.candidate.configuredOrder-z.candidate.configuredOrder||zQ(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||zQ(G.accountId,Q.accountId)})[0];if(!Y)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Y.accountId,quotaCheckedAt:W2(Y.quota,Y.quotaCheckedAt),source:"mode-fallback"}}function Q5(X){let J=a8(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&&v4(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,q)=>({row:K,configuredOrder:q})).filter(({row:K})=>!G.has(K.id)).map(({row:K,configuredOrder:q})=>{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:q,...O===void 0?{}:{resetCreditsApplicable:O},...F===void 0?{}:{killswitchPasses:F}}}),j=[],N=z?{action:"retain"}:X.pin?{action:"clear"}:{action:"none"};while(U.length>0){let K=HQ({candidates:U,pendingBytes:X.pendingBytes??new Map,requestBytes:X.requestBytes,now:X.now,...X.onEmptyWeightedSet?{onEmptyWeightedSet:X.onEmptyWeightedSet}:{}});if(!K)break;let q=Y.get(K.accountId);if(q){j.push(q),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:N,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 B2 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 x1="identity-contradicted: ",z5="duplicate-identity";function q9(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 y4(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 w1(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))q9(X,G.id,"duplicate-identity"),Y.push(G.id);return Y}function c9(X,J,$){let Y=X.rosterRow(J);if(!Y)return[];return Y.accountId=$,w1(X,$)}import{readFile as eL}from"node:fs/promises";import{setTimeout as XD}from"node:timers/promises";import{AsyncLocalStorage as yL}from"node:async_hooks";var VQ=new yL;function B6(X){if(VQ.getStore()!==void 0)throw new B2(X)}function A8(X,J){return VQ.run(X,async()=>await J())}async function UQ(X,J,$,Y,G){if(!J)return;try{await A8(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 Z5=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function hL(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,...fL(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 H2({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 fL(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 L9{defaults;env;held=[];constructor(X,J){this.defaults=X,this.env=J}async acquire(X){let J=await hL(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 l9(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 h4}from"node:crypto";var E0="commonAuthPool",D9=1,$8="rows",V2="retiredEpochs",f4=1,W5=300000,_0=E0;function gL(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 d9(X){return h4("sha256").update(gL(X)).digest("hex")}function KQ(X){if(!y(X)||Object.keys(X).length!==1||typeof X.reservation!=="string"||!X.reservation)return;return{reservation:X.reservation}}function mL(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 O6="commonAuthProviderState";function y(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}var uL=new Set(["__proto__","constructor","prototype"]);function v1(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(uL.has(X))return"id is a reserved object key";return}function B5(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 jQ(X){return X.type==="oauth"?`oauth\x00${X.refresh}`:`api\x00${X.apiKey}`}function Y8(X){return h4("sha256").update(jQ(X)).digest("hex")}function T8(X){return h4("sha256").update(`credential-stamp\x00${jQ(X)}`).digest("hex")}function o8(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 h4("sha256").update(`credential-dispatch\x00${JSON.stringify(J)}`).digest("hex")}function H5(X,J,$,Y={}){return{credentialEpoch:J,digest:T8(X),dispatch:o8(X),binding:{...$},...Y.replace?{replace:!0}:{},...Y.providerState!==void 0?{providerState:Y.providerState}:{}}}function y1(X,J){let $=X?.credentialBound?X.credentialBound(J):J;return h4("sha256").update(`provider-state\x00${JSON.stringify($??null)}`).digest("hex")}function g4(X,J,$,Y){if(!J||$===void 0)return;if(!y(X)||!Object.hasOwn(X,O6))return;let G=b6(X[_0]);if(!G||G.providerState===void 0||G.digest!==T8(J)||G.credentialEpoch!==$||G.binding?.identity!==Y)return;return G.providerState}function Y6(X){return Number.isSafeInteger(X)&&X>=1}function b6(X){if(!y(X))return;let J=X.credentialEpoch;if(!Y6(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?mL(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&&!B5(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 pL(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 cL(X,J,$,Y){if(!X)return"none";if(!y(Y)||!Object.hasOwn(Y,_0))return"missing";let G=b6(Y[_0]);if(!G)return"malformed";if(G.digest!==T8(X))return"mismatched";if(G.dispatch===void 0)return"legacy";if(G.credentialEpoch!==J)return"mismatched";if(!G.binding||!pL(G.binding,X,$))return"mismatched";if(G.dispatch!==o8(X))return"mismatched";return"bound"}function NQ(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>D9)return{status:"error",reason:`${E0}.schemaVersion ${Y} is newer than ${D9}`};if($8 in $&&!y($[$8]))return{status:"error",reason:`${E0}.${$8} is not an object`};return{status:"ready",exists:!0,config:J}}function qQ(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 h1(X){return Array.isArray(X.accounts)?X.accounts:[]}function LQ(X){let J=X[E0];if(!y(J))return{};let $=J[$8];return y($)?$:{}}function lL(X){return y(X.accounts)?X.accounts:{}}function dL(X){if(!y(X))return"not an object";let J=v1(X.id);if(J)return J;if(X.type==="api")return B5(X.baseURL)?void 0:"invalid baseURL";if(X.type==="oauth")return;return"unknown type"}function iL(X,J){if(!y(X))return;let $=X.credentialEpoch;if(!Y6($))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&&!KQ(X.staged))return;return{credentialEpoch:$,needsFirstReading:X.needsFirstReading===!0,...typeof X.disabledReason==="string"?{disabledReason:X.disabledReason}:{},..."quota"in X?{quota:X.quota}:{}}}function nL(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 U2(X,J){return h1(X).find(($)=>y($)&&$.id===J)}function DQ(X){if(!y(X[E0]))X[E0]={};return X[E0]}function V5(X){let J=DQ(X);if(!y(J[$8]))J[$8]={};return J[$8]}function F9(X,J){let $=LQ(X),Y=Object.hasOwn($,J)?$[J]:void 0;return y(Y)?Y:void 0}function K2(X,J,$){Object.defineProperty(V5(X),J,{value:$,enumerable:!0,writable:!0,configurable:!0})}function FQ(X,J){let $=X[E0];if(!y($))return;let Y=$[V2];if(!y(Y)||!Object.hasOwn(Y,J))return;let G=Y[J];return Y6(G)?G:void 0}function PQ(X,J){let $=F9(X,J)?.credentialEpoch;return Y6($)?$:void 0}function j2(X,J){return Math.max(FQ(X,J)??0,PQ(X,J)??0)+1}function OQ(X,J){let $=[...J];if($.length===0)return;let Y=DQ(X),G=y(Y[V2])?Y[V2]:{},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(Y6(W))z(Z,W);for(let Z of $)z(Z,Math.max(FQ(X,Z)??0,PQ(X,Z)??1));Y[V2]=Q}function P9(X,J,$,Y){let G=LQ(X),Q=lL(J),z=new Set,Z=[];for(let W of h1(X)){let B=dL(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"),N=j?KQ(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",...N?{staged:N}:{}});continue}z.add(H);let K=W.type==="api"?"api":"oauth",q=Object.hasOwn(G,H),F=q?iL(G[H],$):void 0,O=nL(W,Q[H]),_=W.enabled!==!1,C=F?F.credentialEpoch:q?void 0:1,L=typeof W.accountId==="string"&&W.accountId?W.accountId:void 0,P={id:H,type:K,enabled:_,needsFirstReading:F?F.needsFirstReading:K==="oauth",hasEntry:q,candidate:!1,...typeof W.label==="string"?{label:W.label}:{},...typeof W.addedAt==="number"?{addedAt:W.addedAt}:{},...L!==void 0?{identity:L}:{},...O?{credential:O,fingerprint:Y8(O)}:{},...F?{credentialEpoch:F.credentialEpoch}:{},...N?{staged:N}:{},...F?.disabledReason!==void 0?{disabledReason:F.disabledReason}:{},...F&&"quota"in F?{quota:F.quota}:{},...sL(Q[H],O,C,L,Y),stamp:cL(O,C,L,Q[H])};if(q&&!F)P.invalid="entry";else P.candidate=_&&O!==void 0&&!j;Z.push(P)}return Z}function sL(X,J,$,Y,G){if(!y(X)||!Object.hasOwn(X,O6))return{};let Q=g4(X,J,$,Y);if(Q===void 0)return{providerStateDropped:"uncovered"};let z=X[O6];if(!G?.validate(z))return{providerStateDropped:"invalid"};if(y1(G,z)!==Q)return{providerStateDropped:"uncovered"};return{providerState:z}}function x0(X){return X.identity??X.id}function m4(X,J){if(X===void 0||X>J+W5)return J;return Math.max(J,X+1)}function U5(X,J){return m4(X,J)>J+W5}function f1(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 MQ(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 _Q(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 AQ(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)&&!B5(X.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var N2="transition",TQ="transitionMark";function aL(X){if(!y(X))return;let J=X[N2];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 u4(X,J,$){if($.enabled)y4(X,J);else q9(X,J,$.reason??"");if(!X.rosterRow(J))return;let Y=X.entry(J)??{credentialEpoch:1,needsFirstReading:!0};if(X.setEntry(J,{...Y,[TQ]:$.mark}),!$.enabled)return;let G=X.rows().find((Q)=>Q.id===J);if(G?.type==="oauth"&&G.identity!==void 0)w1(X,G.identity)}function oL(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 rL(X){if(!X.binding)return!1;return X.replace===!0||X.dispatch===void 0}function tL(X,J,$,Y={}){let G=y(J.accounts)?J.accounts:{},Q=new Map;for(let z of P9(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=b6(Z[_0]);if(!W?.binding)continue;if(W.digest!==T8(z.credential))continue;let B=z.credentialEpoch??1;if(W.credentialEpoch>B){if(!rL(W))continue;if(Y.requireCredentialStamps){if(W.dispatch===void 0)continue;if(W.dispatch!==o8(oL(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===o8(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!==o8(z.credential))continue;let H=aL(Z[_0]);if(H&&F9(X,z.id)?.[TQ]!==H.mark)Q.set(z.id,{kind:"transition",transition:H})}}return Q}function K5(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(x1))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 j5(X,J,$,Y={}){let G=tL(X,J,$,Y);if(G.size===0)return{config:X,torn:[]};let Q=structuredClone(X),z={rows:()=>P9(Q,J,$),rosterRow:(Z)=>U2(Q,Z),entry:(Z)=>F9(Q,Z),setEntry:(Z,W)=>K2(Q,Z,W)};for(let[Z,W]of G)if(W.kind==="replace")K5(z,Z,W.stamp.credentialEpoch,W.stamp.binding);for(let[Z,W]of G)if(W.kind==="identity")c9(z,Z,W.identity);else if(W.kind==="transition")u4(z,Z,W.transition);else if(W.stamp.binding.identity!==void 0)w1(z,W.stamp.binding.identity);return{config:Q,torn:[...G.keys()]}}function N5(X,J,$,Y={}){let{config:G,torn:Q}=j5(X,J,$,Y),z=P9(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 q5(X){try{return await eL(X,"utf8")}catch(J){if(J.code==="ENOENT")return;throw J}}function RQ(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 _6(X){for(let J=0;J<3;J++){let $=await q5(X.configPath),Y=await q5(X.statePath),G=await q5(X.configPath);if($!==G){if(J<2)await XD(2+Math.floor(Math.random()*4));continue}let Q=NQ(RQ($));if(Q.status==="error")return{status:"error",file:"config",reason:Q.reason};let z=qQ(RQ(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:N5(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 G8(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 IQ{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 N5(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){l9(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(),U2(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 V5(this.config)}entry(X){return this.entries(),F9(this.config,X)}setEntry(X,J){K2(this.config,X,J)}async completeTorn(){let{config:X,torn:J}=j5(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 h1(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);OQ(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:f4,accounts:J,[E0]:{...z,schemaVersion:D9,[$8]: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:f4,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 L5(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 L5(this.ctx.configPath)}async write(X,J,$,Y=!0,G=!1,Q){await EQ(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 bQ(X,J){let $=new L9(X.lockDefaults,X.lockEnv),Y={writes:0};try{for(let Z of X.storeLocks)await $.acquire(Z);let G=await _6(X);if(G.status==="error")throw G8(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=f4,Q[E0]={schemaVersion:D9,[$8]:{}};let z={operation:"initialize",rowId:void 0};return await M6(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 g1(G,"initialize",void 0,Y)}finally{await $.releaseAll()}}async function s0(X,J,$,Y,G,Q={}){let z=J.held.length;try{for(let B of X.storeLocks)await J.acquire(B);let Z=await _6(X);if(Z.status!=="ready")throw G8(Z,Y.operation,Y.rowId,$.writes>0?"after-first-write":"before-first-write");let W=new IQ(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 g1(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 CQ)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 SQ)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 H2)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 H6(X,J,$,Y,G){let Q=new L9(X.lockDefaults,X.lockEnv),z={writes:0};try{return await G(Q,z)}catch(Z){let W=g1(Z,J,$,z);if(W.kind!=="after-persist-hook")await UQ(J,Y,$,W,X.logger);throw W}finally{await Q.releaseAll()}}function g6(X,J){return{...X.rowLockOptions,name:`row-${encodeURIComponent(x0(J))}`,path:X.ctx.statePath}}async function r8(X,J,$){let Y=await _6(X.ctx);if(Y.status!=="ready")throw G8(Y,J,$);let G=Y.rows.find((B)=>B.id===$),Q=F9(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"))l9(J,$,Q.staged);if(!G&&y(W)&&Object.hasOwn(W,"staged"))l9(J,$,W.staged);if(!G)throw Q8(J,$);return{result:Y,row:G}}function Q8(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 A6(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 q2(X,J,$,Y){let{ctx:G}=X,Q=new L9(G.lockDefaults,G.lockEnv),z={writes:0};try{if(!Y6($?.credentialEpoch))throw x("pull",J,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await s0(G,Q,z,{operation:"pull",rowId:J},async(Z)=>{Z.assertNotStaged(J);let W=Z.row(J);if(!W)throw Q8("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`);A6("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 g1(Z,"pull",J,z)}finally{await Q.releaseAll()}}function t8(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 p4(X,J,$,Y,G){if(Y===void 0||!X?.merge)return{kind:"set",value:G};return{kind:"set",value:t8(X,J,$,X.merge(structuredClone(Y),structuredClone(G)),"the merged provider state")}}function kQ(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:t8(X,"replace",J.id,z,"the provider state onReplace returned")}}function xQ(X,J,$,Y,G){if(J.kind==="set")return y1(X,J.value);if(J.kind==="clear")return;return g4($,Y?.credential,G,Y?.identity)}async function wQ(X,J,$,Y,G={}){B6("updateProviderState");let{ctx:Q}=X,z="updateProviderState";return H6(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(!Y6(H))throw x(z,J,"invalid-input","the credential epoch the provider state was read at is required");let{row:U}=await r8(X,z,J);await Z.acquire(g6(X,U));for(let j of G.extraLocks??[])await Z.acquire(j);return s0(Q,Z,W,{operation:z,rowId:J},async(j)=>{let N=j.row(J);if(!N)throw Q8(z,J);if(x0(N)!==x0(U))throw x(z,J,"row-key-changed",`row ${J}'s wire identity changed while its lock was being taken`,!0);if(N.invalid)throw x(z,J,"invalid-row",`row ${J} failed validation`);if(!N.credential)throw x(z,J,"no-credential",`row ${J} holds no credential`);if(A6(z,N),(N.credentialEpoch??1)!==H||N.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 q=await D5(j,B,z,N,Y);if(q.kind!=="changed")return{id:J,outcome:"unchanged",...q.kind==="unchanged"&&q.value!==void 0?{providerState:q.value}:{}};return j.setStateAccount(J,q.account),await j.commitState(),q.value===void 0?{id:J,outcome:"cleared"}:{id:J,outcome:"updated",providerState:q.value}})})}var vQ=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function D5(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=b6(H);if(!y(H)||!U?.binding||U.digest!==T8(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),N=await A8($,()=>G(j,Y));if(Q&&N===vQ)return{kind:"declined"};let K=N===void 0?void 0:t8(J,$,z,N,"the provider state the mutator returned"),q=B!==void 0&&Object.hasOwn(B,O6);if(K===void 0?!q: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[O6];let O={...H};delete O.providerState,F[_0]=O}else{F[O6]=K;let O=y1(J,K);if(U.providerState!==O)F[_0]={...H,providerState:O}}return{kind:"changed",...K!==void 0?{value:K}:{},account:F}}import{randomUUID as yQ}from"node:crypto";async function P2(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:N,staged:K,torn:q,invalid:F}=Q;return{id:z,type:Z,label:W,enabled:B,disabledReason:H,identity:U,credentialEpoch:j,stamp:N,staged:K,torn:q,invalid:F}}),G=await A8(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 JD=["access","refresh","expires","lastRefreshedAt","apiKey"];function $D(X){return{baseURL:String(X.baseURL).trim(),authHeader:X.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function YD(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"}:$D(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 hQ(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 L2(X,J,$,Y,G={}){let Q=YD(J,$,Y),z=J.stateAccount($),Z=G.providerState??{kind:"keep"},W=J.row($)?.credentialEpoch??J.entry($)?.credentialEpoch,B=typeof W==="number"?W:1,H=xQ(X.ctx.providerState,Z,z,z&&Object.hasOwn(z,O6)?J.row($):void 0,B),U=typeof z?.lastRefreshedAt==="number"?z.lastRefreshedAt:void 0,j=Q.type==="oauth"?G.stamp??m4(U,X.ctx.now()):void 0,N={...z??{}};for(let F of JD)delete N[F];if(G.clearErrors)delete N.lastRefreshError,delete N.lastQuotaRefreshError,delete N.quota;if(Z.kind==="clear")delete N[O6];else if(Z.kind==="set")N[O6]=Z.value;let K=_Q(Q,j),q={...N,...MQ(Q,j),[_0]:{...G.staged?{staged:G.staged}:{},...G.transition!==void 0?{[N2]:G.transition}:{},...H5(K,B,G.binding??hQ(J,$,K,G.identity),{replace:G.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:K,account:q}}async function D2(X,J,$){return X.setStateAccount(J,$.account),await X.commitState($.stored),$.stored}async function O2(X,J,$,Y,G={}){return D2(J,$,L2(X,J,$,Y,G))}async function GD(X,J,$){if(!J.credential||J.stamp!=="bound")return;let Y=X.stateAccount(J.id),G=g4(Y,J.credential,J.credentialEpoch??1,J.identity);X.setStateAccount(J.id,{...Y??{},[_0]:H5(J.credential,J.credentialEpoch??1,hQ(X,J.id,J.credential,$),G!==void 0?{providerState:G}:{})}),await X.commitState()}function P5(X,J,$){let Y=X==="add"?v1(J):void 0;if(Y)throw x(X,J,"invalid-input",Y);let G=AQ($,{baseURLOptional:X==="rotate"});if(G)throw x(X,J,"invalid-input",G)}function M2(X,J,$,Y){if(!$)throw Q8(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 u1(X,J,$){if($!==void 0&&!Y6(y($)?$.credentialEpoch:void 0))throw x(X,J,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function _2(X,J,$,Y){if(!$)throw Q8(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 F2(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 c4(X,J){return x(X,J,"row-key-changed",`row ${J}'s wire identity changed while its lock was being taken`,!0)}function QD(X,J,$,Y){let{id:G,credential:Q,identity:z}=$;if(!X.ctx.requireCredentialStamps||J.rosterRow(G)||!m1(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=b6(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]=P9({accounts:[f1({id:G,credential:H,identity:B.binding.identity,addedAt:0})],[E0]:{rows:{[G]:{credentialEpoch:j2(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(T8(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(o8(Q)!==B.dispatch)return Z();if(B.providerState!==void 0&&U.providerState===void 0)return Z();if(Y!==void 0&&y1(X.ctx.providerState,Y)!==B.providerState)return Z();return U}function zD(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=b6(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 N=Y===void 0?void 0:d9(Y),K=H?.[O6],q=K===void 0?void 0:d9(K);if(j.providerState!==N||j.providerState!==q)return B();if(T8(Q)!==U.digest||o8(Q)!==U.dispatch)return B();let F=W?J.config:{accounts:[{...f1({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=P9(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(j2(J.config,G)!==U.credentialEpoch)return B();return J.roster().push({...f1({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 fQ(X,J,$={}){B6("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 H6(Y,"add",G,$.onFailure,async(H,U)=>{P5("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 N=J.providerState===void 0?void 0:t8(Y.providerState,"add",G,J.providerState);if(await H.acquire(g6(X,{id:G,identity:z})),Q.type==="oauth")await H.acquire($.providerLock??X.providerLock);for(let K of $.extraLocks??[])await H.acquire(K);return s0(Y,H,U,{operation:"add",rowId:G},async(K)=>{await P2(K,G,$.protect);let q=y(K.state.accounts)?K.state.accounts:{},F=Object.entries(q).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)||m1(K.state,G)))return zD(X,K,J,N);if(j==="rotate"){K.assertNotStaged(G);let X0=K.rows().find((w)=>w.fingerprint===Y8(Q));if(X0)K.assertNotStaged(X0.id)}if(j==="refuse"){let X0=K.rows().find((L0)=>L0.fingerprint===Y8(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||m1(K.state,G))throw x("add",G0,"credential-exists",`row ${G0} already holds this secret or id`)}if(j==="stage-duplicate"&&(K.rosterRow(G)||m1(K.state,G)))throw x("add",G,"id-exists",`row ${G} already exists`);let O=QD(X,K,J,N),_=K.rows(),C=Y8(Q),L=j==="rotate"&&!O&&_.find((X0)=>X0.invalid===void 0&&X0.fingerprint===C);if(L){if(K.assertNotStaged(L.id),A6("add",L),z!==void 0&&L.identity!==void 0&&z!==L.identity)throw F2("add",L.id);let X0=L2(X,K,L.id,Q,{...N!==void 0?{providerState:p4(Y.providerState,"add",L.id,L.providerState,N)}:{}});await K.completeTorn(),K.assertNotStaged(L.id);let w=await D2(K,L.id,X0);return{id:L.id,outcome:"rotated",credential:w,credentialEpoch:L.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(A6("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 F2("add",G);if(!P.hasEntry)K.setEntry(G,{credentialEpoch:1,needsFirstReading:Q.type==="oauth"});let X0=L2(X,K,G,Q,{clearErrors:!0,...N!==void 0?{providerState:{kind:"set",value:N}}:{}});await K.completeTorn();let w=await D2(K,G,X0);if(!P.hasEntry)await K.commitConfig();return{id:G,outcome:"completed",credential:w,credentialEpoch:P.credentialEpoch??1}}let A=j2(K.config,G);if(!Y6(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(f1({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 k="added";if(J.disabled)q9(K,G,J.disabled.reason),k="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))q9(K,G,z5),k="added-disabled"}if(O?.credential)return await K.commitConfig(),{id:G,outcome:k,credential:O.credential,credentialEpoch:O.credentialEpoch??A};K.dropStateAccount(G);let p=L2(X,K,G,Q,{...J.stage&&J.disabled?{staged:{reservation:J.stage.reservation,disabledReason:J.disabled.reason,...Z!==void 0?{label:Z}:{},...N!==void 0?{providerState:d9(N)}:{}}}:{},...N!==void 0?{providerState:{kind:"set",value:N}}:{}});if(j==="rotate")await K.completeTorn();let i=await D2(K,G,p);return await K.commitConfig(),{id:G,outcome:k,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 gQ(X,J,$,Y={},G={}){B6("replace");let{ctx:Q}=X,z=await H6(Q,"replace",J,G.onFailure,async(Z,W)=>{P5("replace",J,$),u1("replace",J,G.attribution);let B=Y.providerState===void 0?void 0:t8(Q.providerState,"replace",J,Y.providerState),{row:H}=await r8(X,"replace",J);if(await Z.acquire(g6(X,H)),$.type==="oauth")await Z.acquire(G.providerLock??X.providerLock);for(let U of G.extraLocks??[])await Z.acquire(U);return s0(Q,Z,W,{operation:"replace",rowId:J},async(U)=>{if(G.attribution!==void 0)_2("replace",J,U.row(J),G.attribution),await U.completeTorn();let j=M2("replace",J,U.row(J),$);if(x0(j)!==x0(H))throw c4("replace",J);let N=U.entry(J)?.credentialEpoch,K=(typeof N==="number"?N:1)+1;if(!Y6(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 q=kQ(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(K5(U,J,K,F),Y.identity!==void 0)w1(U,Y.identity);let O=await O2(X,U,J,$,{clearErrors:!0,binding:F,providerState:q});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 mQ(X,J,$,Y={},G={}){B6("rotate");let{ctx:Q}=X;return H6(Q,"rotate",J,G.onFailure,async(z,Z)=>{P5("rotate",J,$),u1("rotate",J,G.attribution);let W=Y.providerState===void 0?void 0:t8(Q.providerState,"rotate",J,Y.providerState),{row:B}=await r8(X,"rotate",J);if(await z.acquire(g6(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 s0(Q,z,Z,{operation:"rotate",rowId:J},async(H)=>{if(G.attribution!==void 0)_2("rotate",J,H.row(J),G.attribution),await H.completeTorn();let U=M2("rotate",J,H.row(J),$);if(x0(U)!==x0(B))throw c4("rotate",J);if(A6("rotate",U),Y.identity!==void 0&&U.identity!==void 0&&Y.identity!==U.identity)throw F2("rotate",J);let j=Y.identity!==void 0&&U.identity===void 0?Y.identity:void 0,N=await O2(X,H,J,$,{identity:j,...W!==void 0?{providerState:p4(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)c9(H,J,Y.identity),K=!0;if(K)await H.commitConfig();return{id:J,credential:N}},{completeTorn:G.attribution===void 0})})}async function uQ(X,J,$,Y,G){B6(J);let{ctx:Q}=X,z=Q.providerState,Z=G.attribution,W=G.providerState;return H6(Q,J,$,G.onFailure,async(B,H)=>{if(u1(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 r8(X,J,$);await B.acquire(g6(X,U));for(let j of G.extraLocks??[])await B.acquire(j);return s0(Q,B,H,{operation:J,rowId:$},async(j)=>{await P2(j,$,G.protect),j.assertNotStaged($);let N=j.row($),K=Y.enabled?M2("enable",$,N):N;if(!K||!j.rosterRow($))throw Q8(J,$);if(x0(K)!==x0(U))throw c4(J,$);if(Z!==void 0)_2(J,$,K,Z);if(Y.enabled&&K.disabledReason?.startsWith(x1))throw x("enable",$,"identity-contradicted",`row ${$} needs an identity-validated credential replacement before it can be enabled`);let q=!Y.enabled||!K.enabled||K.disabledReason!==void 0;if(Y.enabled&&q&&K.type==="oauth"){let L=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(L)throw x("enable",$,"duplicate-identity",`row ${L.id} is enabled with the same identity as row ${$}`)}if(W===void 0||z===void 0){if(await j.completeTorn(),!q)return{id:$};if(Y.enabled)y4(j,$);else q9(j,$,Y.reason);return await j.commitConfig(),{id:$}}if(!K.credential)throw x(J,$,"no-credential",`row ${$} holds no credential`);A6(J,K);let F=await D5(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(q){if(Y.enabled)y4(j,$);else q9(j,$,Y.reason);await j.commitConfig()}return O}if(!q)return j.setStateAccount($,F.account),await j.commitState(),O;let _=Y.enabled?{mark:yQ(),enabled:!0}:{mark:yQ(),enabled:!1,reason:Y.reason},C=F.account[_0];return j.setStateAccount($,{...F.account,[_0]:{...C,[N2]:_}}),await j.commitState(),u4(j,$,_),await j.commitConfig(),O},{completeTorn:!1})})}function pQ(X,J,$,Y={}){return uQ(X,"disable",J,{enabled:!1,reason:$},Y)}function cQ(X,J,$={}){return uQ(X,"enable",J,{enabled:!0},$)}async function lQ(X,J,$={}){B6("remove");let{ctx:Y}=X;return H6(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(u1("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 _6(Y);if(Z.status!=="ready")throw G8(Z,"remove",J);let W=Z.rows.find((H)=>H.id===J);if(!W&&!m1(Z.state,J))throw Q8("remove",J);let B=x0(W??{id:J});await G.acquire(g6(X,W??{id:J}));for(let H of $.extraLocks??[])await G.acquire(H);return s0(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),N=m1(H.state,J);if(!j&&!N)throw Q8("remove",J);if(x0(j??{id:J})!==B)throw c4("remove",J);if(z!==void 0)if(j)A2(J,j,z);else ZD(X,H,J,z);let K=$.protect;if(K){let q={row:j,config:H.snapshot.config,state:H.snapshot.state},F=await A8("remove",()=>K(J,q));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(N)H.dropStateAccount(J),await H.commitState();return{id:J,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function A2(X,J,$,Y="remove"){if(_2(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 ZD(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=b6(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]=P9({accounts:[f1({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 m1(X,J){let $=X.accounts;return y($)&&Object.hasOwn($,J)}function F5(X){return y(X)&&typeof X.id==="string"?X.id:void 0}function WD(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=F5(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 BD(X,J){let $=new Map;for(let Q of X){let z=F5(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)=>F5(Q)===void 0?Q:Y[G++])}async function dQ(X,J,$={}){B6("reorder");let{ctx:Y}=X,G=$.onFailure;return H6(Y,"reorder",void 0,G&&((Q,z)=>G(z)),async(Q,z)=>{for(let Z of $.extraLocks??[])await Q.acquire(Z);return s0(Y,Q,z,{operation:"reorder",rowId:void 0},async(Z)=>{let W=Z.roster(),B=WD(W,J);if(B)throw new K0({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:B});let H=[...J],U=BD(W,H);if(U.every((j,N)=>j===W[N]))return{ids:H,outcome:"unchanged"};return Z.config.accounts=U,await Z.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function iQ(X,J,$,Y,G={}){return B6("recordIdentity"),H6(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(!Y6(Z))throw x("recordIdentity",J,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:W}=await r8(X,"recordIdentity",J);await Q.acquire(g6(X,W)),await Q.acquire(G.providerLock??X.providerLock);for(let B of G.extraLocks??[])await Q.acquire(B);return s0(X.ctx,Q,z,{operation:"recordIdentity",rowId:J},async(B)=>{let H=M2("recordIdentity",J,B.row(J));if(x0(H)!==x0(W))throw c4("recordIdentity",J);if(A6("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 F2("recordIdentity",J);if(H.identity===void 0)await GD(B,H,$);let U=c9(B,J,$);return await B.commitConfig(),{id:J,disabled:U}})})}function sQ(X){let J=X[E0];return y(J)&&y(J.publications)?J.publications:{}}function aQ(X,J){let $=sQ(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"||!Y6(G.credentialEpoch))||Y.finalized.some((G)=>!y(G)||typeof G.id!=="string"||!Y6(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 oQ(X,J){let $=await _6(X.ctx);if($.status!=="ready")throw G8($,"publishRoster",J);return aQ($.config,J)}function HD(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"||v1(G.id)||Y.has(G.id)||!G.attribution)$();if(Y.add(G.id),u1("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"||v1(G))||new Set(J.order).size!==J.order.length)$()}function rQ(X,J){X.entries();let $=X.config[E0],Y={...sQ(X.config)};Object.defineProperty(Y,J.operationId,{value:J,enumerable:!0,writable:!0,configurable:!0}),$.publications=Y,delete $.publicationOrder}function VD(X,J,$){let Y=new Set;for(let z of h1(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 nQ(X,J){await X.assertAll();for(let Y of J.removed)if(b6(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=b6(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 rQ(X,$),await X.commitConfig({durable:!0}),$}async function tQ(X,J,$={}){return B6("publishRoster"),H6(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=d9(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 _6(X.ctx);if(W.status!=="ready")throw G8(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(g6(X,{id:U}));await Y.acquire($.providerLock??X.providerLock);for(let U of $.extraLocks??[])await Y.acquire(U);let H=await s0(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 N=aQ(U.config,J.operationId);if(N){if(N.planDigest!==Q)throw x("publishRoster",J.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(N.phase==="cleaned")return{outcome:"already-cleaned",receipt:N};return U.markPublicationDecision(),await U.syncConfig(),{outcome:"cleaned",receipt:await nQ(U,N)}}HD(X,J);let K=VD(U,J,j),q=[];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(A2(P.id,A,P.attribution,"publishRoster"),!A.credential||P.fingerprint!==void 0&&Y8(A.credential)!==P.fingerprint)throw x("publishRoster",P.id,"attribution","the removed secret no longer matches");q.push(A)}let F=[];for(let P of J.finalize){let A=j.find((w)=>w.id===P.id),T=b6(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 k=U.stateAccount(P.id),p=U.rosterRow(P.id),i=k?.[O6],X0=i===void 0?void 0:d9(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");A2(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&&q.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 P2(U,J.operationId,$.protect);let C={operationId:J.operationId,planDigest:Q,phase:"committed",removed:q.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 L=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)),...L],rQ(U,C),await U.syncState(),await U.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await nQ(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 O5{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 L9(Y.lockDefaults,Y.lockEnv),Q={writes:0};try{let z=await s0(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)A6("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 q2($,X,{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},Z)}catch(z){this.firedAtLoad.delete(X);let Z=g1(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 UD}from"node:crypto";function M5(X,J){if(l9("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 eQ(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 Xz(X,J,$,Y={}){B6("refresh");let{ctx:G}=X;return H6(G,"refresh",J,Y.onFailure,async(Q,z)=>{let{row:Z}=await r8(X,"refresh",J);M5(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(g6(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 s0(G,Q,{writes:0},{operation:"refresh",rowId:J},async(O)=>{let _=M5(J,O.row(J));if(A6("refresh",_),!_.hasEntry)O.setEntry(J,{credentialEpoch:1,needsFirstReading:!0}),await O.commitConfig(),_=M5(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(U5(H.credential.lastRefreshedAt,G.now()))throw eQ(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:t8(G.providerState,"refresh",J,U.providerState,"the provider state the provider returned"),N=await s0(G,Q,z,{operation:"refresh",rowId:J},async(K)=>{let q=K.row(J),F=K.entry(J);if(!q||q.invalid||!F||F.credentialEpoch!==H.credentialEpoch||q.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`});A6("refresh",q);let O=await Y.refuse?.(q);if(O!==void 0)return{refused:O};let _=G.now(),C=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(U5(C,_))throw eQ(J);let L={type:"oauth",access:U.access,refresh:U.refresh,expires:U.expires},P=q.identity!==void 0&&U.identity!==void 0&&q.identity!==U.identity?{expectedIdentity:q.identity,returnedIdentity:U.identity}:void 0,A=P?{mark:UD(),enabled:!1,reason:`${x1}${JSON.stringify(P)}`}:void 0,T=q.identity===void 0&&U.identity?U.identity:void 0,k=await O2(X,K,J,L,{stamp:m4(C,_),transition:A,identity:T,...j!==void 0?{providerState:p4(G.providerState,"refresh",J,q.providerState,j)}:{}});if(A!==void 0)u4(K,J,A),await K.commitConfig();let p=q.identity;if(T!==void 0)c9(K,J,T),p=T,await K.commitConfig();return{stored:k,identity:p,contradiction:P,refused:void 0}});if(N.refused!==void 0)return{status:"refused",rowId:J,reason:N.refused};if(N.contradiction!==void 0)return{status:"identity-contradicted",rowId:J,...N.contradiction,credential:N.stored};if(Y.onPersisted)try{let K=Y.onPersisted;await A8("refresh",()=>K(J,N.stored))}catch(K){throw new K0({operation:"refresh",rowId:J,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:N.stored,message:"the after-persist hook threw; the rotation stays committed",cause:K})}return{status:"rotated",rowId:J,credential:N.stored,...N.identity!==void 0?{identity:N.identity}:{}}})}import{isDeepStrictEqual as KD}from"node:util";var R2=Object.freeze(["version","accounts",E0]);function _5(X){let J={};for(let[$,Y]of Object.entries(X))if(!R2.includes($))T2(J,$,Y);return J}function T2(X,J,$){Object.defineProperty(X,J,{value:$,enumerable:!0,writable:!0,configurable:!0})}function jD(X,J){let $={};for(let[Y,G]of Object.entries(X))if(R2.includes(Y))T2($,Y,G);else if(Object.hasOwn(J,Y))T2($,Y,J[Y]);for(let[Y,G]of Object.entries(J))if(!Object.hasOwn(X,Y))T2($,Y,G);return $}function Jz(X){return new K0({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:X})}async function $z(X){let J=await _6(X.ctx);if(J.status==="error")return J;return{status:J.status,settings:_5(J.config)}}async function Yz(X,J,$={}){B6("updateSettings");let{ctx:Y}=X,G=$.onFailure;return H6(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 _6(Y);if(W.status!=="ready")throw G8(W,"updateSettings",void 0);let B=_5(W.config),H=structuredClone(B),U=await A8("updateSettings",()=>J(H)),j=U===void 0?H:U;if(!y(j))throw Jz("the settings mutator must produce an object");let N=R2.filter((F)=>Object.hasOwn(j,F));if(N.length>0)throw Jz(`settings cannot set the pool-owned key(s) ${N.join(", ")}`);if(KD(j,B))return{settings:B,outcome:"unchanged"};let K=jD(W.config,j),q={operation:"updateSettings",rowId:void 0};return await M6(Y.configPath,K,{beforeRename:async()=>{await Y.onStep?.("before-config-write",q),await Q.assertAll()}}),z.writes++,await Y.onStep?.("after-config-write",q),{settings:_5(K),outcome:"updated"}}finally{await Q.releaseTo(Z)}})}var Gz=new Map;function ND(X){let J=Gz.get(X);if(!J)J={removedIds:new Set,firedAtLoad:new Set},Gz.set(X,J);return J}function Qz(X){if(X.status==="ready")return{status:"ready",schemaVersion:D9,rows:X.rows};if(X.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(X.config.accounts)?X.config.accounts:[]};return X}function z8(X){let J=ND(X.configPath),$={...Z5,...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 O5(()=>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 _6(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 Qz(z)},async read(){return Qz(await _6(Y))},async initialize(z={}){return{status:await bQ(Y,z.dropKeys??[])}},add:(z,Z)=>fQ(Q,z,Z),publishRoster:(z,Z)=>tQ(Q,z,Z),publication:(z)=>oQ(Q,z),replace:(z,Z,W,B)=>gQ(Q,z,Z,W,B),rotate:(z,Z,W,B)=>mQ(Q,z,Z,W,B),updateProviderState:(z,Z,W,B)=>wQ(Q,z,Z,W,B),disable:(z,Z,W)=>pQ(Q,z,Z,W),enable:(z,Z)=>cQ(Q,z,Z),remove:(z,Z)=>lQ(Q,z,Z),reorder:(z,Z)=>dQ(Q,z,Z),readSettings:()=>$z(Q),updateSettings:(z,Z)=>Yz(Q,z,Z),recordIdentity:(z,Z,W,B)=>iQ(Q,z,Z,W,B),refresh:(z,Z,W)=>Xz(Q,z,Z,W),recordQuota:(z,Z,W)=>q2(Q,z,Z,W),requestReading:(z)=>G.fire(z,"admission"),pullsSettled:()=>G.settled()}}var qD=[/\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 R5(X={}){let{redactStrings:J}=C2({...X,extraValuePatterns:[...qD,...X.extraValuePatterns??[]]});return($)=>J($)}class k6 extends Error{code;constructor(X,J,$){super(J,$);this.name="CommandError",this.code=X}}var zz=/^[a-z][a-z0-9-]{0,63}$/,A5={code:"action-failed",text:"That action failed."},LD=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 l4(X){if(X instanceof k6)return{code:zz.test(X.code)?X.code:A5.code,text:X.message};if(X instanceof K0)return{code:`pool-${X.kind}`,text:LD.has(X.kind)?X.message:`The account pool could not do that (${X.kind}).`};return A5}var Zz="This cannot be undone. Continue?",DD=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function FD(X){let J=X.toLowerCase().replace(/[-_]/g,"");return DD.has(J)||J.endsWith("token")||J.endsWith("key")||J.endsWith("secret")}function PD(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function T5(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)=>T5(G,`${J}[${Q}]`,$));if(!PD(X))return X;let Y={};for(let[G,Q]of Object.entries(X)){if(FD(G)){$.dropped.push(`${J}.${G}`);continue}Object.defineProperty(Y,G,{value:T5(Q,`${J}.${G}`,$),enumerable:!0,writable:!0,configurable:!0})}return Y}function Wz(X,J,$){let Y={redact:$.redact,dropped:[],redacted:[]},G=T5(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 OD(X){return{value:String(X.value),label:String(X.label)}}function MD(X){switch(X.kind){case"choice":return{kind:"choice",id:X.id,label:X.label,choices:(X.choices??[]).map(OD),...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 C5(X){if(X.irreversible===!0)return{message:X.confirm||Zz,irreversible:!0};if(X.confirm)return{message:X.confirm,irreversible:!1};return}function Bz(X){let J=C5(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(MD),...J?{confirm:J}:{}}}function _D(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 AD(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:_D(X.account)}:{},...X.facts!==void 0?{facts:X.facts}:{},actions:(X.actions??[]).map(Bz)}}function TD(X){let{content:J}=X;return{id:X.id,slot:X.slot,title:X.title,lines:(J.lines??[]).map(String),items:(J.items??[]).map(AD),actions:(J.actions??[]).map(Bz),...J.facts!==void 0?{facts:J.facts}:{}}}function Hz(X,J,$){return{command:X,title:J,sections:$.map(TD)}}function Vz(X,J,$,Y){return Wz({command:X,menu:Hz(X,J,$)},X,Y)}function Uz(X,J,$,Y,G){return Wz({command:X,ok:Y.ok,text:String(Y.text),...!Y.ok&&Y.code!==void 0?{code:zz.test(Y.code)?Y.code:"refused"}:{},...Y.needsConfirmation?{needsConfirmation:!0}:{},menu:Hz(X,J,$)},X,G)}var qz="disabled from the command menu";function RD(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function e8(X){return RD(X)?{...X}:{}}function CD(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 ED(X,J){return X.label??J??X.id}function E2(X,J){return G6(X.quota)?f0(X.quota,J):void 0}function Lz(X,J){return`${X} ${J}${X===1?"":"s"}`}var d4="Actions";function SD(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 Kz(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 jz(X){return l4(X).text}async function ID(X){let J=await X.read(),$=await X.readSettings();return{load:J,rows:CD(J),settings:$.status==="error"?{}:$.settings}}function S2(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:ED(X,$)}}function bD(X,J){let{store:$,extraLocks:Y}=X,G=Y?{extraLocks:Y}:{},Q=J.rows.map((U)=>U.id),z=SD(J.load),Z=J.rows.filter((U)=>U.enabled).length,W=J.rows.map((U,j)=>{let{account:N,name:K}=S2(U,X),q=[U.type==="api"?"API key":"OAuth",...N.identity!==void 0?[N.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,qz,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),L=Q.filter((A)=>A!==U.id);return L.splice(C-1,0,U.id),(await $.reorder(L,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:q,group:"Accounts",status:F,account:N,actions:O}}),B=X.accounts?.login,H=[];if(B&&!z)H.push({id:"add",label:B.label??"Add account",group:d4,knobs:B.knobs??[],run:async({values:U,invocation:j})=>{let N=await B.run(U,j);if(N.status==="cancelled")return{ok:!1,text:N.message??"Login cancelled."};if(N.status==="ready"){let K=await $.add(N.account,G);return Kz(N.account.label??K.id,K)}return N.completion.then(async(K)=>{if(!K){j.notify("Login cancelled.","warning");return}let q=await $.add(K,G);j.notify(Kz(K.label??q.id,q))},(K)=>{j.notify(`Adding the account failed: ${jz(K)}`,"error")}).catch((K)=>{j.notify(`Adding the account failed: ${jz(K)}`,"error")}),N.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:z?[z]:[J.rows.length===0?"No accounts yet":`${Lz(J.rows.length,"account")}, ${Z} enabled`],items:z?[]:W,actions:H}}}function kD(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}=S2(H,X),N=E2(H,$);return{id:H.id,label:j,group:G,status:R8(N,{now:Y,form:"compact"}),detail:R8(N,{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}=S2(H,X),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",N=R8(E2(H,$),{now:Y,form:"compact"});return`${U} (${j}): ${N}`}),B=[];if(z.length>0)B.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:d4,run:async({invocation:H})=>{let U=z.map((j)=>j.id);return await Q(U,H),`Checked quota for ${Lz(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 xD(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=e8(J.settings.routing).mode,Z=typeof z==="string"&&Q.some((K)=>K.value===z)?z:"ordered",W=rX(Z),B=J.rows.map((K)=>K.id),H=k1(B,W.placement,X.routing?.formerMainId??Z2),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 N=[{id:"mode",label:"Change mode",group:d4,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:Q,value:Z}],run:async({values:K})=>{let q=String(K.mode);return await $.updateSettings((F)=>{F.routing={...e8(F.routing),mode:q};return},G),`Routing mode set to ${Q.find((F)=>F.value===q)?.label??q}.`}}];if(B.length>1)N.push({id:"order",label:"Set order",group:d4,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:B.join(", "),required:!0}],run:async({values:K})=>{let q=String(K.order).split(/[\s,]+/).filter((O)=>O.length>0),F=await $.reorder(q,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:N}}}function wD(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 E2(G,$)?.limits??[])if(!Y.includes(Q.label))Y.push(Q.label);return Y.length>0?Y:["primary"]}function vD(X,J){let $=X.quota?.scope??"all",Y=new Map;for(let G of J.rows)for(let Q of E2(G,$)?.limits??[])if(Q.windowMinutes!==void 0&&!Y.has(Q.label))Y.set(Q.label,Nz(Q));return(G)=>Y.get(G)??G}function yD(X,J){let{store:$,extraLocks:Y}=X,G=Y?{extraLocks:Y}:{},Q=e8(J.settings.killswitch),z=Q.enabled===!0,Z=e8(Q.accounts),W=wD(X,J),B=vD(X,J),H=z?"on":"off",U=J.rows.map((j)=>{let{account:N,name:K}=S2(j,X),q=e8(Z[j.id]),F=W.filter((O)=>typeof q[O]==="number");return{id:j.id,label:K,group:`Floors · killswitch ${H}`,status:F.length===0?"no floors":F.map((O)=>`${B(O)} ≥${q[O]}%`).join(" · "),account:N,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 q[O]==="number"?{value:q[O]}:{}})),run:async({values:O})=>{return await $.updateSettings((_)=>{let C=e8(_.killswitch),L=e8(C.accounts),P=e8(L[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)L[j.id]=P;else delete L[j.id];if(Object.keys(L).length>0)C.accounts=L;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:d4,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!z}],run:async({values:j})=>{let N=j.enabled===!0;return await $.updateSettings((K)=>{K.killswitch={...e8(K.killswitch),enabled:N};return},G),`Killswitch ${N?"on":"off"}.`}}]}}}async function Dz(X){let J=await ID(X.store);return[bD(X,J),kD(X,J),xD(X,J),yD(X,J)]}var hD=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),E5=["accounts","quota","routing","limits"];function Fz(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 fD(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 gD(X,J){let $={};for(let Y of X){let G=J&&Object.hasOwn(J,Y.id)?J[Y.id]:void 0,Q=fD(Y,G);if("problem"in Q)return Q;$[Y.id]=Q.value}return{values:$}}function mD(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 i9(X){let J=X.logger??Z0("commands"),$=R5(X.redaction),Y={logger:J,redact:$},G=X.now??Date.now,Q=X.extras??[],z=X.replace??{},Z=E5.filter((j)=>!z[j]);for(let j of E5)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(hD.has(j.id)||B.has(j.id))throw Error(`extra section id ${j.id} is taken`);B.add(j.id)}async function H(j,N,K,q){try{return{id:j,slot:N,title:K.title,content:await K.build(q)}}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:N,title:K.title,content:{lines:["This section could not be loaded."]}}}}async function U(j){let N=W&&Z.length>0?await Dz({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 q of E5){let F=z[q];if(F)K.push(await H(q,q,F,j));else{let O=N.find((_)=>_.slot===q);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 q of Q)K.push(await H(q.id,"extra",q,j));return K}return{command:X.command,async open(j){let N=Fz(j,$);return Vz(X.command,X.title,await U(N),Y)},async apply(j,N){let K=Fz(N,$),q=async(L)=>Uz(X.command,X.title,await U(K),L,Y),F=j.command===X.command?mD(await U(K),j):void 0;if(!F)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let O=C5(F);if(O&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:O.message,needsConfirmation:!0});let _=gD(F.knobs??[],j.values);if("problem"in _)return q({ok:!1,code:"invalid-input",text:_.problem});let C;try{let L=await F.run({values:_.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:K});C=typeof L==="string"?{ok:!0,text:L}:{ok:L.ok,text:L.text,...L.ok?{}:{code:L.code??"refused"}}}catch(L){let P=l4(L);J.warn("command menu action failed",{command:X.command,section:j.sectionId,action:j.actionId,code:P.code,error:$(L instanceof Error?L.message:String(L))}),C={ok:!1,...P}}return q(C)}}}function uD(X){return X===null||typeof X==="string"||typeof X==="boolean"||typeof X==="number"&&Number.isFinite(X)}function S5(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(!uD(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 YO,randomUUID as GO}from"node:crypto";import{setTimeout as QO}from"node:timers/promises";import{createHash as pD}from"node:crypto";var I5=86400000,cD=300000,lD=3600000,dD=60000,iD=900000,nD=300000;function b5(X){return X instanceof Error?X.message:String(X)}function k5(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 x5(X){let J=b5(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 s6(X){return pD("sha256").update(X).digest("hex")}function p1(X){let J=s6(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(k5(X.error))G=Math.min(lD,cD*2**Math.min(Y-1,6));else G=I5;return{message:b5(X.error),checkedAt:X.now,nextRetryAt:X.now+G,retryCount:Y,tokenHash:J}}function r0(X,J,$){if(!X?.nextRetryAt||X.nextRetryAt<=$)return!1;if(!J)return!0;return X.tokenHash===s6(J)}function X9(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 i4(X){let $=(X.previous?.retryCount??0)+1,Y,G=X.error?.retryAfter;if(typeof G==="number"&&G>0)Y=G*1000;else if(x5(X.error))Y=Math.min(iD,dD*2**Math.min($-1,6));else Y=nD;return{message:b5(X.error),checkedAt:X.now,nextRetryAt:X.now+Y,retryCount:$}}function c1(X,J){if(!X?.nextRetryAt||X.nextRetryAt<=J)return!1;return!0}function w5(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 Pz}from"node:http";import{setTimeout as sD}from"node:timers/promises";var k2="app_EMoamEEZ73f0CkXaXp7hrann",a9="https://auth.openai.com",s4=1455,aD=3000,oD="cortexkit-opencode-openai-auth";function x2(X){return`${oD}/${X}`}var Mz="main",rD=`"${Mz}" is a reserved account id; choose a different label.`;function w2(X){let J=new Uint8Array(X),$=String.fromCharCode(...J);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function y5(){let J=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((Y)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[Y%66]).join(""),$=w2(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(J)));return{verifier:J,challenge:$}}function V6(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 U6(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=V6(X.id_token),$=J&&U6(J);if($)return $}if(X.access_token){let J=V6(X.access_token);return J?U6(J):void 0}return}function tD(X){return typeof X==="string"&&X.toLowerCase()===Mz}function v5(X){if(tD(X))throw Error(rD);return X}function h5(X,J,$){let Y=new URLSearchParams({response_type:"code",client_id:k2,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`${a9}/oauth/authorize?${Y.toString()}`}async function eD(X,J,$){let Y=await fetch(`${a9}/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:k2,code_verifier:$.verifier}).toString()});if(!Y.ok)throw Error(`Token exchange failed: ${Y.status}`);return await Y.json()}function XF(X){return X.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var JF=`<!doctype html>
2
2
  <html>
3
3
  <head>
4
4
  <title>CortexKit OpenAI Auth - Authorization Successful</title>
@@ -38,7 +38,7 @@ import{Ab as $X,Bb as YX,Cb as BL,Db as HL,Eb as C1,Fb as VL,La as tG,Ma as eG,N
38
38
  setTimeout(() => window.close(), 2000)
39
39
  </script>
40
40
  </body>
41
- </html>`,E2=(X)=>`<!doctype html>
41
+ </html>`,I2=(X)=>`<!doctype html>
42
42
  <html>
43
43
  <head>
44
44
  <title>CortexKit OpenAI Auth - Authorization Failed</title>
@@ -81,18 +81,18 @@ import{Ab as $X,Bb as YX,Cb as BL,Db as HL,Eb as C1,Fb as VL,La as tG,Ma as eG,N
81
81
  <div class="container">
82
82
  <h1>Authorization Failed</h1>
83
83
  <p>An error occurred during authorization.</p>
84
- <div class="error">${nD(X)}</div>
84
+ <div class="error">${XF(X)}</div>
85
85
  </div>
86
86
  </body>
87
- </html>`,S2=[],d4,X9=new Map;function Lz(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(i4,J)})}function Fz(X){X.close(()=>{}),X.closeIdleConnections?.(),setTimeout(()=>{X.closeAllConnections?.()},25).unref?.()}function n9(){return X9.size}function J9(X){if(X9.delete(X),n9()===0)s9()}async function y5(){let X=`http://localhost:${i4}/auth/callback`;if(S2.length>0)return{port:i4,redirectUri:X};if(d4)return d4;d4=(async()=>{let J=(Q,z)=>{let Z=new URL(Q.url||"/",`http://127.0.0.1:${i4}`);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=X9.get(B);if(K)K.reject(Error(q)),J9(B);else if(n9()===0)s9()}else if(n9()===0)s9();z.writeHead(200,{"Content-Type":"text/html"}),z.end(E2(q));return}if(!B){if(n9()===0)s9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(E2("Missing state parameter"));return}if(!W){if(n9()===0)s9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(E2("Missing authorization code"));return}let j=X9.get(B);if(!j){if(n9()===0)s9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(E2("Unknown state — authorization may have expired"));return}J9(B),iD(W,X,j.pkce).then((q)=>j.resolve(q)).catch((q)=>j.reject(q)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(sD);return}if(Z.pathname==="/cancel"){let W=Z.searchParams.get("state"),B=W?[W]:[...X9.keys()];z.writeHead(200),z.end("Login cancelled");for(let H of B){let U=X9.get(H);if(!U)continue;U.reject(Error("Login cancelled")),J9(H)}if(n9()===0)s9();return}z.writeHead(404),z.end("Not found")},$=Nz(J);await Lz($,"127.0.0.1");let Y=[$],G=Nz(J);try{await Lz(G,"::1"),Y.push(G)}catch(Q){let z=Q.code;if(z!=="EADDRNOTAVAIL"&&z!=="EAFNOSUPPORT")throw Fz($),Q}return S2=Y,{port:i4,redirectUri:X}})();try{return await d4}finally{d4=void 0}}function s9(){let X=S2;S2=[];for(let J of X)Fz(J)}function h5(X,J,$=300000,Y){return new Promise((G,Q)=>{if(Y?.aborted){J9(J),Q(Error("Login cancelled"));return}let z=setTimeout(()=>{if(X9.get(J))J9(J),Q(Error("OAuth callback timeout — authorization took too long"))},$),Z=()=>{if(clearTimeout(z),X9.get(J))J9(J),Q(Error("Login cancelled"))};if(Y)Y.addEventListener("abort",Z);X9.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 f5(X){let J=await fetch(`${a9}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":b2(X)},body:JSON.stringify({client_id:I2})});if(!J.ok)throw Error("Failed to initiate device authorization");let $=await J.json();return{deviceData:$,url:`${a9}/codex/device`,instructions:`Enter code: ${$.user_code}`}}async function g5(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(`${a9}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":b2(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(`${a9}/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:`${a9}/deviceauth/callback`,client_id:I2,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+pD,W);try{await uD(B,void 0,{signal:$})}catch(H){if(H instanceof Error&&H.name==="AbortError")throw Error("Device authorization cancelled");throw H}}}async function x2(X){let{label:J,headless:$=!1,signal:Y,version:G}=X;if(x5(J),$){let{deviceData:H,url:U,instructions:j}=await f5(G),q=(async()=>{let K=await g5(H,G,Y),N=Date.now(),F=Z8(K);return{id:x5(J||F||crypto.randomUUID()),label:J||void 0,type:"oauth",access:K.access_token,refresh:K.refresh_token,expires:N+(K.expires_in??3600)*1000,enabled:!0,addedAt:N,lastUsed:N,lastRefreshedAt:N,accountId:F}})();return{url:U,instructions:j,completion:q}}let{redirectUri:Q}=await y5(),z=await w5(),Z=k2(crypto.getRandomValues(new Uint8Array(32)).buffer),W=v5(Q,z,Z),B=(async()=>{try{if(Y?.aborted)throw Error("Login cancelled");let H=await h5(z,Z,void 0,Y),U=Date.now(),j=Z8(H);return{id:x5(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{J9(Z)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:B}}function w2(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 m5(X){let J=Number(X);return Number.isFinite(J)&&J>0?J:void 0}function Pz(X){return typeof X==="number"&&Number.isFinite(X)&&X>=0?X:void 0}function Oz(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=m5(X.get(`${G}-window-minutes`)),z=w2(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 Az=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function Tz(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 o9(X){if(Az.some((G)=>Tz(X,G)==="invalid"))return{};let J={},$=Oz(X,"x-codex-primary-used-percent");if($)J.primary=$;let Y=Oz(X,"x-codex-secondary-used-percent");if(Y)J.secondary=Y;return J}function d1(X){let J=Az.map(($)=>Tz(X,$));return J.includes("valid")&&!J.includes("invalid")}function Mz(X){if(!X)return;if(!Number.isFinite(X.used_percent)||X.used_percent<0||X.used_percent>100)return;let J=m5(X.window_minutes),$=w2(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 Rz(X){let J={},$=Mz(X.rate_limits?.primary);if($)J.primary=$;let Y=Mz(X.rate_limits?.secondary);if(Y)J.secondary=Y;return J}function l1(X){if(X==null||X==="")return;let J=Number(X);return Number.isFinite(J)&&J>=0?J:void 0}function _z(X){if(!X)return;if(!Number.isFinite(X.used_percent)||X.used_percent<0||X.used_percent>100)return;let J=m5(X.limit_window_seconds),$=w2(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 Cz(X){let J={},$=_z(X.rate_limit?.primary_window);if($)J.primary=$;let Y=_z(X.rate_limit?.secondary_window);if(Y)J.secondary=Y;let G=Pz(X.rate_limit_reset_credits?.available_count);if(G!==void 0)J.resetCreditsAvailable=G;let Q=Pz(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=l1(z.limit),B=l1(z.used),H=l1(z.remaining),U=l1(z.used_percent),j=l1(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:w2(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=l1(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 xF,statSync as wF}from"node:fs";import{tmpdir as zZ,userInfo as vF}from"node:os";import{join as a1}from"node:path";import{debuglog as zF}from"node:util";import{createHmac as tD,randomBytes as eD,timingSafeEqual as XF}from"node:crypto";import rD from"node:net";var g6=2,v2=21,y2=5,u5=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 Ez=u.Goodbye;function Sz(X){return X===u.Cancel||X===u.Ping||X===u.Pong||X===u.Goodbye}var t0;(function(X){X[X.Passive=0]="Passive",X[X.Interactive=1]="Interactive",X[X.Background=2]="Background"})(t0||(t0={}));var K6;(function(X){X[X.Normal=0]="Normal",X[X.Expedite=1]="Expedite",X[X.Sheddable=2]="Sheddable"})(K6||(K6={}));var Iz=1,bz=6,p5=1,aD=8,kz=48,c5=4;var xz=0;function T6(X,J,$,Y=K6.Normal){let G=0;if(X)G|=Iz;if(G|=J<<p5,$)G|=aD;return G|=Y<<c5,G}function l5(X){return(X&Iz)!==0}function wz(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 oD(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>Ez)throw new I0(`unknown frame type byte ${Y}`,"unknown_frame_type");let Z=Y;if((G&xz)!==0)throw new I0(`reserved flag bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((G&bz)>>p5===3)throw new I0(`reserved priority bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(G&kz)>>c5;if(W===3)throw new I0(`reserved admission class set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===K6.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(Sz(Z)&&J!==0)throw new I0(`pure-header frame ${u[Z]} declared non-zero body length ${J}`,"pure_header_frame_with_body")}function d5(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>Ez)throw new I0(`unknown frame type byte ${G}`,"unknown_frame_type");let Q=G,z=X[6];if((z&xz)!==0)throw new I0(`reserved flag bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((z&bz)>>p5===3)throw new I0(`reserved priority bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Z=(z&kz)>>c5;if(Z===3)throw new I0(`reserved admission class set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Z===K6.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(Sz(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 j6(X,J,$,Y,G,Q){return R8(2,X,J,$,Y,G,Q)}function R8(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 oD(Z),{header:Z,body:z}}function W8(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=wz(X.header),$=new Uint8Array(J.length+X.body.length);return $.set(J,0),$.set(X.body,J.length),$}class $9 extends Error{}class B8 extends Error{}class C8 extends Error{cause;constructor(X,J){super(X);this.cause=J}}class P9 extends Error{cause;constructor(X,J){super(X);this.cause=J}}function vz(X){return Buffer.from(X.buffer,X.byteOffset,X.byteLength)}var yz=Symbol("subc.socket.writeBorrowed"),hz=Symbol("subc.socket.writeTrackedBorrowed");function H8(X,J,$){let Y=X[yz];return Y?Y.call(X,J,$):X.write(J,$)}function i5(X,J,$){let Y=X[hz];return Y?Y.call(X,J,$):X.writeTracked(J,$)}class r9{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 $9("subc closed the connection"))),X.on("close",()=>J(new $9("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect(X,J,$){return new Promise((Y,G)=>{let Q=rD.connect({host:X,port:J});Q.setNoDelay(!0);let z=setTimeout(()=>{Q.destroy(),G(new B8(`timed out connecting to ${X}:${J}`))},Math.max(0,$-Date.now()));Q.once("connect",()=>{clearTimeout(z),Y(new r9(Q))}),Q.once("error",(Z)=>{clearTimeout(z),G(Z)})})}async readFrame(X,J,$){let Y=await this.readExact(y2,X),G=Y[4];if(G!==g6)throw new I0(`unsupported envelope version ${G}`,"unsupported_version");let Q=await this.readExact(v2-y2,X),z=new Uint8Array(v2);z.set(Y),z.set(Q,y2);let Z=d5(z);if(Z.len>u5)throw new I0(`frame body ${Z.len} exceeds max ${u5}`,"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 B8(`timed out waiting for ${X} bytes`));return}G=setTimeout(()=>{this.waiter=null,Y(new B8(`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[yz](X,J){await this.writeBuffer(vz(X),J)}[hz](X,J){return this.writeTrackedBuffer(vz(X),J)}async writeBuffer(X,J){try{await this.writeTrackedBuffer(X,J).completed}catch($){if($ instanceof C8||$ instanceof P9)throw $.cause??$;throw $}}writeTrackedBuffer(X,J){if(this.closedErr)return{queued:!1,completed:Promise.reject(new C8("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 C8("timed out before bytes could be queued to subc",new B8("timed out writing to subc"))));return}G=setTimeout(()=>{let H=new B8("timed out writing to subc");W(()=>Z($?new P9("timed out after bytes were handed to the subc socket",H):new C8("timed out before bytes could be queued to subc",H)))},B);try{this.sock.write(X,(H)=>{W(()=>{if(H)Z(new P9("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 C8("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 mz=32;var h2=4096,uz="subc-server-v1",pz="subc-client-v1",JF="client";class R6 extends Error{}function s5(X,J,$,Y,G){let Q=tD("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 fz(X,J){if(X.length!==J.length)return!1;return XF(Buffer.from(X),Buffer.from(J))}async function gz(X,J,$){let Y=Buffer.from(JSON.stringify(J),"utf8");if(Y.length>h2)throw new R6(`auth message too large: ${Y.length} > ${h2}`);let G=new Uint8Array(4);new DataView(G.buffer).setUint32(0,Y.length,!0),await H8(X,G,$),await H8(X,Y,$)}async function $F(X,J){let $=await X.readExact(4,J),Y=new DataView($.buffer,$.byteOffset,4).getUint32(0,!0);if(Y>h2)throw new R6(`auth message too large: ${Y} > ${h2}`);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 R6(`auth message JSON decode failed: ${String(Q)}`)}}function n5(X,J){if(!Array.isArray(X))throw new R6(`auth field '${J}' must be a byte array`);for(let $ of X)if(typeof $!=="number"||!Number.isInteger($)||$<0||$>255)throw new R6(`auth field '${J}' has invalid byte ${String($)}`);return Uint8Array.from(X)}async function n4(X,J,$){let Y=new Uint8Array(eD(mz));await gz(X,{client_nonce:Array.from(Y),role:JF},$);let G=await $F(X,$),Q=n5(G.server_nonce,"server_nonce"),z=n5(G.daemon_id,"daemon_id"),Z=n5(G.server_proof,"server_proof"),W=s5(J.key,uz,Y,Q,z);if(!fz(W,Z))throw new R6("server proof mismatch — wrong key or impostor daemon");if(!fz(z,J.daemonId))throw new R6("daemon id mismatch — connection file points at a different daemon");let B=s5(J.key,pz,Y,Q,z);await gz(X,{client_auth:Array.from(B)},$)}import{promises as a5}from"node:fs";var cz=1,lz=32,dz=16;class Q6 extends Error{}function iz(X,J){if(!Array.isArray(X))throw new Q6(`connection file field '${J}' must be a JSON array of bytes`);for(let $ of X)if(typeof $!=="number"||!Number.isInteger($)||$<0||$>255)throw new Q6(`connection file field '${J}' has invalid byte ${String($)}`);return Uint8Array.from(X)}function YF(X){if(X.schema!==cz)throw new Q6(`unsupported connection file schema ${X.schema}; expected ${cz}`);if(X.endpoints.length===0)throw new Q6("connection file must include at least one endpoint");if(X.key.length<lz)throw new Q6(`connection file key is too short: ${X.key.length} bytes, need at least ${lz}`);if(X.daemonId.length!==dz)throw new Q6(`connection file daemon_id must be ${dz} bytes, got ${X.daemonId.length}`)}async function GF(X){if(process.platform==="win32")return;let $=(await a5.stat(X)).mode&511;if(($&63)!==0)throw new Q6(`connection file ${X} has insecure permissions 0o${$.toString(8)}; expected owner-only 0600`)}async function i1(X){await GF(X);let J=await a5.readFile(X,"utf8"),$;try{$=JSON.parse(J)}catch(Z){throw new Q6(`connection file JSON read failed for ${X}: ${String(Z)}`)}let Y=$.wire_version;if(Y!==void 0&&Y!==g6)throw new Q6(`connection file wire_version ${String(Y)} but this client speaks ${g6}; the client library must be upgraded`);let G=$.endpoints;if(!Array.isArray(G))throw new Q6("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 Q6("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),z={schema:$.schema,endpoints:Q,key:iz($.key,"key"),daemonId:iz($.daemon_id,"daemon_id"),pid:$.pid,daemonVer:$.daemon_ver??""};return YF(z),z}var nz=new WeakMap,o5=new WeakMap;class r5 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 O9{handlers=new Map;declaredFamilies=null;onRequest(X,J){if(!QF(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 r5(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 f2{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(),nz.set(this,$),o5.set(this,Y),Object.freeze(this)}onRequest(X,J){o5.get(this).onRequest(X,J)}static create(X,J,$,Y){return new f2(X,J,$,Y)}}function g2(X,J,$,Y=new O9){return f2.create(X,J,$,Y)}function sz(X,J){return o5.get(X)?.handler(J)}function QF(X){return/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(X)}class Y9 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 n1(){return Object.freeze({})}function s4(X,J){return nz.get(X)===J}function m2(X,J){return X===J}var az=zF("subc-client"),ZF=1e4,s1=30000,WF=50,BF=2000,oz="request_deadline",t5="deadline_exceeded_no_drop_observed",HF=30000,VF=30000,rz=new Uint8Array(0),UF="management_surface",l2="SUBC_MODULE_ID",d2="SUBC_LAUNCH_NONCE",i2={baseMs:100,capMs:2000,maxAttempts:6};class z6 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 tz=new WeakMap;function e5(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 t9{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=n1();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 t9.openConnection(J);return new t9($.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(!$Z(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=XJ($),G=$.reverseRequests??new O9;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?e5(J):J instanceof Uint8Array?J:this.encode(J),Q=$.priority??t0.Interactive,z=$.admissionClass??K6.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=e5(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 z6))throw this.terminalCallError("managed call failed",Q);let z=n2(Q.cause instanceof q0?tz.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!==t5){if(this.closedErr)this.scheduleReconnectAfterDrop(Q)}else if(Q.kind==="outcome_unknown"&&Q.code===t5)this.probeLivenessAfterDeadline();throw Q}}}subscribe(X,J,$,Y={}){this.assertLiveHandle(X);let G=J instanceof Uint8Array?J:this.encode(J),Q=Y.priority??t0.Interactive,z=Y.admissionClass??K6.Normal,Z=this.allocateCorr(),W=u2(X,Z),B=null,H=null,U=new Promise((K,N)=>{if(this.closedErr){N(this.closedErr);return}H=K,B={handle:X,resolve:()=>K(),reject:N,onProgress:$,timer:null,subscription:!0},this.pending.set(W,B);let F=j6(u.Request,T6(!1,Q,!1,z),X.channel,X.epoch,Z,G);H8(this.sock,W8(F),Date.now()+s1).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,$=t0.Interactive){this.assertLiveHandle(X);let Y=j6(u.Cancel,T6(!1,$,!1),X.channel,X.epoch,J,rz);H8(this.sock,W8(Y),Date.now()+s1).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&&m2(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=ez(X,J,XJ($),($.reverseRequests??new O9).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 $=j6(u.Goodbye,T6(!1,t0.Interactive,!1),X.channel,X.epoch,0n,rz),Y=i5(this.sock,W8($),Date.now()+s1);if(!Y.queued&&J)this.closeConnectionAfterCleanupFailure();Y.completed.catch(()=>{if(J&&!Y.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection(X){let J=await i1(X.connectionFile),$=Date.now()+(X.handshakeTimeoutMs??ZF),Y=J.endpoints[0],G=await r9.connect(Y.host,Y.port,$);try{await n4(G,J,$)}catch(Q){throw G.close(),Q}return{sock:G,conn:J}}async controlRpc(X,J,$){return this.send(null,X,t0.Interactive,K6.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(N){return Promise.reject(N)}let U=u2(X,H),j=X?.channel??0,q=X?.epoch??0,K=j6(u.Request,T6(W,$,!1,Y),j,q,H,J);return new Promise((N,F)=>{let O=G??s1,_={handle:X,resolve:N,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,$);H8(this.sock,W8(K),Date.now()+O).catch((C)=>{let L=this.pending.get(U);if(L)this.rejectPending(U,L,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),oz))},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?e5(J):J instanceof Uint8Array?J:this.encode(J),Q=$.priority??t0.Interactive,z=$.admissionClass??K6.Normal;try{let Z=await this.sendManaged(X,G,Q,z,$.timeoutMs,$.onProgress,Y,$.signal);return this.decodeReply(Z)}catch(Z){if(Z instanceof z6)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=u2(X,W),H=j6(u.Request,T6(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===oz)return new z6("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${a4(q)}`,t5,q);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",q)};return new Promise((q,K)=>{let N=G??s1,F={handle:X,resolve:q,reject:K,onProgress:Q,timer:null,classifyFailure:j};if(F.timer=setTimeout(()=>this.arbitrateTimeout(B,F,X.channel,W,N),N),this.pending.set(B,F),Z)this.attachCancelSignal(Z,B,X,W,$);let O=i5(this.sock,W8(H),Date.now()+N);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 z6("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=XJ(J),Q=J.reverseRequests??new O9;Q.seal();let z=ez(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 z6&&G.code==="route_closed")throw G;if(!this.closeStarted&&p2(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&&jF(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=j6(u.Ping,T6(!1,t0.Interactive,!1,K6.Normal),0,0,$,new Uint8Array),Q=(async()=>{if(await H8(X,W8(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 $9(`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 t9.openConnection(this.opts);if(this.closeStarted)throw Y.sock.close(),new q0("client closed");this.replaceConnection(Y),await this.reopenCachedRoutes();return}catch(Y){if(!p2(Y)||J>=this.opts.reconnectBackoff.maxAttempts){if(Y instanceof R6&&J>1)throw new R6(`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=n1(),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(KF(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 z6("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:VF},()=>{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 $=u2(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)az("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 $=NF(X.body),Y=$?.split("/",1)[0],G=Y?sz(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)az("failed to answer reverse request: %s",a4(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=j6($,T6(!1,t0.Interactive,!1),J.channel,J.epoch,X.header.corr,Y);await H8(G,W8(z),Date.now()+s1)}errorFromFrame(X){try{let J=JSON.parse(Buffer.from(X.body).toString("utf8")),$=new q0(J.message??"subc error",J.code,J.detail);return tz.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&&m2(J.handle,X))J.handle=null}failHandle(X,J){for(let[$,Y]of this.pending)if(Y.handle&&m2(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 z6("not_sent",`${X}${a4(J)}`,c2(J),J)}outcomeUnknownCallError(X,J){return new z6("outcome_unknown",`${X}${a4(J)}`,c2(J),J)}terminalCallError(X,J){if(J instanceof z6)return J;return new z6("terminal",`${X}${a4(J)}`,c2(J),J)}notSentRecoveryError(X,J){if(J instanceof z6)return J;if(p2(J))return this.notSentCallError(X,J);return this.terminalCallError(X,J)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute(X,J,$=new O9){let Y=g2(X,J,this.connectionToken,$);return this.liveRoutes.set(X,Y),Y}isLiveHandle(X){return s4(X,this.connectionToken)&&this.liveRoutes.get(X.channel)===X}assertLiveConnection(X){if(!s4(X,this.connectionToken))throw new Y9(X)}assertLiveHandle(X){if(!this.isLiveHandle(X))throw new Y9(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 l5(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 p2(X){if(X instanceof $9||X instanceof B8)return!0;if(X instanceof C8||X instanceof P9)return!0;if(X instanceof z6)return X.kind==="not_sent"||X.kind==="outcome_unknown";if(X instanceof R6)return!0;if(X instanceof q0||X instanceof Q6)return!1;let J=c2(X);return J==="ECONNREFUSED"||J==="ECONNRESET"||J==="EPIPE"||J==="ETIMEDOUT"||J==="ENOENT"}function KF(X){return X instanceof q0&&typeof X.code==="string"}function jF(X){if(X==="capability_forbidden")return!1;return X==="module_reloading"||X==="module_warming"||X==="target_unavailable"||X==="module_timeout"}var XZ="unknown_channel",JZ="stale_route_epoch";function n2(X,J){return J===XZ||J===JZ}function qF(X){return{connectionFile:X.connectionFile,handshakeTimeoutMs:X.handshakeTimeoutMs,identity:X.identity,targetKind:X.targetKind??UF,reconnectBackoff:X.reconnectBackoff??i2,sleep:X.sleep??((J)=>new Promise(($)=>setTimeout($,J))),routeOpenRetryDeadlineMs:X.routeOpenRetryDeadlineMs??HF,timeoutArbitrationGraceMs:X.timeoutArbitrationGraceMs??WF,livenessProbeWindowMs:X.livenessProbeWindowMs??BF,onControlPush:X.onControlPush}}function $Z(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 ez(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 XJ(X={}){if(X.consumerIdentity!==void 0)return X.consumerIdentity??void 0;let J=process.env[l2],$=process.env[d2];if(!J||!$)return;return{module_id:J,launch_nonce:$}}function c2(X){if(typeof X==="object"&&X!==null&&"code"in X){let J=X.code;if(typeof J==="string")return J}return}function a4(X){if(X===void 0)return"";return`: ${X instanceof Error?X.message:String(X)}`}function u2(X,J){return X?`${X.channel}:${X.epoch}:${J}`:`0:0:${J}`}function NF(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 zJ}from"node:buffer";var LF=1e4,DF=30000,GZ=30000,FF=250,JJ=64,GJ="health.check",QZ=1n,PF=/^[0-9a-f]{32}$/;function QJ(X){let J=X.machine_id;return typeof J==="string"&&PF.test(J)?J:void 0}class a2{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 o4{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=n1();nextCorr=1n;ingressEpochDropCount=0;requestGate=new a2(JJ);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=QJ(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=s2(X,Y),Q=$.timeoutMs??GZ,z=j6(u.Request,T6(!1,$.priority??t0.Interactive,!1,$.admissionClass??K6.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,j6(u.Push,T6(!1,$.priority??t0.Interactive,!1,$.admissionClass??K6.Normal),X.channel,X.epoch,0n,J))}cancel(X,J){this.assertLiveHandle(X),this.sendOn(this.sock,this.generation,j6(u.Cancel,E8(),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,j6(u.Goodbye,E8(),X.channel,X.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect(X){if(X.manifest.protocol_ver!==g6)throw new w0(`manifest protocol_ver ${X.manifest.protocol_ver} does not match client protocol ${g6}`,"invalid_manifest");let J=MF(X),$=await o4.openConnection(J);return new o4($.sock,$.conn,J,$.ack)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let X=this.sock;try{await YJ(X,j6(u.Goodbye,E8(),0,0,0n,new Uint8Array(0)))}catch{}finally{X.close(),this.finishClosed()}}await this.closed}static async openConnection(X,J){let $=await i1(X.connectionFile),Y=Date.now()+(X.handshakeTimeoutMs??LF),G=$.endpoints[0],Q=await r9.connect(G.host,G.port,Y);try{J?.(Q),await n4(Q,$,Y),await YJ(Q,AF(X));let z=await EF(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:DF});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=s2(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(OF(X)),!0}}switch(X.header.ty){case u.Ping:if(X.header.channel===0)await this.sendOn(J,$,R8(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(s2(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 Y9(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=r2(X.body);if(Y.op===GJ){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=YZ(Y.route_channel,"route_channel"),Q=YZ(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}`,E8(),J,$);return}this.liveRoutes.delete(z.channel),this.abortHandle(z),await this.reportRouteGone(z)}let Z=g2(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),E8(),J,$)}finally{await this.reportRouteGone(Z)}return}let H=SF(B);if(H){try{await this.sendError(X,H.code,H.message,E8(),J,$)}finally{await this.reportRouteGone(Z)}return}try{await this.sendOn(J,$,R8(X.header.ver,u.Response,E8(),0,0,X.header.corr,o2({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=s2(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,R8(Q,u.StreamData,T6(!1,j.priority??t0.Interactive,!1,j.admissionClass??K6.Normal),J.channel,J.epoch,G,U))}},B=await(this.requestGate??new a2(JJ)).acquire(),H=T6(!1,t0.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,R8(Q,u.StreamEnd,H,J.channel,J.epoch,G,new Uint8Array(0)));else if(U instanceof Uint8Array)await this.sendOn($,Y,R8(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 Y9)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 a2(JJ)).acquire();try{if(z.signal.aborted)return;let W=await this.opts.health();await this.sendOn(J,$,R8(G,u.Response,E8(),0,0,Y,o2({op:GJ,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),E8(),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,R8(X.header.ver,u.Error,Y,X.header.channel,X.header.epoch,X.header.corr,o2({code:J,message:$})))}async sendOn(X,J,$){if(this.sock!==X||this.generation!==J||this.closeStarted||this.closedErr)return;await YJ(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 o4.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(!TF(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=QJ(X.ack),this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=n1(),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 CF();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 s4(X,this.connectionToken)&&this.liveRoutes.get(X.channel)===X}assertLiveHandle(X){if(!this.isLiveHandle(X))throw new Y9(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 s2(X,J){return`${X.channel}:${X.epoch}:${J}`}function OF(X){try{let J=r2(X.body);return new w0(J.message??"subc error",J.code,n2(X.header.flags,J.code)?"not_sent":"terminal",J.detail)}catch{return new w0(zJ.from(X.body).toString("utf8")||"subc error")}}function $J(X){return X&&X.length>0?X:void 0}function MF(X){let J=$J(process.env[l2]),$=$J(process.env[d2]),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??i2,sleep:X.sleep??((G)=>new Promise((Q)=>setTimeout(Q,G))),restoredDebounceMs:X.restoredDebounceMs??FF,onConnectionState:X.onConnectionState,launchNonce:$J(X.launchNonce??$),reconnectOnDrop:X.reconnectOnDrop??!Y}}function _F(X){if(X===null)return null;let J=new Set(X??[]);return J.add(GJ),[...J]}function AF(X){let J=X.launchNonce;return j6(u.Hello,E8(),0,0,QZ,o2({manifest:IF(X.manifest),protocol_ver:g6,control_ops:_F(X.controlOps),...J?{launch_nonce:J}:{}}))}function TF(X){if(X instanceof w0)return X.code==="duplicate_module_id";if(X instanceof $9||X instanceof B8)return!0;if(X instanceof C8||X instanceof P9)return!0;if(X instanceof R6)return!0;if(X instanceof Q6)return!1;let J=RF(X);return J==="ECONNREFUSED"||J==="ECONNRESET"||J==="EPIPE"||J==="ETIMEDOUT"||J==="ENOENT"}function RF(X){if(typeof X==="object"&&X!==null&&"code"in X){let J=X.code;if(typeof J==="string")return J}return}async function CF(){await new Promise((X)=>setTimeout(X,0))}function E8(){return T6(!1,t0.Passive,!1)}async function YJ(X,J){await H8(X,W8(J),Date.now()+GZ)}async function EF(X,J){let $=await X.readFrame(J,J);switch($.header.ty){case u.HelloAck:{let Y=r2($.body);if(Y.negotiated_ver!==g6)throw new w0(`subc negotiated protocol ${Y.negotiated_ver}; expected exactly ${g6}`,"unsupported_version");return Y}case u.Error:{let Y=r2($.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 o2(X){return new Uint8Array(zJ.from(JSON.stringify(X),"utf8"))}function r2(X){return JSON.parse(zJ.from(X).toString("utf8"))}function YZ(X,J){if(typeof X!=="number"||!Number.isInteger(X))throw new w0(`route.bind ${J} must be an integer`);return X}function SF(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 IF(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(bF),consumes:X.consumes.map(kF),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 bF(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 kF(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 e2="subc-connection.json",ZZ="subc-",WZ=".connection.json";function BZ(){let X=process.env.HOME;return X?a1(X,".local","share","cortexkit","run",e2):void 0}function yF(){let X=process.env.XDG_RUNTIME_DIR;if(X)return a1(X,e2);let J=BZ();if(J)return J;return a1(vF().homedir,".local","share","cortexkit","run",e2)}function hF(){if(process.env.SUBC_CONNECTION_FILE)return process.env.SUBC_CONNECTION_FILE;let X=process.env.XDG_RUNTIME_DIR;if(X){let G=a1(X,e2);if(t2(G))return G}let J=BZ();if(J&&t2(J))return J;let $=a1(zZ(),`${ZZ}${fF()}${WZ}`);if(t2($))return $;let Y=gF(zZ());return Y.length===1?Y[0]:void 0}function fF(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 HZ(){return hF()??yF()}function e9(X){return X?.trim()||process.env.SUBC_CONNECTION_FILE||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||HZ()}function t2(X){try{return wF(X).isFile()}catch{return!1}}function gF(X){let J;try{J=xF(X)}catch{return[]}let $=[];for(let Y of J){if(typeof Y!=="string")continue;if(!Y.startsWith(ZZ)||!Y.endsWith(WZ))continue;let G=a1(X,Y);if(t2(G))$.push(G)}return $.sort(),$}import{createHash as mF}from"node:crypto";import{existsSync as uF,realpathSync as VZ}from"node:fs";import{dirname as pF,relative as cF,resolve as lF}from"node:path";function UZ(X){let J=X,$;try{$=VZ(J)}catch(Y){if(Y.code!=="ENOENT")throw Y;let G=J;while(!uF(G)){let Q=pF(G);if(Q===G)break;G=Q}$=lF(VZ(G),cF(G,J))}return mF("sha256").update($).digest("hex")}function ZJ(X,J){return{project_root:X,harness:"opencode",session:`store-${UZ(J)}`}}import{AsyncLocalStorage as dF}from"node:async_hooks";import{readFile as KZ}from"node:fs/promises";var iF=new dF;function jZ(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 X7(X,J=iF.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 $=jZ(new TextDecoder("utf-8",{fatal:!0}).decode(await KZ(J.passwdPath)),7),Y=jZ(new TextDecoder("utf-8",{fatal:!0}).decode(await KZ(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 nF}from"node:crypto";import{chmod as sF,mkdir as aF,open as oF,realpath as rF,rename as tF,stat as eF,unlink as XP}from"node:fs/promises";import{basename as JP,dirname as qZ,join as $P}from"node:path";var YP=/^[0-9a-f]{64}$/;function GP(X){if(!YP.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 QP(X){let J;try{J=await rF(X)}catch{return}for(;;){let $=await eF(J).catch(()=>{return});if($&&!await X7($))throw Error(`enrollment token ancestor ${J} is group- or world-writable without sticky bit`);let Y=qZ(J);if(Y===J)return;J=Y}}async function WJ(X,J){GP(J);let $=qZ(X);await aF($,{recursive:!0,mode:448}),await QP($);let Y=$P($,`.${JP(X)}.${process.pid}.${nF(12).toString("hex")}.tmp`),G=!1;try{let Q=await oF(Y,"wx",384);G=!0;try{await Q.writeFile(`${JSON.stringify(J)}
89
- `,"utf8"),await Q.sync(),await sF(Y,384)}finally{await Q.close()}await tF(Y,X),G=!1}finally{if(G)await XP(Y).catch(()=>{return})}}var NZ=["transient","permanent","auth_required","context_overflow"];class V8 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 o1(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function LZ(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=o1(X)&&o1(X.result)?X.result:void 0,G=Y&&o1(Y.error)?Y.error:void 0,Q=G?.class,z=G?.code,Z=typeof Q==="string"&&NZ.includes(Q),W=typeof z==="string",H=Z&&W?Q:"transient";if(typeof Q!=="string")$("unknown");else if(!Z)$(Q);return new V8(W?z:J,H,LZ(H))}function X1(X){return o1(X)&&o1(X.result)&&o1(X.result.error)}var DZ="claustrum",WP=60000;function m6(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function HJ(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=0?X:void 0}function S8(X){return X===void 0||typeof X==="string"}function FZ(X,J){if(X1(X))throw O0(X,"invalid_response",J);let $=m6(X)&&m6(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=HJ($?.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(!S8(Z)||!S8(W)||!S8(B)||!S8(H)||!S8(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 BP(X,J){if(X1(X))throw O0(X,"invalid_response",J);let $=m6(X)&&m6(X.result)?X.result:void 0,Y=$?.record_version,G=Y===void 0?void 0:HJ(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||!S8(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 J1{#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=e9(X.connectionFile),$=X.connector??((Q)=>t9.connect(Q)),Y=X.identity??ZJ(X.projectRoot??process.cwd(),X.storagePath??process.cwd()),G=await $({connectionFile:J,handshakeTimeoutMs:X.handshakeTimeoutMs});return new J1(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 FZ($,this.#G)}async statusCredential(X){let J=await this.#Q("credential.status",{handle:X});return BP(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(X1(J))throw O0(J,"invalid_response",this.#G);if((m6(J)&&m6(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 HP(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 FZ(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(X1(J))throw O0(J,"invalid_response",this.#G);if((m6(J)&&m6(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=BJ(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 VP(J,this.#G)}async enrollRotate(X){let J=await this.#Q("auth.enroll_rotate",{token:X.token,expected_token_generation:X.expectedTokenGeneration}),$=BJ(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(DZ,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(DZ,X,J,{identity:this.#W,consumerIdentity:null})}catch(G){throw this.#B(G)}}throw this.#B(Y)}}#B(X){if(X instanceof V8)return X;let J=X instanceof z6&&X.code?X.code:"transport_error";return new V8(J,"transient","retry")}#V(X){return!this.#H&&X instanceof z6&&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+WP,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 HP(X,J){if(X1(X))throw O0(X,"invalid_response",J);let $=m6(X)&&m6(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(!m6(z))throw O0(X,"invalid_response",J);let Z=HJ(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(!S8(z.refresh_adapter))throw O0(X,"invalid_response",J);if(!S8(z.account_id)||!S8(z.email)||!S8(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 BJ(X,J){if(X1(X))throw O0(X,"invalid_response",J);let $=m6(X)&&m6(X.result)?X.result:void 0;if($===void 0)throw O0(X,"invalid_response",J);return $}function VP(X,J){let $=BJ(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 r4(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 UP,randomBytes as KP,randomUUID as jP}from"node:crypto";import{constants as PZ}from"node:fs";import{chmod as qP,mkdir as NP,open as TZ,readFile as OZ,realpath as LP,rename as DP,stat as RZ,unlink as CZ}from"node:fs/promises";import{basename as EZ,dirname as Y1,extname as MZ,isAbsolute as _Z,join as KJ,resolve as FP}from"node:path";class $0 extends Error{kind;constructor(X,J){super(J);this.name="ClaustrumConsumerError",this.kind=X}}var PP=1,VJ=16384,SZ=30000,jJ=/^[0-9a-f]{64}$/,IZ=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),bZ=new Set(["pending_queue_full"]);function UJ(X){if(!(X instanceof V8))return;if(IZ.has(X.code))return{code:X.code,disposition:"terminal"};if(bZ.has(X.code))return{code:X.code,disposition:"retry"};return{code:X.code,disposition:X.action==="retry"?"retry":"terminal"}}function qJ(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 NJ(X){return J1.connect(X)}function kZ(X){let J=MZ(X)||".json",$=EZ(X,MZ(X));return{statePath:KJ(Y1(X),`${$}-state${J}`),tokenPath:X}}function LJ(X){let J=X.override?.trim();if(J&&!_Z(J)&&!X.cwd)throw new $0("invalid-state","A relative Claustrum enrollment override needs a base directory");let $=J?_Z(J)?J:FP(X.cwd,J):KJ(X.stateDir,`${X.host}-enrollment.json`);return kZ($)}function xZ(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function J7(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=0}function wZ(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=1}function t4(){return new $0("invalid-state","invalid Claustrum enrollment state")}function Y7(X){if(!xZ(X)||X.version!==PP||typeof X.proposedName!=="string"||X.proposedName.length===0)throw t4();if(X.phase==="pending"){if(!jJ.test(String(X.requestSecret??""))||X.requestId!==void 0&&(typeof X.requestId!=="string"||X.requestId.length===0)||!J7(X.createdAt)||!J7(X.updatedAt))throw t4();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)||!wZ(X.tokenGeneration)||!J7(X.updatedAt))throw t4();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"||!J7(X.updatedAt))throw t4();return{version:1,phase:X.phase,proposedName:X.proposedName,...X.errorCode!==void 0&&{errorCode:X.errorCode},updatedAt:X.updatedAt}}throw t4()}function DJ(X){if(!xZ(X)||!jJ.test(String(X.token??""))||!wZ(X.token_generation))throw new $0("invalid-token","invalid Claustrum enrollment token file");return{token:X.token,token_generation:X.token_generation}}function OP(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 MP(X){try{return JSON.parse(X)}catch{throw new $0("invalid-state","Claustrum enrollment file is not valid JSON")}}async function _9(X){let J;try{J=await TZ(X,PZ.O_RDONLY|PZ.O_NOFOLLOW)}catch($){if($.code==="ENOENT")return;throw new $0("unsafe-file","Claustrum enrollment file could not be opened safely")}try{OP(await J.stat());let $=Buffer.alloc(VJ+1),{bytesRead:Y}=await J.read($,0,$.byteLength,0);if(Y>VJ)throw new $0("unsafe-file","Claustrum enrollment file is too large");return MP($.subarray(0,Y).toString("utf8"))}finally{await J.close()}}function AZ(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 _P(X,J,$){try{let[Y,G]=await Promise.all([OZ($.passwdPath??"/etc/passwd","utf8"),OZ($.groupPath??"/etc/group","utf8")]),Q=AZ(Y,7),z=AZ(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 vZ(X,J={}){let $=process.geteuid?.();if($===void 0)return;let Y=process.getegid?.(),G;try{G=await LP(X)}catch{return}let Q;for(;;){let z=await RZ(G).catch(()=>{return});if(z&&(z.mode&18)!==0&&(z.mode&512)===0){if(Q===void 0)Q=Y!==void 0&&await _P($,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=Y1(G);if(Z===G)return;G=Z}}async function $7(X){await NP(X,{recursive:!0,mode:448});let J=await RZ(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 $1(X,J,$={}){let Y=Y1(X);await $7(Y),await vZ(Y,$);let G=`${JSON.stringify(J)}
91
- `;if(Buffer.byteLength(G)>VJ)throw new $0("invalid-state","Claustrum enrollment state is too large");let Q=KJ(Y,`.${EZ(X)}.${process.pid}.${jP()}.tmp`),z,Z=!1;try{z=await TZ(Q,"wx",384),Z=!0,await z.writeFile(G,"utf8"),await z.chmod(384),await z.sync(),await z.close(),z=void 0,await DP(Q,X),Z=!1}finally{if(await z?.close().catch(()=>{}),Z)await CZ(Q).catch(()=>{})}}async function e4(X,J){let $=await _9(X.tokenPath),Y=$===void 0?void 0:DJ($),G=await _9(X.statePath),Q=G===void 0?void 0:Y7(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 M9(Q)}async function X3(X,J){let $;try{$=await e4(X,J)}catch(Y){if(!(Y instanceof $0)||Y.kind!=="invalid-state"&&Y.kind!=="invalid-token")return"unreadable";try{let G=await _9(X.statePath);if(G===void 0)return"unreadable";let Q=Y7(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 FJ(X){let J=await _9(X);if(J===void 0)throw new $0("not-enrolled","Claustrum enrollment is not configured");return DJ(J)}function M9(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 yZ(){return new $0("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class G7{#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??(()=>KP(32).toString("hex")),this.#G=X.writeTokenFile??WJ}async status(){return e4(this.#J,this.#z)}async resetTerminal(){return hZ(this.#J,this.#z)}async#Z(X,J){let $={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:J,updatedAt:this.#$()};return await $1(this.#J.statePath,$,this.#Y),M9($)}async reconcile(){await $7(Y1(this.#J.statePath));let X=await g0({name:"ceremony",path:this.#J.statePath,ttlMs:SZ,renew:!0});if(!X)return{state:"busy"};try{let J=await _9(this.#J.tokenPath),$=J===void 0?void 0:DJ(J),Y=await _9(this.#J.statePath),G=Y===void 0?void 0:Y7(Y);if(G&&G.proposedName!==this.#z)throw yZ();if($){if(!G||G.phase==="pending"){let z={version:1,phase:"approved",proposedName:G?.proposedName??this.#z,tokenGeneration:$.token_generation,updatedAt:this.#$()};await $1(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 $1(this.#J.statePath,z,this.#Y),M9(z)}if(G&&G.phase!=="pending")return M9(G);if(!G){let z=this.#$();if(G={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#W(),createdAt:z,updatedAt:z},!jJ.test(G.requestSecret))throw new $0("invalid-state","invalid minted Claustrum enrollment secret");await $1(this.#J.statePath,G,this.#Y)}if(!G.requestId)try{let z=UP("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 $1(this.#J.statePath,G,this.#Y)}catch(z){let Z=UJ(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 M9(G);try{let z=await this.#X.enrollPoll({requestId:Q,requestSecret:G.requestSecret});if(z.status==="pending")return M9(G);if(z.status==="denied"){let W={version:1,phase:"denied",proposedName:G.proposedName,updatedAt:this.#$()};return await $1(this.#J.statePath,W,this.#Y),M9(W)}await $7(Y1(this.#J.tokenPath)),await vZ(Y1(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 $1(this.#J.statePath,Z,this.#Y),M9(Z)}catch(z){let Z=UJ(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 hZ(X,J){await $7(Y1(X.statePath));let $=await g0({name:"ceremony",path:X.statePath,ttlMs:SZ,renew:!0});if(!$)return"busy";try{if(await _9(X.tokenPath)!==void 0)return"refused-approved";let Y=await _9(X.statePath);if(Y===void 0)return"idle";let G=Y7(Y);if(G.proposedName!==J)throw yZ();if(G.phase==="pending")return"refused-pending";return await $.assertOwned(),await CZ(X.statePath),"reset"}finally{await $.release()}}var J3="claustrum-tombstone:v1:";function Q7(X){return`${J3}${X}`}function PJ(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function z7(X){return typeof X==="string"&&X.startsWith(J3)}function fZ(X,J){if(!PJ(X)||X.type!=="oauth")return!1;return X.refresh===Q7(J)}function gZ(X,J){if(fZ(X,J))return"placeholder";if(PJ(X)&&X.type==="oauth"&&typeof X.refresh==="string"&&X.refresh.length>0&&!z7(X.refresh))return"login";if(PJ(X)&&X.type==="api"&&typeof X.key==="string"&&X.key.length>0)return"login";return"empty"}function OJ(X){let J=gZ(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 mZ(X,J){return J!==void 0&&J.credentialId===X.credentialId&&J.accountIdentity===X.accountIdentity&&J.recordVersion!==X.recordVersion}function AP(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 uZ=Z0("claustrum");function AJ(X,J,$,Y=uZ){let G=mZ(J,$);return Y.debug("scoped 401 re-authorized",{site:X,credentialId:J.credentialId,servedVersion:J.recordVersion,currentVersion:$?.recordVersion??null,retry:G,reason:AP(J,$)}),G}var _J=300000;function MJ(){return new $0("invalid-material","Claustrum returned invalid credential material")}function TP(X){let J=X.trim();if(J.startsWith("{")){let $;try{$=JSON.parse(J)}catch{throw MJ()}if(!$||typeof $!=="object")throw MJ();let Y=$,G=Y.access_token??Y.access;J=typeof G==="string"?G:""}if(!/^[\x21-\x7e]+$/.test(J)||J.startsWith(J3))throw MJ();return J}function RP(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 Z7{#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=()=>FJ(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??uZ}#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 V8)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=RP(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:_J}}),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()<_J))throw new $0("insufficient-validity","Claustrum served credential has insufficient validity");let W=TP(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 CP}from"node:crypto";import{readFile as EP}from"node:fs/promises";function pZ(X,J,$){if(X.accountIdentity!==void 0&&$!==void 0)return X.accountIdentity===$;return X.credentialId===J}function TJ(X,J,$){return X.some((Y)=>pZ(Y,J,$))}function RJ(X,J,$){let Y={credentialId:J,...$!==void 0&&{accountIdentity:$}};return[...X.filter((G)=>G.credentialId!==J||G.accountIdentity!==$),Y]}function CJ(X,J,$){return X.filter((Y)=>!J.some((G)=>pZ(Y,G,$)))}var dZ="vault:";function SP(X){return CP("sha256").update(X).digest("hex")}function IP(X){let J=X.credentialId.split(":");return(J.length>=3?J.slice(2).join(":").trim():void 0)||X.email||X.credentialId}function bP(X){return X.identity!==void 0?`identity:${X.identity}`:`credential:${X.credential.credentialId}`}function A9(X){return[X.credentialId,...X.aliases??[]]}function iZ(X,J,$={}){let Y=$.now??Date.now(),G=$.routePrefix??dZ,Q=$.reservedRouteIds??new Set,z=X?.rows??[],Z=[...X?.declined??[]],W=J.skipped.length===0,B=new Set(J.credentials.map((L)=>L.credentialId)),H=new Set(J.skipped.flatMap((L)=>L.credentialId===void 0?[]:[L.credentialId])),U=J.skipped.some((L)=>L.credentialId===void 0),j=(L)=>!B.has(L)&&(H.has(L)||U),q=new Map;for(let L of z){if(L.accountIdentity===void 0)continue;for(let P of A9(L))if(!q.has(P))q.set(P,L.accountIdentity)}let K=new Map;for(let L of J.credentials){let P=L.accountIdentity!==void 0?{credential:L,identity:L.accountIdentity,claimed:!0}:{credential:L,identity:q.get(L.credentialId),claimed:!1},A=bP(P),T=K.get(A)??[];T.push(P),K.set(A,T)}let N=new Set,F=new Set(Q),O=[],_=(L,P)=>L.credential.credentialId.localeCompare(P.credential.credentialId),C=[...K.values()].map((L)=>L.toSorted(_)).sort((L,P)=>L[0]&&P[0]?_(L[0],P[0]):0);for(let L of C){let P=L[0]?.identity,A=L.filter((r)=>r.credential.state==="active"),T=A.length?A:L,k=T.filter((r)=>r.claimed),p=k.length?k:T,i=new Set(L.map((r)=>r.credential.credentialId)),X0=z.find((r)=>!N.has(r)&&A9(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)=>!N.has(r)&&r.accountIdentity===P));if(G0)N.add(G0);let L0=G0?.routeId;if(!L0||Q.has(L0)){let r=`${G}${J0.credentialId}${P===void 0?"":`~${SP(P).slice(0,10)}`}`;L0=r;for(let a=2;F.has(L0);a++)L0=`${r}~${a}`}F.add(L0);let m=G0?A9(G0).filter(j):[],c0=[...new Set([...L.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()||IP(J0),...J0.email!==void 0&&{email:J0.email},...J0.orgName!==void 0&&{orgName:J0.orgName},enabled:![J0.credentialId,...c0].some((r)=>TJ(Z,r,P)),addedAt:G0?.addedAt??Y,...G0?.quota!==void 0&&{quota:G0.quota},...!w.claimed&&P!==void 0&&{unclaimed:!0}}})}return z.forEach((L,P)=>{if(N.has(L)||!A9(L).some(j))return;if(F.has(L.routeId))return;let[A,...T]=A9(L).filter((i)=>!B.has(i));if(A===void 0)return;F.add(L.routeId);let{aliases:k,...p}=L;O.push({previousIndex:P,row:{...p,credentialId:A,...T.length&&{aliases:T},stale:!0}})}),O.sort((L,P)=>L.previousIndex===P.previousIndex?L.row.credentialId.localeCompare(P.row.credentialId):L.previousIndex-P.previousIndex),{version:1,view:J.view,complete:W,...!W&&{rejected:J.skipped.map((L)=>({...L.credentialId!==void 0&&{credentialId:L.credentialId},reason:L.reason}))},rows:O.map((L)=>L.row),declined:Z}}function EJ(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 W7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function r1(X){return X===void 0||typeof X==="string"}function kP(X){if(!W7(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"||!r1(X.accountIdentity)||!r1(X.email)||!r1(X.orgName)||X.aliases!==void 0&&(!Array.isArray(X.aliases)||!X.aliases.every((J)=>typeof J==="string"))||X.quota!==void 0&&!G6(X.quota)||X.stale!==void 0&&X.stale!==!0||X.unclaimed!==void 0&&X.unclaimed!==!0)return;return X}var xP=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function cZ(X){if(!Array.isArray(X))return;let J=[];for(let $ of X){if(!W7($)||!r1($.credentialId)||typeof $.reason!=="string"||!xP.has($.reason))return;J.push($)}return J}function wP(X){if(!W7(X)||X.version!==1||!r1(X.view)||!Array.isArray(X.rows)||!Array.isArray(X.declined)||X.complete!==void 0&&typeof X.complete!=="boolean"||X.rejected!==void 0&&!cZ(X.rejected))throw new $0("invalid-state","Claustrum roster file is not valid");let J=[];for(let G of X.rows){let Q=kP(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(!W7(G)||typeof G.credentialId!=="string"||!r1(G.accountIdentity))throw new $0("invalid-state","Claustrum roster file is not valid");$.push(G)}let Y=cZ(X.rejected);return{version:1,...typeof X.view==="string"&&{view:X.view},complete:X.complete!==!1,...Y&&{rejected:Y},rows:J,declined:$}}async function T9(X){let J;try{J=await EP(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 wP($)}var vP={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},yP={name:"claustrum-roster",ttlMs:30000};async function $3(X,J,$={}){return lZ(X,vP,async(Y)=>{let G=await T9(X),{next:Q,result:z}=await J(G,{assertOwned:()=>Y.assertOwned()});if(Q)await Y.assertOwned(),await M6(X,Q,{beforeRename:async()=>{await $.beforePublish?.(),await Y.assertOwned()}});return z})}function SJ(X,J){return $3(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=RJ($.declined,Y.credentialId,Y.accountIdentity);return{next:{...$,declined:G,rows:$.rows.map((Q)=>Q===Y?{...Q,enabled:!1}:Q)},result:void 0}})}function IJ(X,J){return $3(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:CJ($.declined,A9(Y),Y.accountIdentity),rows:$.rows.map((G)=>G===Y?{...G,enabled:!0}:G)},result:void 0}})}function hP(X,J){if(!A9(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")&&A9(X).length===1)return"bind";return"refuse"}function bJ(X,J){return $3(X,($)=>{let Y=$?.rows.find((Z)=>Z.routeId===J.routeId),G=!$||!Y?"refuse":hP(Y,J);if(!$||!Y||G==="refuse")return{result:!1};let Q=B7(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 kJ(X){X.signal?.throwIfAborted();let J=async()=>await X.isActive?.()??!0;if(!await J())return;let $=await g0({...yP,path:X.path,renew:!0});if(!$){let Y=await T9(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 $3(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=iZ(G,Y,Q);return{...JSON.stringify(G)!==JSON.stringify(z)&&{next:z},result:z}})}finally{await $.release()}}class H7{#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 $=r4([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 Z7({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 EJ(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 kJ({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 T9(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=r4([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(AJ($.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 SJ(this.#X.rosterPath,X),this.#Y=await T9(this.#X.rosterPath)}async accept(X){this.#Q(),await IJ(this.#X.rosterPath,X),this.#Y=await T9(this.#X.rosterPath)}async recordQuota(X,J,$){this.#Q();let Y=await bJ(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 T9(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 nZ(X){return J1.connect(X)}var sZ=Q7("openai");function aZ(X){return z7(X)}function T0(X){if(!X||X.corrupt===!0)return!1;return aZ(X.refresh)}class G1 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 V7(X){if(aZ(X))throw new G1}var fP=Z0("quota"),xJ="primary",wJ="secondary",gP="app_EMoamEEZ73f0CkXaXp7hrann",mP="https://auth.openai.com";async function Y3(X){V7(X.refreshToken);let J=await X.fetchImpl(`${mP}/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:gP}).toString()});if(!J.ok){let G=k5(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 uP="https://chatgpt.com/backend-api/wham/usage";async function I8(X){let J=X.logger??fP,$=X.accountKey??"unknown",Y=Date.now();J.debug("wham usage fetch started",{pid:process.pid,accountId:$});try{let G=await X.fetchImpl(uP,{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=k5(G.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${G.status}`),{status:G.status,retryAfter:z})}let Q=Cz(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:e0(G)}),G}}import{createHash as pP}from"node:crypto";var cP=globalThis.setTimeout,lP=5;function G3(X){let J=X?.quota?.checkIntervalMinutes??lP;return Math.max(1,J)*60000}function dP(X){return X?.quota?.enabled!==!1}function U7(X,J){if(!X?.resetsAt)return!1;let $=Date.parse(X.resetsAt);return Number.isFinite($)&&$<=J}function tZ(X,J,$,Y,G){if(G!==void 0&&Number.isFinite(G)&&G>$)return G;let Q=J===xJ?X?.primary:J===wJ?X?.secondary:void 0,z=Q?.resetsAt?Date.parse(Q.resetsAt):NaN;if(Number.isFinite(z)&&z>$)return z;return $+Y}function iP(X){let J=X?.quota?.minimumRemaining||{};return{primary:J.primary??J["5h"]??15,secondary:J.secondary??J["1w"]??10}}function oZ(X,J,$){if(!dP(J))return $+G3(J);let Y=iP(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 $+G3(J);G.push(Z)}if(!G.length)return $+G3(J);return Math.min(...G)+60000}function nP(X){if(!X?.quota?.mainQuota||!X.quota.mainQuotaCheckedAt)return null;return{quota:X.quota.mainQuota,checkedAt:X.quota.mainQuotaCheckedAt,tokenFingerprint:X.quota.mainQuotaToken}}function sP(X){let J=X?.quota?.refreshEveryNRequests;return typeof J==="number"&&Number.isFinite(J)&&J>0?Math.floor(J):0}function k6(X){return pP("sha256").update(X).digest("hex").slice(0,16)}class b8{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!==k6(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)!==k6(J))return this.fallbacks.delete(X),this.fallbackTokenFps.delete(X),null;return $}getAllFallbacks(){return this.fallbacks}setMain(X,J,$,Y=!1){if(!Y&&!rZ(J.quota))return;if(this.mainTokenFp=k6(X),$&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)this.clearRateLimited("main");if($)this.mainQuotaAccountId=$;if(this.main=J,vJ(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&&!rZ(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,k6($));else this.fallbackTokenFps.delete(X);if(vJ(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=k6(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 $=b8.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=k6(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=sP(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 $=nP(X);if(!$)return;let Y=J?k6(J):null;if(Y&&$.tokenFingerprint&&$.tokenFingerprint!==Y)return;let G={quota:$.quota,refreshAfter:oZ($.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&&c1(J,this.now())?J:void 0}seedFallbacksFromAccounts(X){let J=G3(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 c1(this.mainLastApiError,this.now())}isFallbackBackedOff(X,J){if(J){if(this.fallbackErrorTokenFps.get(X)!==k6(J))return!1}return c1(this.fallbackApiErrors.get(X),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(X,J){return JSON.stringify([X,k6(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<b8.API_CALL_GAP_MS)await new Promise((G)=>{let Q=cP(G,b8.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=k6(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=k6(X),this.main={quota:G,refreshAfter:oZ(G,this.storage,Q),checkedAt:Q},vJ(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:b8.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+G3(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(b8.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(b8.isAuthError(X))return;this.mainLastApiError=l4({error:X,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(X,J,$){if(b8.isAuthError($))return;let Y=k6(J),G=this.fallbackErrorTokenFps.get(X)===Y?this.fallbackApiErrors.get(X):void 0;this.fallbackApiErrors.set(X,l4({error:$,now:this.now(),previous:G})),this.fallbackErrorTokenFps.set(X,Y)}}function rZ(X){return Boolean(X.primary||X.secondary)}function vJ(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 BO}from"node:fs/promises";var Q1=Z0("refresh"),j7=Z0("accounts"),eP=1e4,XO=15000,yJ=50;function v0(X){return X.type==="oauth"&&X.corrupt!==!0}function JO(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 t1="floors-v1";function WW(X){return X.costZeroing?.enabled!==!1}class q7 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(X){super(`Fallback account ${X} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var $O=[401,403,429],eZ={primary:0,secondary:0},YO=!1,R9={primary:5,secondary:10};function Q0(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}var GO=new Set(["__proto__","constructor","prototype"]);function k8(X){return X.length>0&&!GO.has(X)}function QO(X){return X instanceof q7||Q0(X)&&X.name==="AccountRemovedDuringRefreshError"&&X.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function K7(X){return{id:typeof X.id==="string"&&X.id.trim()?X.id.trim():rP(),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 XW(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 zO(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 ZO(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(!JO(J))return null;let Y=X.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...K7(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{...K7(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{...K7(X),type:"oauth",corrupt:!0}}return{...K7(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:XW(X.lastRefreshError),lastQuotaRefreshError:XW(X.lastQuotaRefreshError),quota:zO(X.quota)}}function WO(X){if(!Q0(X))return;let J=Object.create(null);for(let[$,Y]of Object.entries(X)){if(!k8($)||!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 JW=new Set;function BW(X){if(X.length===0)return;let J=JSON.stringify([...X].sort());if(JW.has(J))return;JW.add(J),j7.warn("account load-dropped, preserved on disk",{droppedIds:X})}function HW(X){if(!Q0(X)||!Array.isArray(X.accounts))return null;let J=X.accounts,$=J.map(ZO).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);BW(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:WO(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 VW(X){if(!("claustrum"in X))return X;let{claustrum:J,...$}=X;return $}async function C9(X){try{return{exists:!0,value:JSON.parse(await BO(X,"utf8"))}}catch(J){if(J.code==="ENOENT")return{exists:!1,value:null};throw J}}function E9(X){return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0))}async function cJ(X){let J;try{J=(await C9(X)).value}catch{return null}return lJ(J)}function UW(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 KW({...X,refresh:E9({...z,mainLastRefreshError:z.mainLastRefreshError??W.lastRefreshError,mainRefreshLeaseId:H.id,mainRefreshLeaseUntil:H.until,mainRefreshLeaseTokenHash:H.tokenHash}),quota:E9({...Q,mainQuota:Z.quota,mainQuotaCheckedAt:Z.quotaCheckedAt,mainQuotaToken:Z.quotaToken,mainLastQuotaApiError:Z.lastQuotaApiError}),accounts:j})}async function b0(X){let J=await C9(X.configPath);if(!J.exists)return null;let $=await C9(X.statePath);return HW(UW(J.value,$.value))}function KW(X){return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0))}function HO(X){return E9({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 jW(X){if(X.type==="api")return E9({apiKey:X.apiKey,lastUsed:X.lastUsed});if(X.corrupt)return{};return E9({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 N7(X){return Math.max(X?.primary?.checkedAt??0,X?.secondary?.checkedAt??0)}function Q3(X,J,$){if($ in J)X[$]=J[$];else delete X[$]}function VO(X,J){return X.access===J.access&&X.refresh===J.refresh&&X.expires===J.expires&&X.lastRefreshedAt===J.lastRefreshedAt}function UO(X,J){if(!VO(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 KO=300000;function $W(X,J){if(X===void 0)return 0;return X>J+KO?0:X}function jO(X,J,$){let Y=Date.now(),G=$W(J.lastRefreshedAt,Y),Q=$W($.lastRefreshedAt,Y),z=J.expires??0,Z=$.expires??0,W=Q>G?$:G>Q?J:Z>z?$:z>Z?J:UO(J,$);Q3(X,W,"access"),Q3(X,W,"refresh"),Q3(X,W,"expires"),Q3(X,W,"lastRefreshedAt"),Q3(X,W,"lastRefreshError")}function qO(X,J){if(!Q0(X))return J;let $=X,Y=N7($.quota),G=N7(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 jO(z,$,J),z}function qW(X){let J=X.refresh?E9({enabled:X.refresh.enabled,refreshBeforeExpiryMinutes:X.refresh.refreshBeforeExpiryMinutes}):void 0,$=X.quota?E9({enabled:X.quota.enabled,checkIntervalMinutes:X.quota.checkIntervalMinutes,refreshEveryNRequests:X.quota.refreshEveryNRequests,minimumRemaining:X.quota.minimumRemaining,failClosedOnUnknownQuota:X.quota.failClosedOnUnknownQuota}):void 0;return KW({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(HO)})}async function Z3(X,J=!1){let $=Date.now(),Y=$+XO,G=0;while(Date.now()<=Y){G++;let Z=await g0({name:"save",ttlMs:eP,path:X,renew:J});if(Z)return Z;let W=Y-Date.now();if(W<=0)break;await tP(Math.min(yJ+FW(yJ),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 ${yJ}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 NW(X){let J=Object.fromEntries(X.accounts.map(($)=>[$.id,jW($)]));return{version:1,main:E9({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 lJ(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 NO(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 LO(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 DO(X,J,$){let Y=lJ(X);if(Y===null)return[];let{preservedRawEntries:G,preservedIds:Q}=NO(X,Y,J,$);return BW(Q),G}async function L7(X,J,$={}){let{configPath:Y,statePath:G}=J,Q=await Z3(Y);try{let z=await Z3(G);try{let Z=await C9(Y),W=await C9(G),B=(Z.exists?HW(UW(Z.value,W.value)):null)??FO(),H=new Set(B.accounts.map((L)=>L.id)),U=lJ(Z.value)??new Set,j=X(B,{rawRosterIds:[...U],loadedRosterIds:[...H]})??B,q=new Set($.allowDrop??[]),K=DO(Z.value,H,q),N=qW(j),F=new Set((Array.isArray(N.accounts)?N.accounts:[]).map((L)=>Q0(L)&&typeof L.id==="string"?L.id.trim():"").filter(Boolean)),O=K.filter((L)=>{if(!Q0(L))return!1;if(typeof L.id!=="string")return!1;return!F.has(L.id.trim())}),_=Q0(Z.value)?Z.value:{},C={...VW(_),...N,accounts:[...Array.isArray(N.accounts)?N.accounts:[],...O]};if($.canWrite&&!$.canWrite())return B;if(await M6(Y,C),$.canWrite&&!$.canWrite())return B;return await M6(G,NW(j)),j7.debug("account config written",{accountCount:C.accounts.length,accountIds:LO(C.accounts)}),j}finally{await z.release()}}finally{await Q.release()}}function FO(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function PO(X,J){X.main=X.main??{};let $=typeof X.main.quotaCheckedAt==="number"?X.main.quotaCheckedAt:N7(X.main.quota),Y=typeof J.quota?.mainQuotaCheckedAt==="number"?J.quota.mainQuotaCheckedAt:N7(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 OO(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 fJ(X){if(Array.isArray(X))return X.map(fJ);if(!Q0(X))return X;return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0).map(([J,$])=>[J,fJ($)]))}async function dJ(X,J,$={mainQuota:!0,mainRefresh:!0,accounts:!0},Y){let G=J.statePath,Q=await Z3(G);try{let z=(await C9(G)).value,Z=Q0(z)?{...z,version:1}:{version:1};if($.mainQuota)PO(Z,X);if($.mainRefresh)OO(Z,X);if($.accounts){let W=$.accounts===!0?null:new Set($.accounts),B=await cJ(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],jW(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 M6(G,fJ(Z))}finally{await Q.release()}}function iJ(X){return X?.fallbackOn?.length?X.fallbackOn:$O}function B3(X,J){return iJ(J).includes(X)}function MO(X){let J=X?.quota?.minimumRemaining||{};return{primary:J.primary??J["5h"]??eZ.primary,secondary:J.secondary??J["1w"]??eZ.secondary}}function gJ(X){return X?.quota?.enabled!==!1}function W3(X){return X?.quota?.failClosedOnUnknownQuota??YO}function H3(X,J,$=Date.now()){if(!gJ(J))return!0;if(!X)return!W3(J);let Y=MO(J),G=W3(J);for(let Q of["primary","secondary"]){let z=X[Q];if(!z)continue;if(U7(z,$)){if(G)return!1;continue}if(z.remainingPercent<Y[Q])return!1}return!0}function Q9(X){return X?.killswitch?.enabled===!0}function YW(X){return{primary:X?.primary??X?.["5h"]??R9.primary,secondary:X?.secondary??X?.["1w"]??R9.secondary}}function D7(X){return X?.cacheKeep??X?.cachekeep}function GW(X){return typeof X==="number"&&Number.isFinite(X)?X:0}function s6(X,J){if(!X?.killswitch)return R9;if(X.killswitch.schema===t1){let{accounts:$,defaults:Y}=X.killswitch,G=J??"main",Q=Q0($)&&Object.hasOwn($,G)&&Q0($[G])?$[G]:Q0(Y)?Y:void 0;return{primary:GW(Q?.primary),secondary:GW(Q?.secondary)}}if(J&&X.killswitch.accounts?.[J])return YW(X.killswitch.accounts[J]);return YW(X.killswitch.main)}function Z1(X,J,$,Y=Date.now()){if(!Q9(J))return!0;if(!X)return!W3(J);let G=s6(J,$),Q=W3(J);for(let z of["primary","secondary"]){let Z=X[z];if(!Z)continue;if(U7(Z,Y)){if(Q)return!1;continue}if(Z.remainingPercent<G[z])return!1}return!0}function LW(X,J,$,Y){if(!Q9(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=s6(Y,Z),H=[],U=!1;for(let j of["primary","secondary"]){let q=W[j];if(!q||U7(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 QW(X){return typeof X.version==="number"&&Array.isArray(X.accounts)}async function DW(X,J){let{configPath:$,statePath:Y}=J;if(!X)return;try{let Q=await C9($);if(Q.exists&&Q0(Q.value)&&QW(Q.value))return}catch{}let G=await Z3($);try{let Q=await Z3(Y);try{let z=await C9($);if(z.exists&&Q0(z.value)){if(QW(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={...VW(W),...qW(Z)};await M6($,B),await M6(Y,NW(Z))}finally{await Q.release()}}finally{await G.release()}}function _O(X){return X?.refresh?.enabled!==!1}function nJ(X){return(X?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function FW(X){return Math.floor(Math.random()*(X+1))}function z1(X,J,$){return!X.access||!X.expires||X.expires-$<=nJ(J)}function AO(X,J){return Boolean(X.access&&typeof X.expires==="number"&&X.expires>J)}function G9(X,J){return Boolean(X?.mainAccountId&&J.accountId&&J.accountId===X.mainAccountId)}class PW 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 OW="common-auth-placeholder:v1:openai",U8="main";function C6(X){return Q0(X)&&X.type==="oauth"&&(X.refresh===OW||X.refresh===sZ)}function z9(X){return X?.accounts.find((J)=>J.id===U8&&J.enabled!==!1&&v0(J))}function sJ(X){if(!X)return X;return{...X,accounts:X.accounts.filter((J)=>J.id!==U8)}}function x6(X,J){let $=X.accounts.findIndex((Y)=>Y.id===J.id);if($!==-1)X.accounts[$]=J}function z3(X){return X instanceof Error?X.message:String(X)}function mJ(X,J,$){if(J instanceof G1)return;X.lastRefreshError=p1({error:J,now:$,refreshToken:X.refresh,previous:X.lastRefreshError})}function hJ(X,J,$){if(J instanceof G1)return;if(X.lastQuotaRefreshError=l4({error:J,now:$,previous:X.lastQuotaRefreshError}),J?.isRefreshError===!0)mJ(X,J,$)}function zW(X,J){if(!X)return!1;if(!X.resetsAt)return!0;let $=Date.parse(X.resetsAt);return Number.isFinite($)?$>J:!0}function TO(X,J){if(!X)return!1;return zW(X.primary,J)||zW(X.secondary,J)}function RO(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 ZW(X,J,$){return!RO(X.quota,J,$)}function CO(X,J,$,Y){return b5($)&&H3(X.quota,J,Y)&&TO(X.quota,Y)}function EO(X){let J=X?.quota?.checkIntervalMinutes??5;return Math.max(1,J)*60000}var SO=60000,IO=60000,aJ=600000;function oJ(X){return`fallback-oauth-refresh-${oP("sha256").update(X).digest("base64url").slice(0,16)}`}var bO=1e4,kO=100,qh=globalThis.setTimeout.bind(globalThis),Nh=globalThis.clearTimeout.bind(globalThis);class rJ{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)V7(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:$+EO(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 dJ(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(()=>{})},SO+FW(IO)),"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(G9(J,G))continue;if(T0(G))continue;let Q=!1,z=G;try{if(z1(z,J,this.now())){let Z=z.lastRefreshError;if(Z&&r0(Z,z.refresh,this.now()))throw Q=!0,Error(e8(Z,this.now()));try{z=await this.refreshAccount(z,J),Y=!0}catch(W){if(QO(W))continue;Q=!0;let B=J.accounts.find((H)=>H.id===G.id&&v0(H));if(B&&!r0(B.lastRefreshError,B.refresh,this.now()))mJ(B,W,this.now()),x6(J,B),Y=!0;throw W}}if(this.seedFallbackQuota(z,J),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(z),J))$.push(z)}catch(Z){let W=AO(z,this.now());if(Q){if(!W)continue}else if(!W)continue;if(CO(z,J,Z,this.now()))Q1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:z.id,error:z3(Z)}),$.push(z);else if(!W3(J))$.push(z)}}if(Y){let G=structuredClone(J);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(G)).catch((Q)=>{j7.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:z3(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){j7.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:X.id,error:z3(J)})}}accountPassesQuotaPolicy(X,J){return H3(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||!_O(X))return;let J=!1;for(let $ of X.accounts){if($.enabled===!1||!v0($))continue;if(G9(X,$))continue;if(T0($))continue;if(!z1($,X,this.now()))continue;if(r0($.lastRefreshError,$.refresh,this.now()))continue;try{Q1.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){Q1.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:z3(Y)}),mJ($,Y,this.now()),x6(X,$),J=!0}}if(J)await this.save(X)}async refreshQuotaForDueAccounts(){let X=await this.load();if(!X||!gJ(X))return;if(!this.options.fetchQuotaFn)return;let J=!1;for(let $ of X.accounts){if($.enabled===!1||!v0($))continue;if(G9(X,$))continue;if(T0($))continue;let Y=$;try{if(z1(Y,X,this.now())){if(r0(Y.lastRefreshError,Y.refresh,this.now()))continue;Y=await this.refreshAccount(Y,X),J=!0}if(c1(Y.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(Y,X),!(this.quotaManager?this.quotaManager.isFallbackStale(Y.id,Y.access):ZW(Y,X,this.now())))continue;await this.refreshAccountQuota(Y,X),J=!0}catch(G){hJ($,G,this.now()),x6(X,$),J=!0}}if(J)await this.save(X),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(X={}){let J=await this.load(),$=[];if(!J||!gJ(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(G9(J,Q))continue;if(T0(Q))continue;let z=Q;try{if(z1(z,J,this.now())){let Z=z.lastRefreshError;if(Z&&r0(Z,z.refresh,this.now()))throw Error(e8(Z,this.now()));z=await this.refreshAccount(z,J),G=!0}if(!Y&&!ZW(z,J,this.now())){if(z.lastQuotaRefreshError)z.lastQuotaRefreshError=void 0,x6(J,z),G=!0;continue}await this.refreshAccountQuota(z,J),G=!0}catch(Z){hJ(Q,Z,this.now()),x6(J,Q),G=!0,$.push({accountId:Q.id,message:z3(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 x6(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 x6(J,Q),Q}async waitForConcurrentFallbackRefresh(X,J,$,Y){let G=Date.now()+bO;while(Date.now()<G){await new Promise((B)=>setTimeout(B,kO));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||!z1(z,Q,this.now())))return x6(J,z),Q1.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&&r0(W,z.refresh,this.now()))throw x6(J,z),Error(e8(W,this.now()))}return null}assertNotShieldedMainRow(X,J,$){if($.asPoolMain||!J)return;if(G9(X,J))throw new PW(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&&!z1(G,Y,this.now()))return x6(J,G),G;let Q=G??X,z=await g0({name:oJ(Q.id),ttlMs:aJ,path:this.paths.configPath,now:this.now,renew:!0});if(!z){Q1.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&&!z1(G,Y,this.now()))return x6(J,G),G;if(!G)throw new q7(X.id);Q=G;let Z=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});Q1.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,x6(J,Q),await this.save(J),!(await this.load())?.accounts.some((H)=>H.id===X.id))throw new q7(X.id);return Q1.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,x6(J,$),await this.save(J)}catch(Q){throw hJ(X,Q,this.now()),x6(J,X),Q}}}var tJ="/backend-api/wham/rate-limit-reset-credits",xO=`https://chatgpt.com${tJ}`,CW=`${tJ}/consume`,wO=`https://chatgpt.com${CW}`,vO=300000,yO=60000,hO=15000,fO=60000;function e1(X){return{configPath:X.configPath,statePath:X.statePath}}class a6 extends Error{kind;cooldownUntil;constructor(X,J,$){super(J);this.name="ResetRedemptionError",this.kind=X,this.cooldownUntil=$}}class W1 extends Error{kind;status;constructor(X,J,$){super(J);this.name="ResetCreditError",this.kind=X,this.status=$}}function EW(X,J,$){return{authorization:`Bearer ${X}`,...$?{"chatgpt-account-id":$}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":J}}function P7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function SW(X){if(!X)return;return{...X.inFlight?{inFlight:{...X.inFlight}}:{},...X.lastOutcome?{lastOutcome:{...X.lastOutcome}}:{},...X.cooldownUntil!==void 0?{cooldownUntil:X.cooldownUntil}:{}}}function O7(X){if(!P7(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}:{},...IW(X.rejectedStatus)?{rejectedStatus:X.rejectedStatus}:{},...typeof X.unknownAnswers==="number"&&Number.isSafeInteger(X.unknownAnswers)&&X.unknownAnswers>0?{unknownAnswers:X.unknownAnswers}:{}}}function IW(X){return typeof X==="number"&&X>=400&&X<500&&X!==408&&X!==409&&X!==425&&X!==429}function F7(X){return X.kind==="http_error"&&IW(X.status)}function bW(X,J){return X.chatgptAccountId!==void 0&&X.chatgptAccountId!==J||X.rejectedStatus!==void 0}function gO(X,J){if(X.chatgptAccountId!==void 0&&X.chatgptAccountId!==J)throw new a6("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function kW(X){return Boolean(X&&Object.hasOwn(X,"inFlight"))}function xW(X,J){return J-X.startedAt<vO}function X4(X,J){if(!k8(J))return;return X.reset?.[J]}function wW(X){if(!X.reset)X.reset=Object.create(null);return X.reset}function vW(X,J,$){if(!k8(J))return;let Y=wW(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 yW(X,J){let $=SW(X),Y=O7(X?.inFlight);if(kW(X)&&!Y)return{kind:"corrupt",beforeState:$};if(X?.cooldownUntil!==void 0&&X.cooldownUntil>J)return{kind:"cooldown",beforeState:$,cooldownUntil:X.cooldownUntil};if(Y&&xW(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 mO(X,J){if(!k8(J))return{kind:"fresh",beforeState:void 0};let $=await X.loadAccountsFn(e1(X));return yW($?X4($,J):void 0,X.now())}async function uO(X,J){let $;if(await X.mutateAccountsFn((Y)=>{let G=X.now(),Q=X4(Y,J);if($=yW(Q,G),$.kind==="corrupt")vW(Y,J,G);return Y},e1(X)),!$)throw Error("corrupt reset state mutation did not run");return $}async function pO(X,J,$,Y){if(!k8(J))return{kind:"fresh",beforeState:void 0};let G;if(await X.mutateAccountsFn((Q)=>{let z=X.now(),Z=X4(Q,J),W=SW(Z),B=O7(Z?.inFlight);if(kW(Z)&&!B)return vW(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&&xW(B,z))return G={kind:"claim",beforeState:W,claim:{inFlight:B,selectedCredit:{id:B.creditId}}},Q;if(B&&!bW(B,Y))return G={kind:"expired_unreconciled",beforeState:W,claim:{inFlight:B,selectedCredit:{id:B.creditId}}},Q;let H=M7($);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=wW(Q);return j[J]={...Z,inFlight:U},G={kind:"claim",beforeState:W,claim:{inFlight:U,selectedCredit:H}},Q},e1(X)),!G)throw Error("reset claim mutation did not run");return G}async function cO(X,J,$,Y,G){if(!k8(J))return;if(!J$(Y.kind))return lO(X,J,$,Y,G);await X.mutateAccountsFn((Q)=>{let z=X4(Q,J),Z=O7(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+fO;else delete z.cooldownUntil;return Q},e1(X));return}function MW(X,J){let $=O7(X?.inFlight);return $&&$.redeemRequestId===J.redeemRequestId&&$.creditId===J.creditId?$:void 0}async function lO(X,J,$,Y,G){let Q=F7(Y)?Y.status:void 0;if(!($.chatgptAccountId===void 0&&G!==void 0)&&Q!==void 0&&Q===$.rejectedStatus){let W=await X.loadAccountsFn(e1(X));return MW(W?X4(W,J):void 0,$)}let Z;return await X.mutateAccountsFn((W)=>{Z=void 0;let B=X4(W,J),H=MW(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},e1(X)),Z}function V3(X,J){if(!X||X.usedPercent<100)return!1;if(!X.resetsAt)return!0;let $=Date.parse(X.resetsAt);return!Number.isFinite($)||$>J}function eJ(X,J,$){if(!(J||V3(X.primary,$)||V3(X.secondary,$)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function _W(X,J){let $=X[J];if($===void 0||$===null)return;return typeof $==="string"?$:null}function dO(X){if(!P7(X))return;let J=_W(X,"granted_at"),$=_W(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 X$(X,J,$){let Y;try{Y=await X(xO,{method:"GET",headers:EW(J,tJ,$),signal:AbortSignal.timeout(hO)})}catch{throw new W1("http_error","reset credit list request failed")}if(!Y.ok)throw new W1("http_error",`reset credit list request failed: ${Y.status}`,Y.status);let G;try{G=await Y.json()}catch{throw new W1("invalid_response","reset credit list response was not valid JSON",Y.status)}if(!P7(G))throw new W1("invalid_response","reset credit list response was not an object",Y.status);return{credits:(Array.isArray(G.credits)?G.credits:[]).flatMap((z)=>{let Z=dO(z);return Z===void 0?[]:[Z]}),availableCount:typeof G.available_count==="number"&&Number.isFinite(G.available_count)?G.available_count:void 0}}function M7(X){return[...X].filter(hW).sort((J,$)=>Date.parse(J.expiresAt)-Date.parse($.expiresAt))[0]}function hW(X){return X.status==="available"&&X.isSupportedByPlan&&X.resetType==="codex_rate_limits"}function fW(X){return X.filter(hW).length}function J$(X){return X==="reset"||X==="already_redeemed"||X==="nothing_to_reset"||X==="no_credit"}async function iO(X,J,$,Y,G){let Q;try{Q=await X(wO,{method:"POST",headers:{...EW(J,CW,$),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:G,credit_id:Y}),signal:AbortSignal.timeout(yO)})}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||!P7(Z)||!J$(Z.code))return{kind:"ambiguous",raw:Z};return{kind:Z.code,raw:Z}}function AW(X){if(X.kind==="cooldown")throw new a6("cooldown_active","reset credit redemption is cooling down",X.cooldownUntil);throw Error(`unexpected reset state decision: ${X.kind}`)}function TW(){throw new a6("expired_unreconciled","the previous reset attempt outcome is unknown")}function RW(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 nO(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(F7(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 sO(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 gW(X,J){if(!k8(J.accountKey))throw new a6("invalid_account_key","the reset account key is reserved");let $=await X.resolveTarget(J.accountKey);if($.chatgptAccountId!==J.expectedChatgptAccountId)throw new a6("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Y=$.chatgptAccountId,G=$.accountKey==="main"?void 0:Y,Q=await mO(X,J.accountKey);if(Q.kind==="corrupt"){if(Q=await uO(X,J.accountKey),Q.kind==="corrupt")return RW($,Q.beforeState)}if(Q.kind==="cooldown")AW(Q);let z;if(Q.kind==="claim")z=Q.claim;else if(Q.kind==="expired_unreconciled"&&(J.retry||!bW(Q.claim.inFlight,Y))){if(!J.retry)TW();z=Q.claim}else{if(J.retry)throw new a6("retry_without_inflight","there is no active reset credit redemption to retry");let[j,q]=await Promise.all([X.fetchUsage($),X$(X.fetchImpl,$.accessToken,G)]),K=eJ(j,X.hasActiveRateLimitMark(J.accountKey),X.now());if(!K.ok)throw new a6("not_exhausted",K.reason);if(!M7(q.credits))throw new a6("no_eligible_credit","no eligible reset credit was returned");let N=await pO(X,J.accountKey,q.credits,Y);if(N.kind==="corrupt")return RW($,N.beforeState);if(N.kind==="cooldown")AW(N);if(N.kind==="expired_unreconciled")TW();if(N.kind!=="claim")throw new a6("no_eligible_credit","no eligible reset credit was available while claiming");z=N.claim}gO(z.inFlight,Y);let Z=await iO(X.fetchImpl,$.accessToken,G,z.inFlight.creditId,z.inFlight.redeemRequestId),W,B=!1;try{W=await cO(X,J.accountKey,z.inFlight,Z,Y)}catch{B=!0}let H=B&&J$(Z.kind),U=F7(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.":F7(Z)&&!U?sO(B,W):nO(Z),...U?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}function s(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}import{statSync as rO}from"node:fs";import{rm as uW}from"node:fs/promises";import{dirname as tO,join as pW}from"node:path";var mW=["primary","secondary"];function $$(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}function U3(X){return typeof X==="number"&&Number.isFinite(X)}function aO(X,J){if(!$$(J))return;let $=J.usedPercent;if(!U3($)||$<0||$>100)return;return{label:X,usedPercent:$,...typeof J.resetsAt==="string"?{resetsAt:J.resetsAt}:{},...U3(J.windowMinutes)&&J.windowMinutes>0?{windowMinutes:J.windowMinutes}:{}}}function oO(X){let J=X.spendControl;if($$(J)&&typeof J.reached==="boolean"){let $=(Y)=>U3(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 S9(X,J,$){if(!$$(X)||!U3(J))return;let Y=[],G=[];for(let z of mW){let Z=aO(z,X[z]);if(Z)Y.push(Z);else if($)G.push({label:z})}let Q=oO(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 x8(X){if(!G6(X))return;let J=f0(X),$={};for(let Y of mW){let G=J.limits.find((z)=>z.label===Y&&z.kind==="reading");if(!G||!U3(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 Z9=Z0("vault"),eO="openai-auth",cW={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},XM={opencode:"OpenCode",pi:"Pi"};function JM(X){return qJ(eO,X)}function lW(X){return pW(tO(X),"openai-auth-vault")}function $M(X,J){return{...LJ({stateDir:X,host:J}),rosterPath:pW(X,`${J}-roster.json`)}}var dW=2000,Y$={"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 iW(X){return X.snapshot()===void 0?"vault-unreachable":"vault-empty"}function YM(X){let J=V6(X);return J?U6(J):void 0}class G${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=JM(X.host),this.paths=$M(X.stateDir,X.host),this.#J=new H7({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:cW,connect:()=>this.#L(),isCustodyActive:()=>this.enrolled(),...X.reservedRouteIds?{reservedRouteIds:X.reservedRouteIds}:{},parseIdentity:YM,...X.now?{now:X.now}:{},onRoster:()=>{this.#$=void 0},onError:(J)=>this.#K("vault roster refresh failed",J),logger:Z9})}#U(){return(this.#X.connectionFile??e9)()}#q(){return{connectionFile:this.#U(),projectRoot:this.#X.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(X)=>Z9.debug("vault transport error",{errorClass:X})}}#L(){return this.#X.connectScoped?.()??nZ(this.#q())}#D(){return this.#X.connectEnrollment?.()??NJ(this.#q())}#K(X,J){this.#$=e0(J),Z9.warn(X,{host:this.host,error:this.#$})}#j(){return[this.paths.tokenPath,this.paths.statePath].map((X)=>{try{let J=rO(X);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let X=this.#j(),J=await X3(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=S9(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 I8({accessToken:G,fetchImpl:$,now:this.#X.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:X,logger:Z9});return await this.recordSnapshot(X,z,!0,Q),J=void 0,new Response(null,{status:200})}catch(z){J=e0(z);let Z=z?.status;if(typeof Z==="number")return new Response(null,{status:Z});throw z}},{site:"quota"}).catch((G)=>{J=e0(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(($)=>{Z9.warn("vault quota poll failed",{routeId:X,error:e0($)})}).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=GM(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),Z9.info("vault account declined",{routeId:X})}async accept(X){await this.#J.accept(X),Z9.info("vault account accepted",{routeId:X})}async status(){await this.authority();let X;try{X=await e4(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 b6("vault-unreachable",`Could not reach the Claustrum vault (${this.#U()}): ${e0(J)}. Is the vault running?`)});try{let J=new G7({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(Z9.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 uW(this.paths.tokenPath,{force:!0}),await uW(this.paths.statePath,{force:!0}),await this.authority(),this.#$=void 0,Z9.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(X){if(this.serves())OJ({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 GM(X){if(!X)return;let J=f0(X).limits.map(($)=>$.checkedAt);return J.length>0?Math.max(...J):void 0}function J4(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 ${cW.category} --operation read`]}function K3(X,J,$){let Y=`${XM[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 j3(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:[...J4(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 nW(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 sW(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 aW(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 q3(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 nW(X.checks);for(let z of sW(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 aW($,Y);$.print(`Applied ${Q.applied.length} of ${G.length} repair(s).`)}}}import{execFileSync as QM,spawn as zM}from"node:child_process";function rW(X,J=process.platform,$=QM,Y=zM){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 oW(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 _7(X,J){let $=new AbortController,Y=await X.begin({headless:!1,signal:$.signal});Y.completion.catch(()=>{}),oW(J,Y);let G=!1;try{G=await(X.openBrowser??rW)(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}),oW(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 Q$(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 tW=`${String.fromCharCode(27)}\\[[0-9;]*m`,ZM=new RegExp(tW,"g"),WM=new RegExp(`^${tW}`);function eW(X){return X.replace(ZM,"")}function B1(X,J){if(J<=0)return"";if(eW(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(WM);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 z$(){return{input:process.stdin,output:process.stdout,signals:process}}function H1(X){return X.input.isTTY===!0}function Z$(X,J=""){X.output.write(`${J}
94
- `)}var BM=50;function HM(X){if(X==="red")return B0.red;if(X==="cyan")return B0.cyan;return""}async function $4(X,J,$){if(!H1(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,N=(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-_))),L=J.slice(C,C+_);if(N(`${B0.dim}┌ ${B0.reset}${B1($.message,Math.max(1,U-4))}`),$.subtitle)N(`${B0.dim}│${B0.reset}`),N(`${B0.cyan}◆${B0.reset} ${B1($.subtitle,Math.max(1,U-4))}`),N("");for(let A of F)N(`${B0.cyan}│${B0.reset} ${B1(A,Math.max(1,U-4))}`);if(F.length)N(`${B0.cyan}│${B0.reset}`);for(let A=0;A<L.length;A++){let T=L[A];if(!T)continue;let k=C+A===z,p=HM(T.color),i=p?`${k?"":B0.dim}${p}${T.label}${B0.reset}`:k?T.label:`${B0.dim}${T.label}${B0.reset}`;if(T.hint)i+=` ${B0.dim}${T.hint}${B0.reset}`;i=B1(i,Math.max(1,U-8)),N(k?`${B0.cyan}│${B0.reset} ${B0.green}●${B0.reset} ${i}`:`${B0.cyan}│${B0.reset} ${B0.dim}○${B0.reset} ${i}`)}let P=L.length<J.length?` (${C+1}-${C+L.length}/${J.length})`:"";N(`${B0.cyan}│${B0.reset} ${B0.dim}${B1(`Up/Down to select | Enter: confirm | Esc: back${P}`,Math.max(1,U-6))}${B0.reset}`),N(`${B0.cyan}└${B0.reset}`);for(let A=K;A<q;A++)N("");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",N),Q?.removeListener("SIGTERM",N)},K=(O)=>{q(),U(O)},N=()=>K(null),F=(O)=>{for(let _ of Q$(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),BM);break;default:break}}};Q?.once("SIGINT",N),Q?.once("SIGTERM",N);try{Y.setRawMode(!0)}catch{q(),U(null);return}Y.resume(),G.write(B0.hide),H(),Y.on("data",F)})}async function W$(X,J,$=!1){if(!H1(X))return!1;return await $4(X,$?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:J})??!1}function XB(X){let J=H1(X);return{terminal:X,interactive:J,print:($)=>Z$(X,$),confirm:($,Y)=>W$(X,$,Y),select:async($,Y)=>J&&$.length>0?$4(X,$,Y):null}}function VM(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 V1(X){let J=X.terminal??z$(),$=XB(J);if(!$.interactive)return VM($,X);if(X.actions.length===0)return $.print("No actions are available."),{status:"cancelled"};let Y=await $4(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 $B="disabled from the auth menu",JB=8;async function w8(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 V$(X){let{rows:J}=await w8(X);return J.some(($)=>$.credential!==void 0)}function U$(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 UM(X){if(X.problem)return[X.problem];if(X.rows.length===0)return["No accounts yet."];let J=X.rows.slice(0,JB).map((Y)=>`${Y.id}: ${U$(Y)}`),$=X.rows.length-JB;if($>0)J.push(`... and ${$} more`);return J}function KM(X){return X instanceof Error?X.message:String(X)}async function K$(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:U$(Y)})),{message:$})}function jM(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 YB(X,J=Date.now()){let $=G6(X.quota)?f0(X.quota):void 0,Y=A7($,{now:J,form:"full"});return(Y.length>0?Y:[T8($,{now:J})]).map((G)=>` ${G}`)}function GB(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 _7($,J),{rows:G}=await w8(X.store),Q=(X.newAccountId??jM)(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 QB(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 w8(X.store),G=await K$(J,Y,"Re-authenticate which account?");if(!G)return;let Q=await _7($,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 zB(X){return{...X.protect?{protect:X.protect}:{},...X.extraLocks?{extraLocks:X.extraLocks}:{}}}function ZB(X){return X instanceof K0&&X.kind==="row-protected"?X.message:void 0}function WB(X){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run(J){let{rows:$}=await w8(X.store),Y=await K$(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,zB(X))}catch(G){let Q=ZB(G);if(Q===void 0)throw G;J.print(`Account ${Y.id} was kept: ${Q}`);return}J.print(`Removed account ${Y.id}.`)}}}function B$(X){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run(J){let{rows:$}=await w8(X.store),Y=await K$(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??$B,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 BB(X){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run(J){let $=await w8(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}: ${U$(Y)}`)}}}function H$(X){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run(J){let $=await w8(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,KM(Z))}}let Q=await w8(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 YB(z,(X.now??Date.now)()))J.print(W)}}}}function HB(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 w8(X.store);if($.problem){J.print($.problem);return}let Y=[],G=[];for(let Q of $.rows)try{await X.store.remove(Q.id,zB(X)),Y.push(Q.id)}catch(z){let Z=ZB(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 j$(X){return VB(X,await X.custody?.()===!0)}function VB(X,J){let $=X.doctor?.length?[q3({checks:X.doctor})]:[],Y=[...X.extraActions??[]];if(J)return[BB(X),B$(X),H$(X),...$,...Y];return[...X.login?[GB(X),QB(X)]:[],WB(X),B$(X),H$(X),...$,...Y,HB(X)]}async function q$(X){let J=await X.custody?.()===!0,$=VB(X,J),[Y,G]=await Promise.all([w8(X.store),X.status?.()??[]]);return V1({title:X.title,subtitle:J?"Accounts come from the vault; select an action":"Select an account action",status:[...G,...UM(Y)],actions:$,...X.terminal?{terminal:X.terminal}:{}})}function N$(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function UB(X){return X!==void 0}function L$(X){return async(J)=>{if(!UB(J))return X.login();if(!await X.hasCredential())return X.login(J);return await X.openMenu(J),N$()}}function v8(X){return X.authority!=="local"}async function o6(X){return{authority:await X.authority(),status:await X.status(),identities:X.identities(),routes:new Set(X.routes().map((J)=>J.id))}}async function T7(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."),dW)})])}finally{clearTimeout(J)}}function y8(X){return X.email||X.label||X.routeId}function KB(X,J){let $=f0(G6(X.quota)?X.quota:void 0),Y=A7($,{now:J});return(Y.length>0?Y:[T8($,{now:J})]).map((G)=>` ${G}`)}var N3="Accounts are managed in the vault with ck. Disconnect to use local accounts.",h8="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function jB(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 L3(X,J){let $=await T7(J),Y=await o6(J),{status:G}=Y,Q=v8(Y)?void 0:await X.store.read(),z=await j$(X),Z=new Set(["check-quotas",...(X.extraActions??[]).map((H)=>H.id)]),W=z.filter((H)=>!v8(Y)||Z.has(H.id)).map((H)=>({...H,run:async(U)=>{if(!Z.has(H.id)&&v8(await o6(J))){U.print(h8);return}await J.authority(),await H.run(U)}})),B=W.find((H)=>H.id==="check-quotas");if(B)B.run=async(H)=>{await T7(J);let U=await o6(J),j=v8(U)?void 0:await X.store.read();if(!j)H.print(N3);else if(j.status!=="ready")H.print("The local account store could not be read.");else for(let N of j.rows){H.print(jB(N));try{if(X.pollQuota&&N.credentialEpoch!==void 0){let _=await X.pollQuota(N);await X.store.recordQuota(N.id,{credentialEpoch:N.credentialEpoch,...N.identity!==void 0?{identity:N.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===N.id):void 0;for(let _ of KB(O??N,(X.now??Date.now)()))H.print(_)}let q=U.routes;for(let N of J.snapshot()?.rows??[]){if(H.print(`Vault ${y8(N)}: ${N.enabled?N.state:"declined"}`),!q.has(N.routeId)){H.print(" quota check skipped: account is not enabled and active");continue}let F=await J.pollQuota(N.routeId);if(!F.ok)H.print(` quota check failed: ${F.error??"vault unavailable"}`);let O=J.snapshot()?.rows.find((_)=>_.routeId===N.routeId);for(let _ of KB({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 V1({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 ${y8(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!Q?[N3]:Q.status==="ready"?Q.rows.map((H)=>jB(H)):["The local account store could not be read."]],actions:W,...X.terminal?{terminal:X.terminal}:{}})}function qB(X){return s(X)?{...X}:{}}function R7(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 D$(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 o6(J);if(!v8(Z))return z;let W=[...Z.status.accounts.map((B)=>({id:B.routeId,label:y8(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 o6(J),Z=qB(Q.settings.killswitch);if(!v8(z)||!Q.settings.killswitch)return Q;let W=qB(Z.accounts);for(let B of z.status.accounts)W[B.routeId]=s6({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 NB(X,J){let $=i9(X),Y=i9({command:X.command,title:X.title,store:D$(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 o6(J),U=v8(H),j=U?Y:$,K=(await j.open(B)).menu.sections.find((L)=>L.id===W);if(!K)throw new b6("unavailable","The account menu is unavailable.");if(!U)return{lines:K.lines,items:K.items.map((L)=>({...L,actions:L.actions.map((P)=>R7(j,W,P,L.id))})),actions:K.actions.map((L)=>R7(j,W,L))};let N=new Map(H.status.accounts.map((L)=>[L.routeId,L])),F=(X.now??Date.now)(),O=(L)=>({id:"check",label:L?"Check this account":"Check now",group:"Actions",run:async()=>{let A=[...(await o6(J)).routes].filter((T)=>!L||T===L);if(L&&A.length===0)throw new b6("unavailable","This vault account cannot be checked right now.");for(let T of A){let k=await J.pollQuota(T);if(!k.ok)throw new b6("quota-check-failed",`${T}: ${k.error??"vault unavailable"}`)}return`Checked quota for ${A.length} account${A.length===1?"":"s"}.`}});if(W==="quota"){let L=(P,A)=>T8(f0(P.quota,X.quota?.scope),{now:F,form:A});return{lines:H.status.accounts.filter((P)=>!H.routes.has(P.routeId)).map((P)=>`${y8(P)} (${P.enabled?P.state:"disabled"}): ${L(P,"compact")}`),items:H.status.accounts.filter((P)=>H.routes.has(P.routeId)).map((P)=>({id:P.routeId,label:y8(P),group:"Accounts",status:L(P,"compact"),detail:L(P,"full"),actions:[O(P.routeId)]})),actions:H.routes.size>0?[O()]:[]}}let _=K.items.map((L)=>{let P=N.get(L.id),A=P&&W==="accounts"?`Vault · ${P.credentialType==="oauth"?"login":"API key"} · ${P.state} · ${P.enabled?"enabled":"declined"}`:L.detail;return{id:L.id,label:L.label,detail:A,group:L.group,status:P&&W==="accounts"?P.enabled?P.state:"disabled":L.status,...L.facts?{facts:L.facts}:{},actions:P&&W!=="limits"?[]:L.actions.map((T)=>R7(j,W,T,L.id))}}),C=K.actions.filter((L)=>W==="limits"||W==="routing"&&L.id==="mode").map((L)=>R7(j,W,L));return{lines:W==="accounts"?[`${H.status.accounts.length} vault account${H.status.accounts.length===1?"":"s"}`,`${H.routes.size} can route`,N3]:K.lines,items:_,actions:C}},Q=i9({...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 o6(J);if(v8(H))return{lines:[N3]};return W.build(B)}})}),z=async()=>{if(!v8(await o6(J)))return{menu:$,error:void 0};let W=await T7(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 o6(J)).routes.size===0||W.sectionId==="limits"&&W.itemId!==void 0&&!(await o6(J)).status.accounts.some((j)=>j.routeId===W.itemId)))return{...await Z(H,B),ok:!1,code:"vault-local-action",text:h8};return U.apply(W,B)}}}var u6="openai",O$="OpenAI accounts",U1="main",FB="that account is already your main account, so it was not added again",t6=Z0("commands"),PB=new Set(["__proto__","constructor","prototype"]);function OB(X,J){let $={version:1,accounts:[],killswitch:X},Y=s(X.accounts)?Object.keys(X.accounts):[],G={};for(let Z of new Set([U1,...J,...Y])){if(PB.has(Z))continue;let W=s6($,Z===U1?void 0:Z);G[Z]={primary:W.primary,secondary:W.secondary}}let Q=s6($,void 0),z={...X};return delete z.main,z.accounts=G,z.defaults={primary:Q.primary,secondary:Q.secondary},z.schema=t1,z}function MB(X,J){let $=s(X.accounts)?{...X.accounts}:{};for(let G of new Set([U1,...J])){if(PB.has(G)||Object.hasOwn($,G))continue;$[G]={primary:R9.primary,secondary:R9.secondary}}let Y=s(X.defaults)?X.defaults:{primary:R9.primary,secondary:R9.secondary};return{...X,accounts:$,defaults:Y,schema:t1}}function F$(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!==t1)X.killswitch=OB(Y,J),$=!0;return $}async function LB(X){let J=await X.read();return J.status==="ready"?J.rows.map(($)=>$.id):[]}function E7(X){let J=async()=>{let Y=await X.readSettings();if(Y.status==="error")return Y;let G=structuredClone(Y.settings);return F$(G,await LB(X)),{...Y,settings:G}},$=async(Y,G)=>{let Q=await LB(X);return X.updateSettings(async(z)=>{F$(z,Q);let Z=await Y(z)??z;if(s(Z.killswitch)&&Z.killswitch.schema!==t1)Z.killswitch=MB(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 S7(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===U1)throw new b6("main-account",FB);let K=q??j.find((F)=>F.id===W.id&&F.id!==U1);if(!K||W.credential.type!=="oauth")return X.add(W,B);let N=await G(K.id,W.credential,W.identity!==void 0?{identity:W.identity}:{},B?.extraLocks?{extraLocks:B.extraLocks}:void 0);return t6.info("account signed in again",{id:K.id}),{id:N.id,outcome:"rotated",credential:N.credential,credentialEpoch:N.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 K1(X,J,$){await E7(X).updateSettings((Y)=>{$(Y);return},J?{extraLocks:J}:{})}var qM=["version","accounts","commonAuthPool"];function M$(X,J){return async($)=>{let Y;if(await E7(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 _B="migration";function P$(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:u6,title:O$,sections:[{id:_B,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 DM($)}var NM=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function LM(X){let J=X.toLowerCase().replace(/[-_]/g,"");if(NM.has(J))return!0;return J.endsWith("token")||J.endsWith("key")||J.endsWith("secret")}function C7(X,J,$){if(Array.isArray(X))return X.map((G,Q)=>C7(G,`${J}[${Q}]`,$));if(!s(X))return X;let Y={};for(let[G,Q]of Object.entries(X)){if(LM(G)){$.push(`${J}.${G}`);continue}Y[G]=C7(Q,`${J}.${G}`,$)}return Y}function DM(X){let J=[],$=C7(X,"menu",J);if(J.length>0)t6.warn("credential-shaped field stripped before RPC",{fields:J});return $}function AB(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 TB(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:
87
+ </html>`,b2=[],n4,J9=new Map;function Oz(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(s4,J)})}function _z(X){X.close(()=>{}),X.closeIdleConnections?.(),setTimeout(()=>{X.closeAllConnections?.()},25).unref?.()}function n9(){return J9.size}function $9(X){if(J9.delete(X),n9()===0)s9()}async function f5(){let X=`http://localhost:${s4}/auth/callback`;if(b2.length>0)return{port:s4,redirectUri:X};if(n4)return n4;n4=(async()=>{let J=(Q,z)=>{let Z=new URL(Q.url||"/",`http://127.0.0.1:${s4}`);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 N=U||H;if(B){let K=J9.get(B);if(K)K.reject(Error(N)),$9(B);else if(n9()===0)s9()}else if(n9()===0)s9();z.writeHead(200,{"Content-Type":"text/html"}),z.end(I2(N));return}if(!B){if(n9()===0)s9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(I2("Missing state parameter"));return}if(!W){if(n9()===0)s9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(I2("Missing authorization code"));return}let j=J9.get(B);if(!j){if(n9()===0)s9();z.writeHead(400,{"Content-Type":"text/html"}),z.end(I2("Unknown state — authorization may have expired"));return}$9(B),eD(W,X,j.pkce).then((N)=>j.resolve(N)).catch((N)=>j.reject(N)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(JF);return}if(Z.pathname==="/cancel"){let W=Z.searchParams.get("state"),B=W?[W]:[...J9.keys()];z.writeHead(200),z.end("Login cancelled");for(let H of B){let U=J9.get(H);if(!U)continue;U.reject(Error("Login cancelled")),$9(H)}if(n9()===0)s9();return}z.writeHead(404),z.end("Not found")},$=Pz(J);await Oz($,"127.0.0.1");let Y=[$],G=Pz(J);try{await Oz(G,"::1"),Y.push(G)}catch(Q){let z=Q.code;if(z!=="EADDRNOTAVAIL"&&z!=="EAFNOSUPPORT")throw _z($),Q}return b2=Y,{port:s4,redirectUri:X}})();try{return await n4}finally{n4=void 0}}function s9(){let X=b2;b2=[];for(let J of X)_z(J)}function g5(X,J,$=300000,Y){return new Promise((G,Q)=>{if(Y?.aborted){$9(J),Q(Error("Login cancelled"));return}let z=setTimeout(()=>{if(J9.get(J))$9(J),Q(Error("OAuth callback timeout — authorization took too long"))},$),Z=()=>{if(clearTimeout(z),J9.get(J))$9(J),Q(Error("Login cancelled"))};if(Y)Y.addEventListener("abort",Z);J9.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 m5(X){let J=await fetch(`${a9}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":x2(X)},body:JSON.stringify({client_id:k2})});if(!J.ok)throw Error("Failed to initiate device authorization");let $=await J.json();return{deviceData:$,url:`${a9}/codex/device`,instructions:`Enter code: ${$.user_code}`}}async function u5(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(`${a9}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":x2(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(`${a9}/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:`${a9}/deviceauth/callback`,client_id:k2,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+aD,W);try{await sD(B,void 0,{signal:$})}catch(H){if(H instanceof Error&&H.name==="AbortError")throw Error("Device authorization cancelled");throw H}}}async function v2(X){let{label:J,headless:$=!1,signal:Y,version:G}=X;if(v5(J),$){let{deviceData:H,url:U,instructions:j}=await m5(G),N=(async()=>{let K=await u5(H,G,Y),q=Date.now(),F=Z8(K);return{id:v5(J||F||crypto.randomUUID()),label:J||void 0,type:"oauth",access:K.access_token,refresh:K.refresh_token,expires:q+(K.expires_in??3600)*1000,enabled:!0,addedAt:q,lastUsed:q,lastRefreshedAt:q,accountId:F}})();return{url:U,instructions:j,completion:N}}let{redirectUri:Q}=await f5(),z=await y5(),Z=w2(crypto.getRandomValues(new Uint8Array(32)).buffer),W=h5(Q,z,Z),B=(async()=>{try{if(Y?.aborted)throw Error("Login cancelled");let H=await g5(z,Z,void 0,Y),U=Date.now(),j=Z8(H);return{id:v5(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{$9(Z)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:B}}function y2(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 p5(X){let J=Number(X);return Number.isFinite(J)&&J>0?J:void 0}function Az(X){return typeof X==="number"&&Number.isFinite(X)&&X>=0?X:void 0}function Tz(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=p5(X.get(`${G}-window-minutes`)),z=y2(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 Ez=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function Sz(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 o9(X){if(Ez.some((G)=>Sz(X,G)==="invalid"))return{};let J={},$=Tz(X,"x-codex-primary-used-percent");if($)J.primary=$;let Y=Tz(X,"x-codex-secondary-used-percent");if(Y)J.secondary=Y;return J}function d1(X){let J=Ez.map(($)=>Sz(X,$));return J.includes("valid")&&!J.includes("invalid")}function Rz(X){if(!X)return;if(!Number.isFinite(X.used_percent)||X.used_percent<0||X.used_percent>100)return;let J=p5(X.window_minutes),$=y2(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 Iz(X){let J={},$=Rz(X.rate_limits?.primary);if($)J.primary=$;let Y=Rz(X.rate_limits?.secondary);if(Y)J.secondary=Y;return J}function l1(X){if(X==null||X==="")return;let J=Number(X);return Number.isFinite(J)&&J>=0?J:void 0}function Cz(X){if(!X)return;if(!Number.isFinite(X.used_percent)||X.used_percent<0||X.used_percent>100)return;let J=p5(X.limit_window_seconds),$=y2(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 bz(X){let J={},$=Cz(X.rate_limit?.primary_window);if($)J.primary=$;let Y=Cz(X.rate_limit?.secondary_window);if(Y)J.secondary=Y;let G=Az(X.rate_limit_reset_credits?.available_count);if(G!==void 0)J.resetCreditsAvailable=G;let Q=Az(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=l1(z.limit),B=l1(z.used),H=l1(z.remaining),U=l1(z.used_percent),j=l1(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:y2(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=l1(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 mF,statSync as uF}from"node:fs";import{tmpdir as HZ,userInfo as pF}from"node:os";import{join as a1}from"node:path";import{debuglog as KF}from"node:util";import{createHmac as QF,randomBytes as zF,timingSafeEqual as ZF}from"node:crypto";import GF from"node:net";var m6=2,h2=21,f2=5,c5=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 kz=u.Goodbye;function xz(X){return X===u.Cancel||X===u.Ping||X===u.Pong||X===u.Goodbye}var t0;(function(X){X[X.Passive=0]="Passive",X[X.Interactive=1]="Interactive",X[X.Background=2]="Background"})(t0||(t0={}));var K6;(function(X){X[X.Normal=0]="Normal",X[X.Expedite=1]="Expedite",X[X.Sheddable=2]="Sheddable"})(K6||(K6={}));var wz=1,vz=6,l5=1,$F=8,yz=48,d5=4;var hz=0;function T6(X,J,$,Y=K6.Normal){let G=0;if(X)G|=wz;if(G|=J<<l5,$)G|=$F;return G|=Y<<d5,G}function i5(X){return(X&wz)!==0}function fz(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 YF(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>kz)throw new I0(`unknown frame type byte ${Y}`,"unknown_frame_type");let Z=Y;if((G&hz)!==0)throw new I0(`reserved flag bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((G&vz)>>l5===3)throw new I0(`reserved priority bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(G&yz)>>d5;if(W===3)throw new I0(`reserved admission class set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===K6.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(xz(Z)&&J!==0)throw new I0(`pure-header frame ${u[Z]} declared non-zero body length ${J}`,"pure_header_frame_with_body")}function n5(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>kz)throw new I0(`unknown frame type byte ${G}`,"unknown_frame_type");let Q=G,z=X[6];if((z&hz)!==0)throw new I0(`reserved flag bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((z&vz)>>l5===3)throw new I0(`reserved priority bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Z=(z&yz)>>d5;if(Z===3)throw new I0(`reserved admission class set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Z===K6.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(xz(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 j6(X,J,$,Y,G,Q){return C8(2,X,J,$,Y,G,Q)}function C8(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 YF(Z),{header:Z,body:z}}function W8(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=fz(X.header),$=new Uint8Array(J.length+X.body.length);return $.set(J,0),$.set(X.body,J.length),$}class Y9 extends Error{}class B8 extends Error{}class E8 extends Error{cause;constructor(X,J){super(X);this.cause=J}}class O9 extends Error{cause;constructor(X,J){super(X);this.cause=J}}function gz(X){return Buffer.from(X.buffer,X.byteOffset,X.byteLength)}var mz=Symbol("subc.socket.writeBorrowed"),uz=Symbol("subc.socket.writeTrackedBorrowed");function H8(X,J,$){let Y=X[mz];return Y?Y.call(X,J,$):X.write(J,$)}function s5(X,J,$){let Y=X[uz];return Y?Y.call(X,J,$):X.writeTracked(J,$)}class r9{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 Y9("subc closed the connection"))),X.on("close",()=>J(new Y9("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect(X,J,$){return new Promise((Y,G)=>{let Q=GF.connect({host:X,port:J});Q.setNoDelay(!0);let z=setTimeout(()=>{Q.destroy(),G(new B8(`timed out connecting to ${X}:${J}`))},Math.max(0,$-Date.now()));Q.once("connect",()=>{clearTimeout(z),Y(new r9(Q))}),Q.once("error",(Z)=>{clearTimeout(z),G(Z)})})}async readFrame(X,J,$){let Y=await this.readExact(f2,X),G=Y[4];if(G!==m6)throw new I0(`unsupported envelope version ${G}`,"unsupported_version");let Q=await this.readExact(h2-f2,X),z=new Uint8Array(h2);z.set(Y),z.set(Q,f2);let Z=n5(z);if(Z.len>c5)throw new I0(`frame body ${Z.len} exceeds max ${c5}`,"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 B8(`timed out waiting for ${X} bytes`));return}G=setTimeout(()=>{this.waiter=null,Y(new B8(`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[mz](X,J){await this.writeBuffer(gz(X),J)}[uz](X,J){return this.writeTrackedBuffer(gz(X),J)}async writeBuffer(X,J){try{await this.writeTrackedBuffer(X,J).completed}catch($){if($ instanceof E8||$ instanceof O9)throw $.cause??$;throw $}}writeTrackedBuffer(X,J){if(this.closedErr)return{queued:!1,completed:Promise.reject(new E8("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 E8("timed out before bytes could be queued to subc",new B8("timed out writing to subc"))));return}G=setTimeout(()=>{let H=new B8("timed out writing to subc");W(()=>Z($?new O9("timed out after bytes were handed to the subc socket",H):new E8("timed out before bytes could be queued to subc",H)))},B);try{this.sock.write(X,(H)=>{W(()=>{if(H)Z(new O9("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 E8("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 lz=32;var g2=4096,dz="subc-server-v1",iz="subc-client-v1",WF="client";class R6 extends Error{}function o5(X,J,$,Y,G){let Q=QF("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 pz(X,J){if(X.length!==J.length)return!1;return ZF(Buffer.from(X),Buffer.from(J))}async function cz(X,J,$){let Y=Buffer.from(JSON.stringify(J),"utf8");if(Y.length>g2)throw new R6(`auth message too large: ${Y.length} > ${g2}`);let G=new Uint8Array(4);new DataView(G.buffer).setUint32(0,Y.length,!0),await H8(X,G,$),await H8(X,Y,$)}async function BF(X,J){let $=await X.readExact(4,J),Y=new DataView($.buffer,$.byteOffset,4).getUint32(0,!0);if(Y>g2)throw new R6(`auth message too large: ${Y} > ${g2}`);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 R6(`auth message JSON decode failed: ${String(Q)}`)}}function a5(X,J){if(!Array.isArray(X))throw new R6(`auth field '${J}' must be a byte array`);for(let $ of X)if(typeof $!=="number"||!Number.isInteger($)||$<0||$>255)throw new R6(`auth field '${J}' has invalid byte ${String($)}`);return Uint8Array.from(X)}async function a4(X,J,$){let Y=new Uint8Array(zF(lz));await cz(X,{client_nonce:Array.from(Y),role:WF},$);let G=await BF(X,$),Q=a5(G.server_nonce,"server_nonce"),z=a5(G.daemon_id,"daemon_id"),Z=a5(G.server_proof,"server_proof"),W=o5(J.key,dz,Y,Q,z);if(!pz(W,Z))throw new R6("server proof mismatch — wrong key or impostor daemon");if(!pz(z,J.daemonId))throw new R6("daemon id mismatch — connection file points at a different daemon");let B=o5(J.key,iz,Y,Q,z);await cz(X,{client_auth:Array.from(B)},$)}import{promises as r5}from"node:fs";var nz=1,sz=32,az=16;class Q6 extends Error{}function oz(X,J){if(!Array.isArray(X))throw new Q6(`connection file field '${J}' must be a JSON array of bytes`);for(let $ of X)if(typeof $!=="number"||!Number.isInteger($)||$<0||$>255)throw new Q6(`connection file field '${J}' has invalid byte ${String($)}`);return Uint8Array.from(X)}function HF(X){if(X.schema!==nz)throw new Q6(`unsupported connection file schema ${X.schema}; expected ${nz}`);if(X.endpoints.length===0)throw new Q6("connection file must include at least one endpoint");if(X.key.length<sz)throw new Q6(`connection file key is too short: ${X.key.length} bytes, need at least ${sz}`);if(X.daemonId.length!==az)throw new Q6(`connection file daemon_id must be ${az} bytes, got ${X.daemonId.length}`)}async function VF(X){if(process.platform==="win32")return;let $=(await r5.stat(X)).mode&511;if(($&63)!==0)throw new Q6(`connection file ${X} has insecure permissions 0o${$.toString(8)}; expected owner-only 0600`)}async function i1(X){await VF(X);let J=await r5.readFile(X,"utf8"),$;try{$=JSON.parse(J)}catch(Z){throw new Q6(`connection file JSON read failed for ${X}: ${String(Z)}`)}let Y=$.wire_version;if(Y!==void 0&&Y!==m6)throw new Q6(`connection file wire_version ${String(Y)} but this client speaks ${m6}; the client library must be upgraded`);let G=$.endpoints;if(!Array.isArray(G))throw new Q6("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 Q6("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),z={schema:$.schema,endpoints:Q,key:oz($.key,"key"),daemonId:oz($.daemon_id,"daemon_id"),pid:$.pid,daemonVer:$.daemon_ver??""};return HF(z),z}var rz=new WeakMap,t5=new WeakMap;class e5 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 M9{handlers=new Map;declaredFamilies=null;onRequest(X,J){if(!UF(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 e5(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 m2{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(),rz.set(this,$),t5.set(this,Y),Object.freeze(this)}onRequest(X,J){t5.get(this).onRequest(X,J)}static create(X,J,$,Y){return new m2(X,J,$,Y)}}function u2(X,J,$,Y=new M9){return m2.create(X,J,$,Y)}function tz(X,J){return t5.get(X)?.handler(J)}function UF(X){return/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(X)}class G9 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 n1(){return Object.freeze({})}function o4(X,J){return rz.get(X)===J}function p2(X,J){return X===J}var ez=KF("subc-client"),jF=1e4,s1=30000,NF=50,qF=2000,XZ="request_deadline",XJ="deadline_exceeded_no_drop_observed",LF=30000,DF=30000,JZ=new Uint8Array(0),FF="management_surface",i2="SUBC_MODULE_ID",n2="SUBC_LAUNCH_NONCE",s2={baseMs:100,capMs:2000,maxAttempts:6};class z6 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 N0?this.cause.detail:void 0}}class N0 extends Error{code;detail;constructor(X,J,$){super(X);this.code=J,this.detail=$}}var $Z=new WeakMap;function JJ(X){if(X instanceof Uint8Array)return X;let J=X===null?"null":Array.isArray(X)?"array":typeof X;throw new N0(`binary request body must be a Uint8Array; got ${J}`,"binary_body_required")}class t9{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=n1();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=MF(X),$=await t9.openConnection(J);return new t9($.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 N0(`no catalog claimant for capability ${X}`,"capability_unprovided");if(J.length>1)throw new N0(`multiple catalog claimants for capability ${X}: ${J.join(", ")}`,"capability_ambiguous");return J[0]}async resolveProviders(X){if(!zZ(X))throw new N0(`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=$J($),G=$.reverseRequests??new M9;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 N0(`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 N0("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 N0("route.open response was not installed");return Z}async request(X,J,$={}){this.assertLiveHandle(X);let Y=$.binary??!1,G=Y?JJ(J):J instanceof Uint8Array?J:this.encode(J),Q=$.priority??t0.Interactive,z=$.admissionClass??K6.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 N0("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=JJ(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 z6))throw this.terminalCallError("managed call failed",Q);let z=a2(Q.cause instanceof N0?$Z.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!==XJ){if(this.closedErr)this.scheduleReconnectAfterDrop(Q)}else if(Q.kind==="outcome_unknown"&&Q.code===XJ)this.probeLivenessAfterDeadline();throw Q}}}subscribe(X,J,$,Y={}){this.assertLiveHandle(X);let G=J instanceof Uint8Array?J:this.encode(J),Q=Y.priority??t0.Interactive,z=Y.admissionClass??K6.Normal,Z=this.allocateCorr(),W=c2(X,Z),B=null,H=null,U=new Promise((K,q)=>{if(this.closedErr){q(this.closedErr);return}H=K,B={handle:X,resolve:()=>K(),reject:q,onProgress:$,timer:null,subscription:!0},this.pending.set(W,B);let F=j6(u.Request,T6(!1,Q,!1,z),X.channel,X.epoch,Z,G);H8(this.sock,W8(F),Date.now()+s1).catch((O)=>{let _=this.pending.get(W);if(_)this.rejectPending(W,_,O instanceof Error?O:new N0(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,$=t0.Interactive){this.assertLiveHandle(X);let Y=j6(u.Cancel,T6(!1,$,!1),X.channel,X.epoch,J,JZ);H8(this.sock,W8(Y),Date.now()+s1).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&&p2(Y.handle,X))Y.closed=!0,Y.handle=null,this.routes.delete($);if(J.drain)await this.drainUnaryOnHandle(X);if(this.failHandle(X,new N0("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=YZ(X,J,$J($),($.reverseRequests??new M9).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 N0("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 $=j6(u.Goodbye,T6(!1,t0.Interactive,!1),X.channel,X.epoch,0n,JZ),Y=s5(this.sock,W8($),Date.now()+s1);if(!Y.queued&&J)this.closeConnectionAfterCleanupFailure();Y.completed.catch(()=>{if(J&&!Y.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection(X){let J=await i1(X.connectionFile),$=Date.now()+(X.handshakeTimeoutMs??jF),Y=J.endpoints[0],G=await r9.connect(Y.host,Y.port,$);try{await a4(G,J,$)}catch(Q){throw G.close(),Q}return{sock:G,conn:J}}async controlRpc(X,J,$){return this.send(null,X,t0.Interactive,K6.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(q){return Promise.reject(q)}let U=c2(X,H),j=X?.channel??0,N=X?.epoch??0,K=j6(u.Request,T6(W,$,!1,Y),j,N,H,J);return new Promise((q,F)=>{let O=G??s1,_={handle:X,resolve:q,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,$);H8(this.sock,W8(K),Date.now()+O).catch((C)=>{let L=this.pending.get(U);if(L)this.rejectPending(U,L,C instanceof Error?C:new N0(String(C)))})})}arbitrateTimeout(X,J,$,Y,G){let Q=()=>{if(J.onLateResponse)this.lateResponses.set(X,J.onLateResponse);this.rejectPending(X,J,new N0(this.timeoutMessage($,Y,G),XZ))},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?JJ(J):J instanceof Uint8Array?J:this.encode(J),Q=$.priority??t0.Interactive,z=$.admissionClass??K6.Normal;try{let Z=await this.sendManaged(X,G,Q,z,$.timeoutMs,$.onProgress,Y,$.signal);return this.decodeReply(Z)}catch(Z){if(Z instanceof z6)throw Z;throw this.terminalCallError("managed call failed",Z)}}sendManaged(X,J,$,Y,G,Q,z=!1,Z){try{this.assertLiveHandle(X)}catch(N){return Promise.reject(this.notSentCallError("request used a stale route handle",N))}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(N){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",N))}let B=c2(X,W),H=j6(u.Request,T6(z,$,!1,Y),X.channel,X.epoch,W,J),U=!1,j=(N)=>{if(!U)return this.notSentCallError("request bytes were not queued to the subc socket",N);if(N instanceof N0&&N.code===XZ)return new z6("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${r4(N)}`,XJ,N);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",N)};return new Promise((N,K)=>{let q=G??s1,F={handle:X,resolve:N,reject:K,onProgress:Q,timer:null,classifyFailure:j};if(F.timer=setTimeout(()=>this.arbitrateTimeout(B,F,X.channel,W,q),q),this.pending.set(B,F),Z)this.attachCancelSignal(Z,B,X,W,$);let O=s5(this.sock,W8(H),Date.now()+q);U=O.queued,O.completed.catch((_)=>{let C=this.pending.get(B);if(C)this.rejectPending(B,C,_ instanceof Error?_:new N0(String(_)))})})}async cachedRouteHandle(X,J){let $=J.identity??this.opts.identity;if(!$)throw new z6("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=$J(J),Q=J.reverseRequests??new M9;Q.seal();let z=YZ(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 z6&&G.code==="route_closed")throw G;if(!this.closeStarted&&l2(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 N0&&OF(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=j6(u.Ping,T6(!1,t0.Interactive,!1,K6.Normal),0,0,$,new Uint8Array),Q=(async()=>{if(await H8(X,W8(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 Y9(`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 N0("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 N0("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 N0("client closed");J+=1;try{let Y=await t9.openConnection(this.opts);if(this.closeStarted)throw Y.sock.close(),new N0("client closed");this.replaceConnection(Y),await this.reopenCachedRoutes();return}catch(Y){if(!l2(Y)||J>=this.opts.reconnectBackoff.maxAttempts){if(Y instanceof R6&&J>1)throw new R6(`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 N0("subc connection replaced")),this.sock.close(),this.sock=X.sock,this.currentConn=X.conn,this.closedErr=null,this.generation+=1,this.connectionToken=n1(),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(PF(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 z6("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:DF},()=>{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 N0(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 $=c2(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 N0("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)ez("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 $=_F(X.body),Y=$?.split("/",1)[0],G=Y?tz(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)ez("failed to answer reverse request: %s",r4(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=j6($,T6(!1,t0.Interactive,!1),J.channel,J.epoch,X.header.corr,Y);await H8(G,W8(z),Date.now()+s1)}errorFromFrame(X){try{let J=JSON.parse(Buffer.from(X.body).toString("utf8")),$=new N0(J.message??"subc error",J.code,J.detail);return $Z.set($,X.header.flags),$}catch{return new N0(Buffer.from(X.body).toString("utf8")||"subc error")}}evictRouteHandle(X){for(let J of this.routes.values())if(J.handle&&p2(J.handle,X))J.handle=null}failHandle(X,J){for(let[$,Y]of this.pending)if(Y.handle&&p2(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 z6("not_sent",`${X}${r4(J)}`,d2(J),J)}outcomeUnknownCallError(X,J){return new z6("outcome_unknown",`${X}${r4(J)}`,d2(J),J)}terminalCallError(X,J){if(J instanceof z6)return J;return new z6("terminal",`${X}${r4(J)}`,d2(J),J)}notSentRecoveryError(X,J){if(J instanceof z6)return J;if(l2(J))return this.notSentCallError(X,J);return this.terminalCallError(X,J)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute(X,J,$=new M9){let Y=u2(X,J,this.connectionToken,$);return this.liveRoutes.set(X,Y),Y}isLiveHandle(X){return o4(X,this.connectionToken)&&this.liveRoutes.get(X.channel)===X}assertLiveConnection(X){if(!o4(X,this.connectionToken))throw new G9(X)}assertLiveHandle(X){if(!this.isLiveHandle(X))throw new G9(X)}allocateCorr(){let X=0xffffffffffffffffn;if(this.nextCorr>X){let $=new N0("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 N0("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 i5(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 l2(X){if(X instanceof Y9||X instanceof B8)return!0;if(X instanceof E8||X instanceof O9)return!0;if(X instanceof z6)return X.kind==="not_sent"||X.kind==="outcome_unknown";if(X instanceof R6)return!0;if(X instanceof N0||X instanceof Q6)return!1;let J=d2(X);return J==="ECONNREFUSED"||J==="ECONNRESET"||J==="EPIPE"||J==="ETIMEDOUT"||J==="ENOENT"}function PF(X){return X instanceof N0&&typeof X.code==="string"}function OF(X){if(X==="capability_forbidden")return!1;return X==="module_reloading"||X==="module_warming"||X==="target_unavailable"||X==="module_timeout"}var GZ="unknown_channel",QZ="stale_route_epoch";function a2(X,J){return J===GZ||J===QZ}function MF(X){return{connectionFile:X.connectionFile,handshakeTimeoutMs:X.handshakeTimeoutMs,identity:X.identity,targetKind:X.targetKind??FF,reconnectBackoff:X.reconnectBackoff??s2,sleep:X.sleep??((J)=>new Promise(($)=>setTimeout($,J))),routeOpenRetryDeadlineMs:X.routeOpenRetryDeadlineMs??LF,timeoutArbitrationGraceMs:X.timeoutArbitrationGraceMs??NF,livenessProbeWindowMs:X.livenessProbeWindowMs??qF,onControlPush:X.onControlPush}}function zZ(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 YZ(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 $J(X={}){if(X.consumerIdentity!==void 0)return X.consumerIdentity??void 0;let J=process.env[i2],$=process.env[n2];if(!J||!$)return;return{module_id:J,launch_nonce:$}}function d2(X){if(typeof X==="object"&&X!==null&&"code"in X){let J=X.code;if(typeof J==="string")return J}return}function r4(X){if(X===void 0)return"";return`: ${X instanceof Error?X.message:String(X)}`}function c2(X,J){return X?`${X.channel}:${X.epoch}:${J}`:`0:0:${J}`}function _F(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 WJ}from"node:buffer";var AF=1e4,TF=30000,WZ=30000,RF=250,YJ=64,zJ="health.check",BZ=1n,CF=/^[0-9a-f]{32}$/;function ZJ(X){let J=X.machine_id;return typeof J==="string"&&CF.test(J)?J:void 0}class r2{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 t4{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=n1();nextCorr=1n;ingressEpochDropCount=0;requestGate=new r2(YJ);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=ZJ(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=o2(X,Y),Q=$.timeoutMs??WZ,z=j6(u.Request,T6(!1,$.priority??t0.Interactive,!1,$.admissionClass??K6.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,j6(u.Push,T6(!1,$.priority??t0.Interactive,!1,$.admissionClass??K6.Normal),X.channel,X.epoch,0n,J))}cancel(X,J){this.assertLiveHandle(X),this.sendOn(this.sock,this.generation,j6(u.Cancel,S8(),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,j6(u.Goodbye,S8(),X.channel,X.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect(X){if(X.manifest.protocol_ver!==m6)throw new w0(`manifest protocol_ver ${X.manifest.protocol_ver} does not match client protocol ${m6}`,"invalid_manifest");let J=SF(X),$=await t4.openConnection(J);return new t4($.sock,$.conn,J,$.ack)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let X=this.sock;try{await QJ(X,j6(u.Goodbye,S8(),0,0,0n,new Uint8Array(0)))}catch{}finally{X.close(),this.finishClosed()}}await this.closed}static async openConnection(X,J){let $=await i1(X.connectionFile),Y=Date.now()+(X.handshakeTimeoutMs??AF),G=$.endpoints[0],Q=await r9.connect(G.host,G.port,Y);try{J?.(Q),await a4(Q,$,Y),await QJ(Q,bF(X));let z=await vF(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:TF});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=o2(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(EF(X)),!0}}switch(X.header.ty){case u.Ping:if(X.header.channel===0)await this.sendOn(J,$,C8(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(o2(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 G9(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=e2(X.body);if(Y.op===zJ){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=ZZ(Y.route_channel,"route_channel"),Q=ZZ(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}`,S8(),J,$);return}this.liveRoutes.delete(z.channel),this.abortHandle(z),await this.reportRouteGone(z)}let Z=u2(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),S8(),J,$)}finally{await this.reportRouteGone(Z)}return}let H=yF(B);if(H){try{await this.sendError(X,H.code,H.message,S8(),J,$)}finally{await this.reportRouteGone(Z)}return}try{await this.sendOn(J,$,C8(X.header.ver,u.Response,S8(),0,0,X.header.corr,t2({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=o2(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,C8(Q,u.StreamData,T6(!1,j.priority??t0.Interactive,!1,j.admissionClass??K6.Normal),J.channel,J.epoch,G,U))}},B=await(this.requestGate??new r2(YJ)).acquire(),H=T6(!1,t0.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,C8(Q,u.StreamEnd,H,J.channel,J.epoch,G,new Uint8Array(0)));else if(U instanceof Uint8Array)await this.sendOn($,Y,C8(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 G9)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 r2(YJ)).acquire();try{if(z.signal.aborted)return;let W=await this.opts.health();await this.sendOn(J,$,C8(G,u.Response,S8(),0,0,Y,t2({op:zJ,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),S8(),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,C8(X.header.ver,u.Error,Y,X.header.channel,X.header.epoch,X.header.corr,t2({code:J,message:$})))}async sendOn(X,J,$){if(this.sock!==X||this.generation!==J||this.closeStarted||this.closedErr)return;await QJ(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 t4.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(!kF(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=ZJ(X.ack),this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=n1(),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 wF();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 o4(X,this.connectionToken)&&this.liveRoutes.get(X.channel)===X}assertLiveHandle(X){if(!this.isLiveHandle(X))throw new G9(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 o2(X,J){return`${X.channel}:${X.epoch}:${J}`}function EF(X){try{let J=e2(X.body);return new w0(J.message??"subc error",J.code,a2(X.header.flags,J.code)?"not_sent":"terminal",J.detail)}catch{return new w0(WJ.from(X.body).toString("utf8")||"subc error")}}function GJ(X){return X&&X.length>0?X:void 0}function SF(X){let J=GJ(process.env[i2]),$=GJ(process.env[n2]),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??s2,sleep:X.sleep??((G)=>new Promise((Q)=>setTimeout(Q,G))),restoredDebounceMs:X.restoredDebounceMs??RF,onConnectionState:X.onConnectionState,launchNonce:GJ(X.launchNonce??$),reconnectOnDrop:X.reconnectOnDrop??!Y}}function IF(X){if(X===null)return null;let J=new Set(X??[]);return J.add(zJ),[...J]}function bF(X){let J=X.launchNonce;return j6(u.Hello,S8(),0,0,BZ,t2({manifest:hF(X.manifest),protocol_ver:m6,control_ops:IF(X.controlOps),...J?{launch_nonce:J}:{}}))}function kF(X){if(X instanceof w0)return X.code==="duplicate_module_id";if(X instanceof Y9||X instanceof B8)return!0;if(X instanceof E8||X instanceof O9)return!0;if(X instanceof R6)return!0;if(X instanceof Q6)return!1;let J=xF(X);return J==="ECONNREFUSED"||J==="ECONNRESET"||J==="EPIPE"||J==="ETIMEDOUT"||J==="ENOENT"}function xF(X){if(typeof X==="object"&&X!==null&&"code"in X){let J=X.code;if(typeof J==="string")return J}return}async function wF(){await new Promise((X)=>setTimeout(X,0))}function S8(){return T6(!1,t0.Passive,!1)}async function QJ(X,J){await H8(X,W8(J),Date.now()+WZ)}async function vF(X,J){let $=await X.readFrame(J,J);switch($.header.ty){case u.HelloAck:{let Y=e2($.body);if(Y.negotiated_ver!==m6)throw new w0(`subc negotiated protocol ${Y.negotiated_ver}; expected exactly ${m6}`,"unsupported_version");return Y}case u.Error:{let Y=e2($.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 t2(X){return new Uint8Array(WJ.from(JSON.stringify(X),"utf8"))}function e2(X){return JSON.parse(WJ.from(X).toString("utf8"))}function ZZ(X,J){if(typeof X!=="number"||!Number.isInteger(X))throw new w0(`route.bind ${J} must be an integer`);return X}function yF(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 hF(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(fF),consumes:X.consumes.map(gF),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 fF(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 gF(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 J7="subc-connection.json",VZ="subc-",UZ=".connection.json";function KZ(){let X=process.env.HOME;return X?a1(X,".local","share","cortexkit","run",J7):void 0}function cF(){let X=process.env.XDG_RUNTIME_DIR;if(X)return a1(X,J7);let J=KZ();if(J)return J;return a1(pF().homedir,".local","share","cortexkit","run",J7)}function lF(){if(process.env.SUBC_CONNECTION_FILE)return process.env.SUBC_CONNECTION_FILE;let X=process.env.XDG_RUNTIME_DIR;if(X){let G=a1(X,J7);if(X7(G))return G}let J=KZ();if(J&&X7(J))return J;let $=a1(HZ(),`${VZ}${dF()}${UZ}`);if(X7($))return $;let Y=iF(HZ());return Y.length===1?Y[0]:void 0}function dF(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 jZ(){return lF()??cF()}function e9(X){return X?.trim()||process.env.SUBC_CONNECTION_FILE||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||jZ()}function X7(X){try{return uF(X).isFile()}catch{return!1}}function iF(X){let J;try{J=mF(X)}catch{return[]}let $=[];for(let Y of J){if(typeof Y!=="string")continue;if(!Y.startsWith(VZ)||!Y.endsWith(UZ))continue;let G=a1(X,Y);if(X7(G))$.push(G)}return $.sort(),$}import{createHash as nF}from"node:crypto";import{existsSync as sF,realpathSync as NZ}from"node:fs";import{dirname as aF,relative as oF,resolve as rF}from"node:path";function qZ(X){let J=X,$;try{$=NZ(J)}catch(Y){if(Y.code!=="ENOENT")throw Y;let G=J;while(!sF(G)){let Q=aF(G);if(Q===G)break;G=Q}$=rF(NZ(G),oF(G,J))}return nF("sha256").update($).digest("hex")}function BJ(X,J){return{project_root:X,harness:"opencode",session:`store-${qZ(J)}`}}import{AsyncLocalStorage as tF}from"node:async_hooks";import{readFile as LZ}from"node:fs/promises";var eF=new tF;function DZ(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 $7(X,J=eF.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 $=DZ(new TextDecoder("utf-8",{fatal:!0}).decode(await LZ(J.passwdPath)),7),Y=DZ(new TextDecoder("utf-8",{fatal:!0}).decode(await LZ(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 XP}from"node:crypto";import{chmod as JP,mkdir as $P,open as YP,realpath as GP,rename as QP,stat as zP,unlink as ZP}from"node:fs/promises";import{basename as WP,dirname as FZ,join as BP}from"node:path";var HP=/^[0-9a-f]{64}$/;function VP(X){if(!HP.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 UP(X){let J;try{J=await GP(X)}catch{return}for(;;){let $=await zP(J).catch(()=>{return});if($&&!await $7($))throw Error(`enrollment token ancestor ${J} is group- or world-writable without sticky bit`);let Y=FZ(J);if(Y===J)return;J=Y}}async function HJ(X,J){VP(J);let $=FZ(X);await $P($,{recursive:!0,mode:448}),await UP($);let Y=BP($,`.${WP(X)}.${process.pid}.${XP(12).toString("hex")}.tmp`),G=!1;try{let Q=await YP(Y,"wx",384);G=!0;try{await Q.writeFile(`${JSON.stringify(J)}
89
+ `,"utf8"),await Q.sync(),await JP(Y,384)}finally{await Q.close()}await QP(Y,X),G=!1}finally{if(G)await ZP(Y).catch(()=>{return})}}var PZ=["transient","permanent","auth_required","context_overflow"];class V8 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 o1(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function OZ(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=o1(X)&&o1(X.result)?X.result:void 0,G=Y&&o1(Y.error)?Y.error:void 0,Q=G?.class,z=G?.code,Z=typeof Q==="string"&&PZ.includes(Q),W=typeof z==="string",H=Z&&W?Q:"transient";if(typeof Q!=="string")$("unknown");else if(!Z)$(Q);return new V8(W?z:J,H,OZ(H))}function X1(X){return o1(X)&&o1(X.result)&&o1(X.result.error)}var MZ="claustrum",NP=60000;function u6(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function UJ(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=0?X:void 0}function I8(X){return X===void 0||typeof X==="string"}function _Z(X,J){if(X1(X))throw O0(X,"invalid_response",J);let $=u6(X)&&u6(X.result)?X.result:void 0,Y=$?.payload;if(!Array.isArray(Y)||Y.length===0||!Y.every((N)=>typeof N==="number"&&Number.isInteger(N)&&N>=0&&N<=255))throw O0(X,"invalid_response",J);let G=UJ($?.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(!I8(Z)||!I8(W)||!I8(B)||!I8(H)||!I8(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 qP(X,J){if(X1(X))throw O0(X,"invalid_response",J);let $=u6(X)&&u6(X.result)?X.result:void 0,Y=$?.record_version,G=Y===void 0?void 0:UJ(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||!I8(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 J1{#X;#J;#W;#Q;#z;#Y;#$=null;#B=0;#H=!1;constructor(X,J,$,Y,G,Q){this.#X=X,this.#J=J,this.#W=$,this.#Q=Y,this.#z=G,this.#Y=Q}static async connect(X={}){let J=e9(X.connectionFile),$=X.connector??((Q)=>t9.connect(Q)),Y=X.identity??BJ(X.projectRoot??process.cwd(),X.storagePath??process.cwd()),G=await $({connectionFile:J,handshakeTimeoutMs:X.handshakeTimeoutMs});return new J1(G,$,J,X.handshakeTimeoutMs,Y,X.logger??((Q)=>console.warn(Q)))}async getCredential(X,J){let $=await this.#G("credential.get",{handle:X,min_ttl_ms:J,force_refresh:!1});return _Z($,this.#Y)}async statusCredential(X){let J=await this.#G("credential.status",{handle:X});return qP(J,this.#Y)}async reportAuthFailure(X){let J=await this.#G("credential.report_auth_failure",{handle:X.handle,provider_status:X.providerStatus,record_version:X.recordVersion,reporter_source:X.reporterSource});if(X1(J))throw O0(J,"invalid_response",this.#Y);if((u6(J)&&u6(J.result)?J.result:void 0)?.accepted!==!0)throw O0(J,"invalid_response",this.#Y)}async listScoped(X){let J=await this.#G("credential.list_scoped",X===void 0?{}:{enrollment_token:X});return LP(J,this.#Y)}async getScoped(X){let J=await this.#G("credential.get_scoped",{credential_id:X.credentialId,enrollment_token:X.enrollmentToken,min_ttl_ms:X.minTtlMs});return _Z(J,this.#Y)}async reportAuthFailureScoped(X){let J=await this.#G("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(X1(J))throw O0(J,"invalid_response",this.#Y);if((u6(J)&&u6(J.result)?J.result:void 0)?.accepted!==!0)throw O0(J,"invalid_response",this.#Y)}async enrollPropose(X){let J=await this.#G("auth.enroll_propose",{proposed_name:X.name,request_secret_hash:X.requestSecretHash}),Y=VJ(J,this.#Y).request_id;if(typeof Y!=="string"||Y.length===0)throw O0(J,"invalid_response",this.#Y);return{requestId:Y}}async enrollPoll(X){let J=await this.#G("auth.enroll_poll",{request_id:X.requestId,request_secret:X.requestSecret});return DP(J,this.#Y)}async enrollRotate(X){let J=await this.#G("auth.enroll_rotate",{token:X.token,expected_token_generation:X.expectedTokenGeneration}),$=VJ(J,this.#Y),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.#Y);return{token:Y,tokenGeneration:G}}close(){this.#H=!0,this.#X.close()}async#G(X,J){let $=this.#X;try{return await $.call(MZ,X,J,{identity:this.#z,consumerIdentity:null})}catch(Y){if(this.#V(Y)){try{if(this.#X===$)await this.#U()}catch(G){throw this.#Z(G)}try{return await this.#X.call(MZ,X,J,{identity:this.#z,consumerIdentity:null})}catch(G){throw this.#Z(G)}}throw this.#Z(Y)}}#Z(X){if(X instanceof V8)return X;let J=X instanceof z6&&X.code?X.code:"transport_error";return new V8(J,"transient","retry")}#V(X){return!this.#H&&X instanceof z6&&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.#$){await this.#$;return}let X=Date.now();if(X<this.#B)throw Error("Claustrum client reconnect is backed off");this.#B=X+NP,this.#$=this.#J({connectionFile:this.#W,handshakeTimeoutMs:this.#Q}).then((J)=>{if(this.#H)throw J.close(),Error("Claustrum client is closed");let $=this.#X;this.#X=J,$.close()}).finally(()=>{this.#$=null}),await this.#$}}function LP(X,J){if(X1(X))throw O0(X,"invalid_response",J);let $=u6(X)&&u6(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(!u6(z))throw O0(X,"invalid_response",J);let Z=UJ(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(!I8(z.refresh_adapter))throw O0(X,"invalid_response",J);if(!I8(z.account_id)||!I8(z.email)||!I8(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 VJ(X,J){if(X1(X))throw O0(X,"invalid_response",J);let $=u6(X)&&u6(X.result)?X.result:void 0;if($===void 0)throw O0(X,"invalid_response",J);return $}function DP(X,J){let $=VJ(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 e4(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 FP,randomBytes as PP,randomUUID as OP}from"node:crypto";import{constants as AZ}from"node:fs";import{chmod as MP,mkdir as _P,open as SZ,readFile as TZ,realpath as AP,rename as TP,stat as IZ,unlink as bZ}from"node:fs/promises";import{basename as kZ,dirname as Y1,extname as RZ,isAbsolute as CZ,join as NJ,resolve as RP}from"node:path";class $0 extends Error{kind;constructor(X,J){super(J);this.name="ClaustrumConsumerError",this.kind=X}}var CP=1,KJ=16384,xZ=30000,qJ=/^[0-9a-f]{64}$/,wZ=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),vZ=new Set(["pending_queue_full"]);function jJ(X){if(!(X instanceof V8))return;if(wZ.has(X.code))return{code:X.code,disposition:"terminal"};if(vZ.has(X.code))return{code:X.code,disposition:"retry"};return{code:X.code,disposition:X.action==="retry"?"retry":"terminal"}}function LJ(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 DJ(X){return J1.connect(X)}function yZ(X){let J=RZ(X)||".json",$=kZ(X,RZ(X));return{statePath:NJ(Y1(X),`${$}-state${J}`),tokenPath:X}}function FJ(X){let J=X.override?.trim();if(J&&!CZ(J)&&!X.cwd)throw new $0("invalid-state","A relative Claustrum enrollment override needs a base directory");let $=J?CZ(J)?J:RP(X.cwd,J):NJ(X.stateDir,`${X.host}-enrollment.json`);return yZ($)}function hZ(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function Y7(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=0}function fZ(X){return typeof X==="number"&&Number.isSafeInteger(X)&&X>=1}function X3(){return new $0("invalid-state","invalid Claustrum enrollment state")}function Q7(X){if(!hZ(X)||X.version!==CP||typeof X.proposedName!=="string"||X.proposedName.length===0)throw X3();if(X.phase==="pending"){if(!qJ.test(String(X.requestSecret??""))||X.requestId!==void 0&&(typeof X.requestId!=="string"||X.requestId.length===0)||!Y7(X.createdAt)||!Y7(X.updatedAt))throw X3();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)||!fZ(X.tokenGeneration)||!Y7(X.updatedAt))throw X3();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"||!Y7(X.updatedAt))throw X3();return{version:1,phase:X.phase,proposedName:X.proposedName,...X.errorCode!==void 0&&{errorCode:X.errorCode},updatedAt:X.updatedAt}}throw X3()}function PJ(X){if(!hZ(X)||!qJ.test(String(X.token??""))||!fZ(X.token_generation))throw new $0("invalid-token","invalid Claustrum enrollment token file");return{token:X.token,token_generation:X.token_generation}}function EP(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 SP(X){try{return JSON.parse(X)}catch{throw new $0("invalid-state","Claustrum enrollment file is not valid JSON")}}async function A9(X){let J;try{J=await SZ(X,AZ.O_RDONLY|AZ.O_NOFOLLOW)}catch($){if($.code==="ENOENT")return;throw new $0("unsafe-file","Claustrum enrollment file could not be opened safely")}try{EP(await J.stat());let $=Buffer.alloc(KJ+1),{bytesRead:Y}=await J.read($,0,$.byteLength,0);if(Y>KJ)throw new $0("unsafe-file","Claustrum enrollment file is too large");return SP($.subarray(0,Y).toString("utf8"))}finally{await J.close()}}function EZ(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 IP(X,J,$){try{let[Y,G]=await Promise.all([TZ($.passwdPath??"/etc/passwd","utf8"),TZ($.groupPath??"/etc/group","utf8")]),Q=EZ(Y,7),z=EZ(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 gZ(X,J={}){let $=process.geteuid?.();if($===void 0)return;let Y=process.getegid?.(),G;try{G=await AP(X)}catch{return}let Q;for(;;){let z=await IZ(G).catch(()=>{return});if(z&&(z.mode&18)!==0&&(z.mode&512)===0){if(Q===void 0)Q=Y!==void 0&&await IP($,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=Y1(G);if(Z===G)return;G=Z}}async function G7(X){await _P(X,{recursive:!0,mode:448});let J=await IZ(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 MP(X,448)}async function $1(X,J,$={}){let Y=Y1(X);await G7(Y),await gZ(Y,$);let G=`${JSON.stringify(J)}
91
+ `;if(Buffer.byteLength(G)>KJ)throw new $0("invalid-state","Claustrum enrollment state is too large");let Q=NJ(Y,`.${kZ(X)}.${process.pid}.${OP()}.tmp`),z,Z=!1;try{z=await SZ(Q,"wx",384),Z=!0,await z.writeFile(G,"utf8"),await z.chmod(384),await z.sync(),await z.close(),z=void 0,await TP(Q,X),Z=!1}finally{if(await z?.close().catch(()=>{}),Z)await bZ(Q).catch(()=>{})}}async function J3(X,J){let $=await A9(X.tokenPath),Y=$===void 0?void 0:PJ($),G=await A9(X.statePath),Q=G===void 0?void 0:Q7(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 _9(Q)}async function $3(X,J){let $;try{$=await J3(X,J)}catch(Y){if(!(Y instanceof $0)||Y.kind!=="invalid-state"&&Y.kind!=="invalid-token")return"unreadable";try{let G=await A9(X.statePath);if(G===void 0)return"unreadable";let Q=Q7(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 OJ(X){let J=await A9(X);if(J===void 0)throw new $0("not-enrolled","Claustrum enrollment is not configured");return PJ(J)}function _9(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 mZ(){return new $0("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class z7{#X;#J;#W;#Q;#z;#Y;#$;constructor(X){this.#$=X.ancestorOptions??{},this.#X=X.client,this.#J=X.paths,this.#W=X.proposedName,this.#Q=X.now??Date.now,this.#z=X.mintSecret??(()=>PP(32).toString("hex")),this.#Y=X.writeTokenFile??HJ}async status(){return J3(this.#J,this.#W)}async resetTerminal(){return uZ(this.#J,this.#W)}async#B(X,J){let $={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:J,updatedAt:this.#Q()};return await $1(this.#J.statePath,$,this.#$),_9($)}async reconcile(){await G7(Y1(this.#J.statePath));let X=await g0({name:"ceremony",path:this.#J.statePath,ttlMs:xZ,renew:!0});if(!X)return{state:"busy"};try{let J=await A9(this.#J.tokenPath),$=J===void 0?void 0:PJ(J),Y=await A9(this.#J.statePath),G=Y===void 0?void 0:Q7(Y);if(G&&G.proposedName!==this.#W)throw mZ();if($){if(!G||G.phase==="pending"){let z={version:1,phase:"approved",proposedName:G?.proposedName??this.#W,tokenGeneration:$.token_generation,updatedAt:this.#Q()};await $1(this.#J.statePath,z,this.#$),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.#Q()};return await $1(this.#J.statePath,z,this.#$),_9(z)}if(G&&G.phase!=="pending")return _9(G);if(!G){let z=this.#Q();if(G={version:1,phase:"pending",proposedName:this.#W,requestSecret:this.#z(),createdAt:z,updatedAt:z},!qJ.test(G.requestSecret))throw new $0("invalid-state","invalid minted Claustrum enrollment secret");await $1(this.#J.statePath,G,this.#$)}if(!G.requestId)try{let z=FP("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.#Q()},await $1(this.#J.statePath,G,this.#$)}catch(z){let Z=jJ(z);if(!Z)throw z;if(Z.disposition==="retry")return{state:"pending",proposedName:G.proposedName,retryCode:Z.code};return this.#B(G,Z.code)}let Q=G.requestId;if(!Q)return _9(G);try{let z=await this.#X.enrollPoll({requestId:Q,requestSecret:G.requestSecret});if(z.status==="pending")return _9(G);if(z.status==="denied"){let W={version:1,phase:"denied",proposedName:G.proposedName,updatedAt:this.#Q()};return await $1(this.#J.statePath,W,this.#$),_9(W)}await G7(Y1(this.#J.tokenPath)),await gZ(Y1(this.#J.tokenPath),this.#$),await this.#Y(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.#Q()};return await $1(this.#J.statePath,Z,this.#$),_9(Z)}catch(z){let Z=jJ(z);if(!Z)throw z;if(Z.disposition==="retry")return{state:"pending",proposedName:G.proposedName,requestId:Q,retryCode:Z.code};return this.#B(G,Z.code)}}finally{await X.release()}}}async function uZ(X,J){await G7(Y1(X.statePath));let $=await g0({name:"ceremony",path:X.statePath,ttlMs:xZ,renew:!0});if(!$)return"busy";try{if(await A9(X.tokenPath)!==void 0)return"refused-approved";let Y=await A9(X.statePath);if(Y===void 0)return"idle";let G=Q7(Y);if(G.proposedName!==J)throw mZ();if(G.phase==="pending")return"refused-pending";return await $.assertOwned(),await bZ(X.statePath),"reset"}finally{await $.release()}}var Y3="claustrum-tombstone:v1:";function Z7(X){return`${Y3}${X}`}function MJ(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function W7(X){return typeof X==="string"&&X.startsWith(Y3)}function pZ(X,J){if(!MJ(X)||X.type!=="oauth")return!1;return X.refresh===Z7(J)}function cZ(X,J){if(pZ(X,J))return"placeholder";if(MJ(X)&&X.type==="oauth"&&typeof X.refresh==="string"&&X.refresh.length>0&&!W7(X.refresh))return"login";if(MJ(X)&&X.type==="api"&&typeof X.key==="string"&&X.key.length>0)return"login";return"empty"}function _J(X){let J=cZ(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 lZ(X,J){return J!==void 0&&J.credentialId===X.credentialId&&J.accountIdentity===X.accountIdentity&&J.recordVersion!==X.recordVersion}function bP(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 dZ=Z0("claustrum");function RJ(X,J,$,Y=dZ){let G=lZ(J,$);return Y.debug("scoped 401 re-authorized",{site:X,credentialId:J.credentialId,servedVersion:J.recordVersion,currentVersion:$?.recordVersion??null,retry:G,reason:bP(J,$)}),G}var TJ=300000;function AJ(){return new $0("invalid-material","Claustrum returned invalid credential material")}function kP(X){let J=X.trim();if(J.startsWith("{")){let $;try{$=JSON.parse(J)}catch{throw AJ()}if(!$||typeof $!=="object")throw AJ();let Y=$,G=Y.access_token??Y.access;J=typeof G==="string"?G:""}if(!/^[\x21-\x7e]+$/.test(J)||J.startsWith(Y3))throw AJ();return J}function xP(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 B7{#X;#J;#W;#Q;#z;#Y;#$;#B=new WeakMap;#H=new WeakMap;#G=!1;constructor(X){let J=X.tokenPath;if(X.readToken)this.#J=X.readToken;else if(J)this.#J=()=>OJ(J);else throw new $0("not-enrolled","Claustrum enrollment token path is required");this.#X=X.client,this.#Q=X.family,this.#z=X.parseIdentity,this.#Y=X.requireAssertion??!1,this.#W=X.now??Date.now,this.#$=X.logger??dZ}#Z(X){if(this.#G)throw new $0("closed","Claustrum scoped custody is closed");X?.throwIfAborted()}async#V(X){this.#Z(X);let J=await this.#J();if(this.#Z(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.#Z(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.#Z(J),G instanceof V8)throw G;throw new $0("unavailable","Claustrum scoped operation unavailable")}finally{Y?.()}return this.#Z(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=xP(Z,this.#Q);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.#$.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.#Y&&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:TJ}}),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.#W()<TJ))throw new $0("insufficient-validity","Claustrum served credential has insufficient validity");let W=kP(z.material),B=z.accountId?.trim()?z.accountId:void 0;if(this.#Y&&(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.#z?.(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.#B.set(K,Q),K}async reportFailure(X,J,$){if(J!==401)return;this.#Z();let Y=this.#B.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.#$.debug("scoped 401 reported",{credentialId:X.credentialId,recordVersion:X.recordVersion,reporterSource:$})}catch(z){throw this.#H.delete(X),z}}close(){if(this.#G)return;this.#G=!0,this.#X.close()}}import{createHash as wP}from"node:crypto";import{readFile as vP}from"node:fs/promises";function iZ(X,J,$){if(X.accountIdentity!==void 0&&$!==void 0)return X.accountIdentity===$;return X.credentialId===J}function CJ(X,J,$){return X.some((Y)=>iZ(Y,J,$))}function EJ(X,J,$){let Y={credentialId:J,...$!==void 0&&{accountIdentity:$}};return[...X.filter((G)=>G.credentialId!==J||G.accountIdentity!==$),Y]}function SJ(X,J,$){return X.filter((Y)=>!J.some((G)=>iZ(Y,G,$)))}var aZ="vault:";function yP(X){return wP("sha256").update(X).digest("hex")}function hP(X){let J=X.credentialId.split(":");return(J.length>=3?J.slice(2).join(":").trim():void 0)||X.email||X.credentialId}function fP(X){return X.identity!==void 0?`identity:${X.identity}`:`credential:${X.credential.credentialId}`}function T9(X){return[X.credentialId,...X.aliases??[]]}function oZ(X,J,$={}){let Y=$.now??Date.now(),G=$.routePrefix??aZ,Q=$.reservedRouteIds??new Set,z=X?.rows??[],Z=[...X?.declined??[]],W=J.skipped.length===0,B=new Set(J.credentials.map((L)=>L.credentialId)),H=new Set(J.skipped.flatMap((L)=>L.credentialId===void 0?[]:[L.credentialId])),U=J.skipped.some((L)=>L.credentialId===void 0),j=(L)=>!B.has(L)&&(H.has(L)||U),N=new Map;for(let L of z){if(L.accountIdentity===void 0)continue;for(let P of T9(L))if(!N.has(P))N.set(P,L.accountIdentity)}let K=new Map;for(let L of J.credentials){let P=L.accountIdentity!==void 0?{credential:L,identity:L.accountIdentity,claimed:!0}:{credential:L,identity:N.get(L.credentialId),claimed:!1},A=fP(P),T=K.get(A)??[];T.push(P),K.set(A,T)}let q=new Set,F=new Set(Q),O=[],_=(L,P)=>L.credential.credentialId.localeCompare(P.credential.credentialId),C=[...K.values()].map((L)=>L.toSorted(_)).sort((L,P)=>L[0]&&P[0]?_(L[0],P[0]):0);for(let L of C){let P=L[0]?.identity,A=L.filter((r)=>r.credential.state==="active"),T=A.length?A:L,k=T.filter((r)=>r.claimed),p=k.length?k:T,i=new Set(L.map((r)=>r.credential.credentialId)),X0=z.find((r)=>!q.has(r)&&T9(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)=>!q.has(r)&&r.accountIdentity===P));if(G0)q.add(G0);let L0=G0?.routeId;if(!L0||Q.has(L0)){let r=`${G}${J0.credentialId}${P===void 0?"":`~${yP(P).slice(0,10)}`}`;L0=r;for(let a=2;F.has(L0);a++)L0=`${r}~${a}`}F.add(L0);let m=G0?T9(G0).filter(j):[],c0=[...new Set([...L.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()||hP(J0),...J0.email!==void 0&&{email:J0.email},...J0.orgName!==void 0&&{orgName:J0.orgName},enabled:![J0.credentialId,...c0].some((r)=>CJ(Z,r,P)),addedAt:G0?.addedAt??Y,...G0?.quota!==void 0&&{quota:G0.quota},...!w.claimed&&P!==void 0&&{unclaimed:!0}}})}return z.forEach((L,P)=>{if(q.has(L)||!T9(L).some(j))return;if(F.has(L.routeId))return;let[A,...T]=T9(L).filter((i)=>!B.has(i));if(A===void 0)return;F.add(L.routeId);let{aliases:k,...p}=L;O.push({previousIndex:P,row:{...p,credentialId:A,...T.length&&{aliases:T},stale:!0}})}),O.sort((L,P)=>L.previousIndex===P.previousIndex?L.row.credentialId.localeCompare(P.row.credentialId):L.previousIndex-P.previousIndex),{version:1,view:J.view,complete:W,...!W&&{rejected:J.skipped.map((L)=>({...L.credentialId!==void 0&&{credentialId:L.credentialId},reason:L.reason}))},rows:O.map((L)=>L.row),declined:Z}}function IJ(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 H7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function r1(X){return X===void 0||typeof X==="string"}function gP(X){if(!H7(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"||!r1(X.accountIdentity)||!r1(X.email)||!r1(X.orgName)||X.aliases!==void 0&&(!Array.isArray(X.aliases)||!X.aliases.every((J)=>typeof J==="string"))||X.quota!==void 0&&!G6(X.quota)||X.stale!==void 0&&X.stale!==!0||X.unclaimed!==void 0&&X.unclaimed!==!0)return;return X}var mP=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function nZ(X){if(!Array.isArray(X))return;let J=[];for(let $ of X){if(!H7($)||!r1($.credentialId)||typeof $.reason!=="string"||!mP.has($.reason))return;J.push($)}return J}function uP(X){if(!H7(X)||X.version!==1||!r1(X.view)||!Array.isArray(X.rows)||!Array.isArray(X.declined)||X.complete!==void 0&&typeof X.complete!=="boolean"||X.rejected!==void 0&&!nZ(X.rejected))throw new $0("invalid-state","Claustrum roster file is not valid");let J=[];for(let G of X.rows){let Q=gP(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(!H7(G)||typeof G.credentialId!=="string"||!r1(G.accountIdentity))throw new $0("invalid-state","Claustrum roster file is not valid");$.push(G)}let Y=nZ(X.rejected);return{version:1,...typeof X.view==="string"&&{view:X.view},complete:X.complete!==!1,...Y&&{rejected:Y},rows:J,declined:$}}async function R9(X){let J;try{J=await vP(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 uP($)}var pP={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},cP={name:"claustrum-roster",ttlMs:30000};async function G3(X,J,$={}){return sZ(X,pP,async(Y)=>{let G=await R9(X),{next:Q,result:z}=await J(G,{assertOwned:()=>Y.assertOwned()});if(Q)await Y.assertOwned(),await M6(X,Q,{beforeRename:async()=>{await $.beforePublish?.(),await Y.assertOwned()}});return z})}function bJ(X,J){return G3(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=EJ($.declined,Y.credentialId,Y.accountIdentity);return{next:{...$,declined:G,rows:$.rows.map((Q)=>Q===Y?{...Q,enabled:!1}:Q)},result:void 0}})}function kJ(X,J){return G3(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:SJ($.declined,T9(Y),Y.accountIdentity),rows:$.rows.map((G)=>G===Y?{...G,enabled:!0}:G)},result:void 0}})}function lP(X,J){if(!T9(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")&&T9(X).length===1)return"bind";return"refuse"}function xJ(X,J){return G3(X,($)=>{let Y=$?.rows.find((Z)=>Z.routeId===J.routeId),G=!$||!Y?"refuse":lP(Y,J);if(!$||!Y||G==="refuse")return{result:!1};let Q=V7(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 wJ(X){X.signal?.throwIfAborted();let J=async()=>await X.isActive?.()??!0;if(!await J())return;let $=await g0({...cP,path:X.path,renew:!0});if(!$){let Y=await R9(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 G3(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=oZ(G,Y,Q);return{...JSON.stringify(G)!==JSON.stringify(z)&&{next:z},result:z}})}finally{await $.release()}}class U7{#X;#J=new AbortController;#W;#Q;#z;#Y;#$;#B;#H=!1;constructor(X){this.#X=X,this.#W=X.logger??Z0("claustrum")}#G(X){this.#J.signal.throwIfAborted(),X?.throwIfAborted()}async#Z(){return await this.#X.isCustodyActive?.()??!0}#V(X,J){let $=e4([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.#G(),this.#Q)return this.#Q;if(!this.#z)this.#z=this.#X.connect().then((X)=>{if(this.#J.signal.aborted)X.close(),this.#G();return this.#Q=new B7({client:X,family:this.#X.family,tokenPath:this.#X.tokenPath,parseIdentity:this.#X.parseIdentity,requireAssertion:this.#X.requireAssertion,now:this.#X.now,logger:this.#W}),this.#Q}).finally(()=>{this.#z=void 0});return this.#V(this.#z)}snapshot(){return this.#$}routingRows(){return IJ(this.#$)}refresh(){if(this.#G(),this.#Y)return this.#Y;return this.#Y=(async()=>{if(!await this.#Z()){this.#$=void 0,this.#Q?.close(),this.#Q=void 0;return}let X=await this.#U(),J=await wJ({path:this.#X.rosterPath,custody:X,isActive:()=>this.#Z(),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.#G();let $=J?.view!==this.#$?.view;if(this.#$=J,J&&$)this.#X.onRoster?.(J);return J})().finally(()=>{this.#Y=void 0}),this.#Y}start(){if(this.#H)return;this.#G(),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.#B=(this.#X.setTimeoutImpl??setTimeout)(()=>{this.#B=void 0,X()},J),this.#B.unref?.()};X()}async authorize(X,J){this.#G(J);let $=this.#$??await this.#V(this.refresh(),J);if(!$||!await this.#Z())throw new $0("not-active","Claustrum scoped custody is not active");let Y=await R9(this.#X.rosterPath);this.#G(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=e4([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.#G(),!this.#Q)throw new $0("no-receipt","Claustrum dispatch receipt has no active owner");await this.#Q.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(RJ($.site,G,z,this.#W))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.#G(),await bJ(this.#X.rosterPath,X),this.#$=await R9(this.#X.rosterPath)}async accept(X){this.#G(),await kJ(this.#X.rosterPath,X),this.#$=await R9(this.#X.rosterPath)}async recordQuota(X,J,$){this.#G();let Y=await xJ(this.#X.rosterPath,{routeId:X,observation:J,credentialId:$.credentialId,accountIdentitySource:$.accountIdentitySource,...$.accountIdentity!==void 0&&{accountIdentity:$.accountIdentity},...$.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:$.expectedAccountIdentity}});if(Y)this.#$=await R9(this.#X.rosterPath);return Y}close(){if(this.#J.signal.aborted)return;if(this.#J.abort(new $0("closed","Claustrum consumer is closed")),this.#B)(this.#X.clearTimeoutImpl??clearTimeout)(this.#B);this.#B=void 0,this.#Q?.close(),this.#$=void 0}}function rZ(X){return J1.connect(X)}var tZ=Z7("openai");function eZ(X){return W7(X)}function T0(X){if(!X||X.corrupt===!0)return!1;return eZ(X.refresh)}class G1 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 K7(X){if(eZ(X))throw new G1}var dP=Z0("quota"),vJ="primary",yJ="secondary",iP="app_EMoamEEZ73f0CkXaXp7hrann",nP="https://auth.openai.com";async function Q3(X){K7(X.refreshToken);let J=await X.fetchImpl(`${nP}/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:iP}).toString()});if(!J.ok){let G=w5(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 sP="https://chatgpt.com/backend-api/wham/usage";async function b8(X){let J=X.logger??dP,$=X.accountKey??"unknown",Y=Date.now();J.debug("wham usage fetch started",{pid:process.pid,accountId:$});try{let G=await X.fetchImpl(sP,{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=w5(G.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${G.status}`),{status:G.status,retryAfter:z})}let Q=bz(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:e0(G)}),G}}import{createHash as aP}from"node:crypto";var oP=globalThis.setTimeout,rP=5;function z3(X){let J=X?.quota?.checkIntervalMinutes??rP;return Math.max(1,J)*60000}function tP(X){return X?.quota?.enabled!==!1}function j7(X,J){if(!X?.resetsAt)return!1;let $=Date.parse(X.resetsAt);return Number.isFinite($)&&$<=J}function $W(X,J,$,Y,G){if(G!==void 0&&Number.isFinite(G)&&G>$)return G;let Q=J===vJ?X?.primary:J===yJ?X?.secondary:void 0,z=Q?.resetsAt?Date.parse(Q.resetsAt):NaN;if(Number.isFinite(z)&&z>$)return z;return $+Y}function eP(X){let J=X?.quota?.minimumRemaining||{};return{primary:J.primary??J["5h"]??15,secondary:J.secondary??J["1w"]??10}}function XW(X,J,$){if(!tP(J))return $+z3(J);let Y=eP(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 $+z3(J);G.push(Z)}if(!G.length)return $+z3(J);return Math.min(...G)+60000}function XO(X){if(!X?.quota?.mainQuota||!X.quota.mainQuotaCheckedAt)return null;return{quota:X.quota.mainQuota,checkedAt:X.quota.mainQuotaCheckedAt,tokenFingerprint:X.quota.mainQuotaToken}}function JO(X){let J=X?.quota?.refreshEveryNRequests;return typeof J==="number"&&Number.isFinite(J)&&J>0?Math.floor(J):0}function x6(X){return aP("sha256").update(X).digest("hex").slice(0,16)}class k8{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!==x6(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)!==x6(J))return this.fallbacks.delete(X),this.fallbackTokenFps.delete(X),null;return $}getAllFallbacks(){return this.fallbacks}setMain(X,J,$,Y=!1){if(!Y&&!JW(J.quota))return;if(this.mainTokenFp=x6(X),$&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)this.clearRateLimited("main");if($)this.mainQuotaAccountId=$;if(this.main=J,hJ(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&&!JW(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,x6($));else this.fallbackTokenFps.delete(X);if(hJ(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=x6(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 $=k8.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=x6(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=JO(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 $=XO(X);if(!$)return;let Y=J?x6(J):null;if(Y&&$.tokenFingerprint&&$.tokenFingerprint!==Y)return;let G={quota:$.quota,refreshAfter:XW($.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&&c1(J,this.now())?J:void 0}seedFallbacksFromAccounts(X){let J=z3(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 c1(this.mainLastApiError,this.now())}isFallbackBackedOff(X,J){if(J){if(this.fallbackErrorTokenFps.get(X)!==x6(J))return!1}return c1(this.fallbackApiErrors.get(X),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(X,J){return JSON.stringify([X,x6(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<k8.API_CALL_GAP_MS)await new Promise((G)=>{let Q=oP(G,k8.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=x6(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=x6(X),this.main={quota:G,refreshAfter:XW(G,this.storage,Q),checkedAt:Q},hJ(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:k8.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+z3(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(k8.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(k8.isAuthError(X))return;this.mainLastApiError=i4({error:X,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(X,J,$){if(k8.isAuthError($))return;let Y=x6(J),G=this.fallbackErrorTokenFps.get(X)===Y?this.fallbackApiErrors.get(X):void 0;this.fallbackApiErrors.set(X,i4({error:$,now:this.now(),previous:G})),this.fallbackErrorTokenFps.set(X,Y)}}function JW(X){return Boolean(X.primary||X.secondary)}function hJ(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 qO}from"node:fs/promises";var Q1=Z0("refresh"),q7=Z0("accounts"),zO=1e4,ZO=15000,fJ=50;function v0(X){return X.type==="oauth"&&X.corrupt!==!0}function WO(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 t1="floors-v1";function UW(X){return X.costZeroing?.enabled!==!1}class L7 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(X){super(`Fallback account ${X} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var BO=[401,403,429],YW={primary:0,secondary:0},HO=!1,C9={primary:5,secondary:10};function Q0(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}var VO=new Set(["__proto__","constructor","prototype"]);function x8(X){return X.length>0&&!VO.has(X)}function UO(X){return X instanceof L7||Q0(X)&&X.name==="AccountRemovedDuringRefreshError"&&X.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function N7(X){return{id:typeof X.id==="string"&&X.id.trim()?X.id.trim():GO(),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 GW(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 KO(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 jO(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(!WO(J))return null;let Y=X.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...N7(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{...N7(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{...N7(X),type:"oauth",corrupt:!0}}return{...N7(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:GW(X.lastRefreshError),lastQuotaRefreshError:GW(X.lastQuotaRefreshError),quota:KO(X.quota)}}function NO(X){if(!Q0(X))return;let J=Object.create(null);for(let[$,Y]of Object.entries(X)){if(!x8($)||!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 QW=new Set;function KW(X){if(X.length===0)return;let J=JSON.stringify([...X].sort());if(QW.has(J))return;QW.add(J),q7.warn("account load-dropped, preserved on disk",{droppedIds:X})}function jW(X){if(!Q0(X)||!Array.isArray(X.accounts))return null;let J=X.accounts,$=J.map(jO).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);KW(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:NO(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 NW(X){if(!("claustrum"in X))return X;let{claustrum:J,...$}=X;return $}async function E9(X){try{return{exists:!0,value:JSON.parse(await qO(X,"utf8"))}}catch(J){if(J.code==="ENOENT")return{exists:!1,value:null};throw J}}function S9(X){return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0))}async function dJ(X){let J;try{J=(await E9(X)).value}catch{return null}return iJ(J)}function qW(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((N)=>{if(!Q0(N))return N;let K=typeof N.id==="string"&&Q0(G[N.id])?G[N.id]:{};return{...N,...K}}):void 0;return LW({...X,refresh:S9({...z,mainLastRefreshError:z.mainLastRefreshError??W.lastRefreshError,mainRefreshLeaseId:H.id,mainRefreshLeaseUntil:H.until,mainRefreshLeaseTokenHash:H.tokenHash}),quota:S9({...Q,mainQuota:Z.quota,mainQuotaCheckedAt:Z.quotaCheckedAt,mainQuotaToken:Z.quotaToken,mainLastQuotaApiError:Z.lastQuotaApiError}),accounts:j})}async function b0(X){let J=await E9(X.configPath);if(!J.exists)return null;let $=await E9(X.statePath);return jW(qW(J.value,$.value))}function LW(X){return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0))}function LO(X){return S9({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 DW(X){if(X.type==="api")return S9({apiKey:X.apiKey,lastUsed:X.lastUsed});if(X.corrupt)return{};return S9({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 D7(X){return Math.max(X?.primary?.checkedAt??0,X?.secondary?.checkedAt??0)}function Z3(X,J,$){if($ in J)X[$]=J[$];else delete X[$]}function DO(X,J){return X.access===J.access&&X.refresh===J.refresh&&X.expires===J.expires&&X.lastRefreshedAt===J.lastRefreshedAt}function FO(X,J){if(!DO(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 PO=300000;function zW(X,J){if(X===void 0)return 0;return X>J+PO?0:X}function OO(X,J,$){let Y=Date.now(),G=zW(J.lastRefreshedAt,Y),Q=zW($.lastRefreshedAt,Y),z=J.expires??0,Z=$.expires??0,W=Q>G?$:G>Q?J:Z>z?$:z>Z?J:FO(J,$);Z3(X,W,"access"),Z3(X,W,"refresh"),Z3(X,W,"expires"),Z3(X,W,"lastRefreshedAt"),Z3(X,W,"lastRefreshError")}function MO(X,J){if(!Q0(X))return J;let $=X,Y=D7($.quota),G=D7(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 OO(z,$,J),z}function FW(X){let J=X.refresh?S9({enabled:X.refresh.enabled,refreshBeforeExpiryMinutes:X.refresh.refreshBeforeExpiryMinutes}):void 0,$=X.quota?S9({enabled:X.quota.enabled,checkIntervalMinutes:X.quota.checkIntervalMinutes,refreshEveryNRequests:X.quota.refreshEveryNRequests,minimumRemaining:X.quota.minimumRemaining,failClosedOnUnknownQuota:X.quota.failClosedOnUnknownQuota}):void 0;return LW({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(LO)})}async function B3(X,J=!1){let $=Date.now(),Y=$+ZO,G=0;while(Date.now()<=Y){G++;let Z=await g0({name:"save",ttlMs:zO,path:X,renew:J});if(Z)return Z;let W=Y-Date.now();if(W<=0)break;await QO(Math.min(fJ+_W(fJ),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 ${fJ}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 PW(X){let J=Object.fromEntries(X.accounts.map(($)=>[$.id,DW($)]));return{version:1,main:S9({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 iJ(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 _O(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 AO(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 TO(X,J,$){let Y=iJ(X);if(Y===null)return[];let{preservedRawEntries:G,preservedIds:Q}=_O(X,Y,J,$);return KW(Q),G}async function F7(X,J,$={}){let{configPath:Y,statePath:G}=J,Q=await B3(Y);try{let z=await B3(G);try{let Z=await E9(Y),W=await E9(G),B=(Z.exists?jW(qW(Z.value,W.value)):null)??RO(),H=new Set(B.accounts.map((L)=>L.id)),U=iJ(Z.value)??new Set,j=X(B,{rawRosterIds:[...U],loadedRosterIds:[...H]})??B,N=new Set($.allowDrop??[]),K=TO(Z.value,H,N),q=FW(j),F=new Set((Array.isArray(q.accounts)?q.accounts:[]).map((L)=>Q0(L)&&typeof L.id==="string"?L.id.trim():"").filter(Boolean)),O=K.filter((L)=>{if(!Q0(L))return!1;if(typeof L.id!=="string")return!1;return!F.has(L.id.trim())}),_=Q0(Z.value)?Z.value:{},C={...NW(_),...q,accounts:[...Array.isArray(q.accounts)?q.accounts:[],...O]};if($.canWrite&&!$.canWrite())return B;if(await M6(Y,C),$.canWrite&&!$.canWrite())return B;return await M6(G,PW(j)),q7.debug("account config written",{accountCount:C.accounts.length,accountIds:AO(C.accounts)}),j}finally{await z.release()}}finally{await Q.release()}}function RO(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function CO(X,J){X.main=X.main??{};let $=typeof X.main.quotaCheckedAt==="number"?X.main.quotaCheckedAt:D7(X.main.quota),Y=typeof J.quota?.mainQuotaCheckedAt==="number"?J.quota.mainQuotaCheckedAt:D7(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 EO(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 mJ(X){if(Array.isArray(X))return X.map(mJ);if(!Q0(X))return X;return Object.fromEntries(Object.entries(X).filter(([,J])=>J!==void 0).map(([J,$])=>[J,mJ($)]))}async function nJ(X,J,$={mainQuota:!0,mainRefresh:!0,accounts:!0},Y){let G=J.statePath,Q=await B3(G);try{let z=(await E9(G)).value,Z=Q0(z)?{...z,version:1}:{version:1};if($.mainQuota)CO(Z,X);if($.mainRefresh)EO(Z,X);if($.accounts){let W=$.accounts===!0?null:new Set($.accounts),B=await dJ(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]=MO(Z.accounts[H.id],DW(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 M6(G,mJ(Z))}finally{await Q.release()}}function sJ(X){return X?.fallbackOn?.length?X.fallbackOn:BO}function V3(X,J){return sJ(J).includes(X)}function SO(X){let J=X?.quota?.minimumRemaining||{};return{primary:J.primary??J["5h"]??YW.primary,secondary:J.secondary??J["1w"]??YW.secondary}}function uJ(X){return X?.quota?.enabled!==!1}function H3(X){return X?.quota?.failClosedOnUnknownQuota??HO}function U3(X,J,$=Date.now()){if(!uJ(J))return!0;if(!X)return!H3(J);let Y=SO(J),G=H3(J);for(let Q of["primary","secondary"]){let z=X[Q];if(!z)continue;if(j7(z,$)){if(G)return!1;continue}if(z.remainingPercent<Y[Q])return!1}return!0}function z9(X){return X?.killswitch?.enabled===!0}function ZW(X){return{primary:X?.primary??X?.["5h"]??C9.primary,secondary:X?.secondary??X?.["1w"]??C9.secondary}}function P7(X){return X?.cacheKeep??X?.cachekeep}function WW(X){return typeof X==="number"&&Number.isFinite(X)?X:0}function a6(X,J){if(!X?.killswitch)return C9;if(X.killswitch.schema===t1){let{accounts:$,defaults:Y}=X.killswitch,G=J??"main",Q=Q0($)&&Object.hasOwn($,G)&&Q0($[G])?$[G]:Q0(Y)?Y:void 0;return{primary:WW(Q?.primary),secondary:WW(Q?.secondary)}}if(J&&X.killswitch.accounts?.[J])return ZW(X.killswitch.accounts[J]);return ZW(X.killswitch.main)}function Z1(X,J,$,Y=Date.now()){if(!z9(J))return!0;if(!X)return!H3(J);let G=a6(J,$),Q=H3(J);for(let z of["primary","secondary"]){let Z=X[z];if(!Z)continue;if(j7(Z,Y)){if(Q)return!1;continue}if(Z.remainingPercent<G[z])return!1}return!0}function OW(X,J,$,Y){if(!z9(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=a6(Y,Z),H=[],U=!1;for(let j of["primary","secondary"]){let N=W[j];if(!N||j7(N,$))continue;if(N.remainingPercent>=B[j])continue;let K=N.resetsAt?Date.parse(N.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 BW(X){return typeof X.version==="number"&&Array.isArray(X.accounts)}async function MW(X,J){let{configPath:$,statePath:Y}=J;if(!X)return;try{let Q=await E9($);if(Q.exists&&Q0(Q.value)&&BW(Q.value))return}catch{}let G=await B3($);try{let Q=await B3(Y);try{let z=await E9($);if(z.exists&&Q0(z.value)){if(BW(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={...NW(W),...FW(Z)};await M6($,B),await M6(Y,PW(Z))}finally{await Q.release()}}finally{await G.release()}}function IO(X){return X?.refresh?.enabled!==!1}function aJ(X){return(X?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function _W(X){return Math.floor(Math.random()*(X+1))}function z1(X,J,$){return!X.access||!X.expires||X.expires-$<=aJ(J)}function bO(X,J){return Boolean(X.access&&typeof X.expires==="number"&&X.expires>J)}function Q9(X,J){return Boolean(X?.mainAccountId&&J.accountId&&J.accountId===X.mainAccountId)}class AW 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 TW="common-auth-placeholder:v1:openai",U8="main";function C6(X){return Q0(X)&&X.type==="oauth"&&(X.refresh===TW||X.refresh===tZ)}function Z9(X){return X?.accounts.find((J)=>J.id===U8&&J.enabled!==!1&&v0(J))}function oJ(X){if(!X)return X;return{...X,accounts:X.accounts.filter((J)=>J.id!==U8)}}function w6(X,J){let $=X.accounts.findIndex((Y)=>Y.id===J.id);if($!==-1)X.accounts[$]=J}function W3(X){return X instanceof Error?X.message:String(X)}function pJ(X,J,$){if(J instanceof G1)return;X.lastRefreshError=p1({error:J,now:$,refreshToken:X.refresh,previous:X.lastRefreshError})}function gJ(X,J,$){if(J instanceof G1)return;if(X.lastQuotaRefreshError=i4({error:J,now:$,previous:X.lastQuotaRefreshError}),J?.isRefreshError===!0)pJ(X,J,$)}function HW(X,J){if(!X)return!1;if(!X.resetsAt)return!0;let $=Date.parse(X.resetsAt);return Number.isFinite($)?$>J:!0}function kO(X,J){if(!X)return!1;return HW(X.primary,J)||HW(X.secondary,J)}function xO(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 VW(X,J,$){return!xO(X.quota,J,$)}function wO(X,J,$,Y){return x5($)&&U3(X.quota,J,Y)&&kO(X.quota,Y)}function vO(X){let J=X?.quota?.checkIntervalMinutes??5;return Math.max(1,J)*60000}var yO=60000,hO=60000,rJ=600000;function tJ(X){return`fallback-oauth-refresh-${YO("sha256").update(X).digest("base64url").slice(0,16)}`}var fO=1e4,gO=100;class eJ{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)K7(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:$+vO(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 nJ(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(()=>{})},yO+_W(hO)),"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(Q9(J,G))continue;if(T0(G))continue;let Q=!1,z=G;try{if(z1(z,J,this.now())){let Z=z.lastRefreshError;if(Z&&r0(Z,z.refresh,this.now()))throw Q=!0,Error(X9(Z,this.now()));try{z=await this.refreshAccount(z,J),Y=!0}catch(W){if(UO(W))continue;Q=!0;let B=J.accounts.find((H)=>H.id===G.id&&v0(H));if(B&&!r0(B.lastRefreshError,B.refresh,this.now()))pJ(B,W,this.now()),w6(J,B),Y=!0;throw W}}if(this.seedFallbackQuota(z,J),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(z),J))$.push(z)}catch(Z){let W=bO(z,this.now());if(Q){if(!W)continue}else if(!W)continue;if(wO(z,J,Z,this.now()))Q1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:z.id,error:W3(Z)}),$.push(z);else if(!H3(J))$.push(z)}}if(Y){let G=structuredClone(J);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(G)).catch((Q)=>{q7.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:W3(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){q7.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:X.id,error:W3(J)})}}accountPassesQuotaPolicy(X,J){return U3(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||!IO(X))return;let J=!1;for(let $ of X.accounts){if($.enabled===!1||!v0($))continue;if(Q9(X,$))continue;if(T0($))continue;if(!z1($,X,this.now()))continue;if(r0($.lastRefreshError,$.refresh,this.now()))continue;try{Q1.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){Q1.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:W3(Y)}),pJ($,Y,this.now()),w6(X,$),J=!0}}if(J)await this.save(X)}async refreshQuotaForDueAccounts(){let X=await this.load();if(!X||!uJ(X))return;if(!this.options.fetchQuotaFn)return;let J=!1;for(let $ of X.accounts){if($.enabled===!1||!v0($))continue;if(Q9(X,$))continue;if(T0($))continue;let Y=$;try{if(z1(Y,X,this.now())){if(r0(Y.lastRefreshError,Y.refresh,this.now()))continue;Y=await this.refreshAccount(Y,X),J=!0}if(c1(Y.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(Y,X),!(this.quotaManager?this.quotaManager.isFallbackStale(Y.id,Y.access):VW(Y,X,this.now())))continue;await this.refreshAccountQuota(Y,X),J=!0}catch(G){gJ($,G,this.now()),w6(X,$),J=!0}}if(J)await this.save(X),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(X={}){let J=await this.load(),$=[];if(!J||!uJ(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(Q9(J,Q))continue;if(T0(Q))continue;let z=Q;try{if(z1(z,J,this.now())){let Z=z.lastRefreshError;if(Z&&r0(Z,z.refresh,this.now()))throw Error(X9(Z,this.now()));z=await this.refreshAccount(z,J),G=!0}if(!Y&&!VW(z,J,this.now())){if(z.lastQuotaRefreshError)z.lastQuotaRefreshError=void 0,w6(J,z),G=!0;continue}await this.refreshAccountQuota(z,J),G=!0}catch(Z){gJ(Q,Z,this.now()),w6(J,Q),G=!0,$.push({accountId:Q.id,message:W3(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 w6(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 w6(J,Q),Q}async waitForConcurrentFallbackRefresh(X,J,$,Y){let G=Date.now()+fO;while(Date.now()<G){await new Promise((B)=>setTimeout(B,gO));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||!z1(z,Q,this.now())))return w6(J,z),Q1.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&&r0(W,z.refresh,this.now()))throw w6(J,z),Error(X9(W,this.now()))}return null}assertNotShieldedMainRow(X,J,$){if($.asPoolMain||!J)return;if(Q9(X,J))throw new AW(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&&!z1(G,Y,this.now()))return w6(J,G),G;let Q=G??X,z=await g0({name:tJ(Q.id),ttlMs:rJ,path:this.paths.configPath,now:this.now,renew:!0});if(!z){Q1.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&&!z1(G,Y,this.now()))return w6(J,G),G;if(!G)throw new L7(X.id);Q=G;let Z=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});Q1.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,w6(J,Q),await this.save(J),!(await this.load())?.accounts.some((H)=>H.id===X.id))throw new L7(X.id);return Q1.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,w6(J,$),await this.save(J)}catch(Q){throw gJ(X,Q,this.now()),w6(J,X),Q}}}var X$="/backend-api/wham/rate-limit-reset-credits",mO=`https://chatgpt.com${X$}`,bW=`${X$}/consume`,uO=`https://chatgpt.com${bW}`,pO=300000,cO=60000,lO=15000,dO=60000;function e1(X){return{configPath:X.configPath,statePath:X.statePath}}class o6 extends Error{kind;cooldownUntil;constructor(X,J,$){super(J);this.name="ResetRedemptionError",this.kind=X,this.cooldownUntil=$}}class W1 extends Error{kind;status;constructor(X,J,$){super(J);this.name="ResetCreditError",this.kind=X,this.status=$}}function kW(X,J,$){return{authorization:`Bearer ${X}`,...$?{"chatgpt-account-id":$}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":J}}function M7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function xW(X){if(!X)return;return{...X.inFlight?{inFlight:{...X.inFlight}}:{},...X.lastOutcome?{lastOutcome:{...X.lastOutcome}}:{},...X.cooldownUntil!==void 0?{cooldownUntil:X.cooldownUntil}:{}}}function _7(X){if(!M7(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}:{},...wW(X.rejectedStatus)?{rejectedStatus:X.rejectedStatus}:{},...typeof X.unknownAnswers==="number"&&Number.isSafeInteger(X.unknownAnswers)&&X.unknownAnswers>0?{unknownAnswers:X.unknownAnswers}:{}}}function wW(X){return typeof X==="number"&&X>=400&&X<500&&X!==408&&X!==409&&X!==425&&X!==429}function O7(X){return X.kind==="http_error"&&wW(X.status)}function vW(X,J){return X.chatgptAccountId!==void 0&&X.chatgptAccountId!==J||X.rejectedStatus!==void 0}function iO(X,J){if(X.chatgptAccountId!==void 0&&X.chatgptAccountId!==J)throw new o6("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function yW(X){return Boolean(X&&Object.hasOwn(X,"inFlight"))}function hW(X,J){return J-X.startedAt<pO}function X4(X,J){if(!x8(J))return;return X.reset?.[J]}function fW(X){if(!X.reset)X.reset=Object.create(null);return X.reset}function gW(X,J,$){if(!x8(J))return;let Y=fW(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 mW(X,J){let $=xW(X),Y=_7(X?.inFlight);if(yW(X)&&!Y)return{kind:"corrupt",beforeState:$};if(X?.cooldownUntil!==void 0&&X.cooldownUntil>J)return{kind:"cooldown",beforeState:$,cooldownUntil:X.cooldownUntil};if(Y&&hW(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 nO(X,J){if(!x8(J))return{kind:"fresh",beforeState:void 0};let $=await X.loadAccountsFn(e1(X));return mW($?X4($,J):void 0,X.now())}async function sO(X,J){let $;if(await X.mutateAccountsFn((Y)=>{let G=X.now(),Q=X4(Y,J);if($=mW(Q,G),$.kind==="corrupt")gW(Y,J,G);return Y},e1(X)),!$)throw Error("corrupt reset state mutation did not run");return $}async function aO(X,J,$,Y){if(!x8(J))return{kind:"fresh",beforeState:void 0};let G;if(await X.mutateAccountsFn((Q)=>{let z=X.now(),Z=X4(Q,J),W=xW(Z),B=_7(Z?.inFlight);if(yW(Z)&&!B)return gW(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&&hW(B,z))return G={kind:"claim",beforeState:W,claim:{inFlight:B,selectedCredit:{id:B.creditId}}},Q;if(B&&!vW(B,Y))return G={kind:"expired_unreconciled",beforeState:W,claim:{inFlight:B,selectedCredit:{id:B.creditId}}},Q;let H=A7($);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=fW(Q);return j[J]={...Z,inFlight:U},G={kind:"claim",beforeState:W,claim:{inFlight:U,selectedCredit:H}},Q},e1(X)),!G)throw Error("reset claim mutation did not run");return G}async function oO(X,J,$,Y,G){if(!x8(J))return;if(!Y$(Y.kind))return rO(X,J,$,Y,G);await X.mutateAccountsFn((Q)=>{let z=X4(Q,J),Z=_7(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+dO;else delete z.cooldownUntil;return Q},e1(X));return}function RW(X,J){let $=_7(X?.inFlight);return $&&$.redeemRequestId===J.redeemRequestId&&$.creditId===J.creditId?$:void 0}async function rO(X,J,$,Y,G){let Q=O7(Y)?Y.status:void 0;if(!($.chatgptAccountId===void 0&&G!==void 0)&&Q!==void 0&&Q===$.rejectedStatus){let W=await X.loadAccountsFn(e1(X));return RW(W?X4(W,J):void 0,$)}let Z;return await X.mutateAccountsFn((W)=>{Z=void 0;let B=X4(W,J),H=RW(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},e1(X)),Z}function K3(X,J){if(!X||X.usedPercent<100)return!1;if(!X.resetsAt)return!0;let $=Date.parse(X.resetsAt);return!Number.isFinite($)||$>J}function J$(X,J,$){if(!(J||K3(X.primary,$)||K3(X.secondary,$)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function CW(X,J){let $=X[J];if($===void 0||$===null)return;return typeof $==="string"?$:null}function tO(X){if(!M7(X))return;let J=CW(X,"granted_at"),$=CW(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 $$(X,J,$){let Y;try{Y=await X(mO,{method:"GET",headers:kW(J,X$,$),signal:AbortSignal.timeout(lO)})}catch{throw new W1("http_error","reset credit list request failed")}if(!Y.ok)throw new W1("http_error",`reset credit list request failed: ${Y.status}`,Y.status);let G;try{G=await Y.json()}catch{throw new W1("invalid_response","reset credit list response was not valid JSON",Y.status)}if(!M7(G))throw new W1("invalid_response","reset credit list response was not an object",Y.status);return{credits:(Array.isArray(G.credits)?G.credits:[]).flatMap((z)=>{let Z=tO(z);return Z===void 0?[]:[Z]}),availableCount:typeof G.available_count==="number"&&Number.isFinite(G.available_count)?G.available_count:void 0}}function A7(X){return[...X].filter(uW).sort((J,$)=>Date.parse(J.expiresAt)-Date.parse($.expiresAt))[0]}function uW(X){return X.status==="available"&&X.isSupportedByPlan&&X.resetType==="codex_rate_limits"}function pW(X){return X.filter(uW).length}function Y$(X){return X==="reset"||X==="already_redeemed"||X==="nothing_to_reset"||X==="no_credit"}async function eO(X,J,$,Y,G){let Q;try{Q=await X(uO,{method:"POST",headers:{...kW(J,bW,$),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:G,credit_id:Y}),signal:AbortSignal.timeout(cO)})}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||!M7(Z)||!Y$(Z.code))return{kind:"ambiguous",raw:Z};return{kind:Z.code,raw:Z}}function EW(X){if(X.kind==="cooldown")throw new o6("cooldown_active","reset credit redemption is cooling down",X.cooldownUntil);throw Error(`unexpected reset state decision: ${X.kind}`)}function SW(){throw new o6("expired_unreconciled","the previous reset attempt outcome is unknown")}function IW(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 XM(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(O7(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 JM(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 cW(X,J){if(!x8(J.accountKey))throw new o6("invalid_account_key","the reset account key is reserved");let $=await X.resolveTarget(J.accountKey);if($.chatgptAccountId!==J.expectedChatgptAccountId)throw new o6("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let Y=$.chatgptAccountId,G=$.accountKey==="main"?void 0:Y,Q=await nO(X,J.accountKey);if(Q.kind==="corrupt"){if(Q=await sO(X,J.accountKey),Q.kind==="corrupt")return IW($,Q.beforeState)}if(Q.kind==="cooldown")EW(Q);let z;if(Q.kind==="claim")z=Q.claim;else if(Q.kind==="expired_unreconciled"&&(J.retry||!vW(Q.claim.inFlight,Y))){if(!J.retry)SW();z=Q.claim}else{if(J.retry)throw new o6("retry_without_inflight","there is no active reset credit redemption to retry");let[j,N]=await Promise.all([X.fetchUsage($),$$(X.fetchImpl,$.accessToken,G)]),K=J$(j,X.hasActiveRateLimitMark(J.accountKey),X.now());if(!K.ok)throw new o6("not_exhausted",K.reason);if(!A7(N.credits))throw new o6("no_eligible_credit","no eligible reset credit was returned");let q=await aO(X,J.accountKey,N.credits,Y);if(q.kind==="corrupt")return IW($,q.beforeState);if(q.kind==="cooldown")EW(q);if(q.kind==="expired_unreconciled")SW();if(q.kind!=="claim")throw new o6("no_eligible_credit","no eligible reset credit was available while claiming");z=q.claim}iO(z.inFlight,Y);let Z=await eO(X.fetchImpl,$.accessToken,G,z.inFlight.creditId,z.inFlight.redeemRequestId),W,B=!1;try{W=await oO(X,J.accountKey,z.inFlight,Z,Y)}catch{B=!0}let H=B&&Y$(Z.kind),U=O7(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.":O7(Z)&&!U?JM(B,W):XM(Z),...U?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}function s(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}import{statSync as GM}from"node:fs";import{rm as dW}from"node:fs/promises";import{dirname as QM,join as iW}from"node:path";var lW=["primary","secondary"];function G$(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}function j3(X){return typeof X==="number"&&Number.isFinite(X)}function $M(X,J){if(!G$(J))return;let $=J.usedPercent;if(!j3($)||$<0||$>100)return;return{label:X,usedPercent:$,...typeof J.resetsAt==="string"?{resetsAt:J.resetsAt}:{},...j3(J.windowMinutes)&&J.windowMinutes>0?{windowMinutes:J.windowMinutes}:{}}}function YM(X){let J=X.spendControl;if(G$(J)&&typeof J.reached==="boolean"){let $=(Y)=>j3(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 I9(X,J,$){if(!G$(X)||!j3(J))return;let Y=[],G=[];for(let z of lW){let Z=$M(z,X[z]);if(Z)Y.push(Z);else if($)G.push({label:z})}let Q=YM(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 K8(X){if(!G6(X))return;let J=f0(X),$={};for(let Y of lW){let G=J.limits.find((z)=>z.label===Y&&z.kind==="reading");if(!G||!j3(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 W9=Z0("vault"),zM="openai-auth",nW={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},ZM={opencode:"OpenCode",pi:"Pi"};function WM(X){return LJ(zM,X)}function sW(X){return iW(QM(X),"openai-auth-vault")}function BM(X,J){return{...FJ({stateDir:X,host:J}),rosterPath:iW(X,`${J}-roster.json`)}}var aW=2000,Q$={"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 oW(X){return X.snapshot()===void 0?"vault-unreachable":"vault-empty"}function HM(X){let J=V6(X);return J?U6(J):void 0}class z${host;name;paths;#X;#J;#W=new Map;#Q=new Map;#z;#Y;#$;#B=!1;#H=!1;#G=Promise.withResolvers();#Z;#V="unknown";#U;constructor(X){this.#X=X,this.host=X.host,this.name=WM(X.host),this.paths=BM(X.stateDir,X.host),this.#J=new U7({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:nW,connect:()=>this.#D(),isCustodyActive:()=>this.enrolled(),...X.reservedRouteIds?{reservedRouteIds:X.reservedRouteIds}:{},parseIdentity:HM,...X.now?{now:X.now}:{},onRoster:()=>{this.#z=void 0},onError:(J)=>this.#K("vault roster refresh failed",J),logger:W9})}#N(){return(this.#X.connectionFile??e9)()}#q(){return{connectionFile:this.#N(),projectRoot:this.#X.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(X)=>W9.debug("vault transport error",{errorClass:X})}}#D(){return this.#X.connectScoped?.()??rZ(this.#q())}#F(){return this.#X.connectEnrollment?.()??DJ(this.#q())}#K(X,J){this.#z=e0(J),W9.warn(X,{host:this.host,error:this.#z})}#j(){return[this.paths.tokenPath,this.paths.statePath].map((X)=>{try{let J=GM(X);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let X=this.#j(),J=await $3(this.paths,this.name);if(X===this.#j())return this.#V=J,this.#U=X,J;return"unreadable"}enrolled(){return this.#U!==this.#j()||this.#V!=="local"}start(){if(this.#B||this.#H)return;this.#B=!0;let X=async()=>{try{await this.authority(),await this.#L()}catch($){if(!this.#H)this.#K("vault roster refresh failed",$)}if(this.#H)return;let J=this.#X.pollIntervalMs??5000;if(J<=0)return;this.#Z=setTimeout(()=>{this.#Z=void 0,X()},J),this.#Z.unref?.()};X()}#L(){return this.#$??=this.#J.refresh().finally(()=>{this.#$=void 0,this.#G.resolve()}),this.#$}firstRoster(){return this.#G.promise}async refresh(){try{await this.authority();let X=this.#$;if(X)await X.catch(()=>{return});let J=await this.#L();return this.#z=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=I9(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))}pollQuota(X){let J=this.#Q.get(X);if(J)return J;let $=this.#P(X).finally(()=>{this.#Q.delete(X)});return this.#Q.set(X,$),$}async#P(X){let J,$=this.#X.fetchImpl?.()??globalThis.fetch,Y=await this.send(X,async(G,Q)=>{try{let z=await b8({accessToken:G,fetchImpl:$,now:this.#X.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:X,logger:W9});return await this.recordSnapshot(X,z,!0,Q),J=void 0,new Response(null,{status:200})}catch(z){J=e0(z);let Z=z?.status;if(typeof Z==="number")return new Response(null,{status:Z});throw z}},{site:"quota"}).catch((G)=>{J=e0(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){let J=this.#W.get(X);if(J)return J;let $=this.pollQuota(X).catch((Y)=>{W9.warn("vault quota poll failed",{routeId:X,error:e0(Y)})}).finally(()=>{this.#W.delete(X)});return this.#W.set(X,$),$}async pollStale(X){let J=(this.#X.now??Date.now)(),$=[];for(let Y of this.routes()){let G=VM(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),W9.info("vault account declined",{routeId:X})}async accept(X){await this.#J.accept(X),W9.info("vault account accepted",{routeId:X})}async status(){await this.authority();let X;try{X=await J3(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.#z?{lastError:this.#z}:{}}}async connectStep(){let X=await this.#F().catch((J)=>{throw new k6("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${e0(J)}. Is the vault running?`)});try{let J=new z7({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(W9.info("vault enrollment step",{host:this.host,state:Y.state}),Y.state==="approved")this.#z=void 0,await this.refresh();return Y}finally{X.close()}}waitForApproval(X={}){return this.#Y??=(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.#Y=void 0}),this.#Y}async disconnect(){await dW(this.paths.tokenPath,{force:!0}),await dW(this.paths.statePath,{force:!0}),await this.authority(),this.#z=void 0,W9.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(X){if(this.serves())_J({mode:"custody",auth:X,provider:"openai"})}close(){if(this.#H=!0,this.#G.resolve(),this.#Z)clearTimeout(this.#Z);this.#Z=void 0,this.#J.close()}}function VM(X){if(!X)return;let J=f0(X).limits.map(($)=>$.checkedAt);return J.length>0?Math.max(...J):void 0}function J4(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 ${nW.category} --operation read`]}function N3(X,J,$){let Y=`${ZM[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 q3(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:[...J4(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 rW(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 tW(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 eW(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 L3(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 rW(X.checks);for(let z of tW(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 eW($,Y);$.print(`Applied ${Q.applied.length} of ${G.length} repair(s).`)}}}import{execFileSync as UM,spawn as KM}from"node:child_process";function JB(X,J=process.platform,$=UM,Y=KM){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 XB(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 T7(X,J){let $=new AbortController,Y=await X.begin({headless:!1,signal:$.signal});Y.completion.catch(()=>{}),XB(J,Y);let G=!1;try{G=await(X.openBrowser??JB)(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}),XB(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 Z$(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 $B=`${String.fromCharCode(27)}\\[[0-9;]*m`,jM=new RegExp($B,"g"),NM=new RegExp(`^${$B}`);function YB(X){return X.replace(jM,"")}function B1(X,J){if(J<=0)return"";if(YB(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(NM);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 W$(){return{input:process.stdin,output:process.stdout,signals:process}}function H1(X){return X.input.isTTY===!0}function B$(X,J=""){X.output.write(`${J}
94
+ `)}var qM=50;function LM(X){if(X==="red")return B0.red;if(X==="cyan")return B0.cyan;return""}async function $4(X,J,$){if(!H1(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,N=B;if($.clearScreen)G.write(B0.clearScreen+B0.moveTo(1,1));else if(N>0)G.write(B0.up(N));let K=0,q=(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-_))),L=J.slice(C,C+_);if(q(`${B0.dim}┌ ${B0.reset}${B1($.message,Math.max(1,U-4))}`),$.subtitle)q(`${B0.dim}│${B0.reset}`),q(`${B0.cyan}◆${B0.reset} ${B1($.subtitle,Math.max(1,U-4))}`),q("");for(let A of F)q(`${B0.cyan}│${B0.reset} ${B1(A,Math.max(1,U-4))}`);if(F.length)q(`${B0.cyan}│${B0.reset}`);for(let A=0;A<L.length;A++){let T=L[A];if(!T)continue;let k=C+A===z,p=LM(T.color),i=p?`${k?"":B0.dim}${p}${T.label}${B0.reset}`:k?T.label:`${B0.dim}${T.label}${B0.reset}`;if(T.hint)i+=` ${B0.dim}${T.hint}${B0.reset}`;i=B1(i,Math.max(1,U-8)),q(k?`${B0.cyan}│${B0.reset} ${B0.green}●${B0.reset} ${i}`:`${B0.cyan}│${B0.reset} ${B0.dim}○${B0.reset} ${i}`)}let P=L.length<J.length?` (${C+1}-${C+L.length}/${J.length})`:"";q(`${B0.cyan}│${B0.reset} ${B0.dim}${B1(`Up/Down to select | Enter: confirm | Esc: back${P}`,Math.max(1,U-6))}${B0.reset}`),q(`${B0.cyan}└${B0.reset}`);for(let A=K;A<N;A++)q("");B=K};return new Promise((U)=>{let j=Y.isRaw??!1,N=()=>{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",q),Q?.removeListener("SIGTERM",q)},K=(O)=>{N(),U(O)},q=()=>K(null),F=(O)=>{for(let _ of Z$(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),qM);break;default:break}}};Q?.once("SIGINT",q),Q?.once("SIGTERM",q);try{Y.setRawMode(!0)}catch{N(),U(null);return}Y.resume(),G.write(B0.hide),H(),Y.on("data",F)})}async function H$(X,J,$=!1){if(!H1(X))return!1;return await $4(X,$?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:J})??!1}function GB(X){let J=H1(X);return{terminal:X,interactive:J,print:($)=>B$(X,$),confirm:($,Y)=>H$(X,$,Y),select:async($,Y)=>J&&$.length>0?$4(X,$,Y):null}}function DM(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 V1(X){let J=X.terminal??W$(),$=GB(J);if(!$.interactive)return DM($,X);if(X.actions.length===0)return $.print("No actions are available."),{status:"cancelled"};let Y=await $4(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 zB="disabled from the auth menu",QB=8;async function w8(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 K$(X){let{rows:J}=await w8(X);return J.some(($)=>$.credential!==void 0)}function j$(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 FM(X){if(X.problem)return[X.problem];if(X.rows.length===0)return["No accounts yet."];let J=X.rows.slice(0,QB).map((Y)=>`${Y.id}: ${j$(Y)}`),$=X.rows.length-QB;if($>0)J.push(`... and ${$} more`);return J}function PM(X){return X instanceof Error?X.message:String(X)}async function N$(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:j$(Y)})),{message:$})}function OM(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 ZB(X,J=Date.now()){let $=G6(X.quota)?f0(X.quota):void 0,Y=R7($,{now:J,form:"full"});return(Y.length>0?Y:[R8($,{now:J})]).map((G)=>` ${G}`)}function WB(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 T7($,J),{rows:G}=await w8(X.store),Q=(X.newAccountId??OM)(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 BB(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 w8(X.store),G=await N$(J,Y,"Re-authenticate which account?");if(!G)return;let Q=await T7($,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 HB(X){return{...X.protect?{protect:X.protect}:{},...X.extraLocks?{extraLocks:X.extraLocks}:{}}}function VB(X){return X instanceof K0&&X.kind==="row-protected"?X.message:void 0}function UB(X){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run(J){let{rows:$}=await w8(X.store),Y=await N$(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,HB(X))}catch(G){let Q=VB(G);if(Q===void 0)throw G;J.print(`Account ${Y.id} was kept: ${Q}`);return}J.print(`Removed account ${Y.id}.`)}}}function V$(X){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run(J){let{rows:$}=await w8(X.store),Y=await N$(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??zB,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 KB(X){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run(J){let $=await w8(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}: ${j$(Y)}`)}}}function U$(X){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run(J){let $=await w8(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,PM(Z))}}let Q=await w8(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 ZB(z,(X.now??Date.now)()))J.print(W)}}}}function jB(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 w8(X.store);if($.problem){J.print($.problem);return}let Y=[],G=[];for(let Q of $.rows)try{await X.store.remove(Q.id,HB(X)),Y.push(Q.id)}catch(z){let Z=VB(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 q$(X){return NB(X,await X.custody?.()===!0)}function NB(X,J){let $=X.doctor?.length?[L3({checks:X.doctor})]:[],Y=[...X.extraActions??[]];if(J)return[KB(X),V$(X),U$(X),...$,...Y];return[...X.login?[WB(X),BB(X)]:[],UB(X),V$(X),U$(X),...$,...Y,jB(X)]}async function L$(X){let J=await X.custody?.()===!0,$=NB(X,J),[Y,G]=await Promise.all([w8(X.store),X.status?.()??[]]);return V1({title:X.title,subtitle:J?"Accounts come from the vault; select an action":"Select an account action",status:[...G,...FM(Y)],actions:$,...X.terminal?{terminal:X.terminal}:{}})}function D$(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function qB(X){return X!==void 0}function F$(X){return async(J)=>{if(!qB(J))return X.login();if(!await X.hasCredential())return X.login(J);return await X.openMenu(J),D$()}}function v8(X){return X.authority!=="local"}async function r6(X){return{authority:await X.authority(),status:await X.status(),identities:X.identities(),routes:new Set(X.routes().map((J)=>J.id))}}async function C7(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."),aW)})])}finally{clearTimeout(J)}}function y8(X){return X.email||X.label||X.routeId}function LB(X,J){let $=f0(G6(X.quota)?X.quota:void 0),Y=R7($,{now:J});return(Y.length>0?Y:[R8($,{now:J})]).map((G)=>` ${G}`)}var D3="Accounts are managed in the vault with ck. Disconnect to use local accounts.",h8="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function DB(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 F3(X,J){let $=await C7(J),Y=await r6(J),{status:G}=Y,Q=v8(Y)?void 0:await X.store.read(),z=await q$(X),Z=new Set(["check-quotas",...(X.extraActions??[]).map((H)=>H.id)]),W=z.filter((H)=>!v8(Y)||Z.has(H.id)).map((H)=>({...H,run:async(U)=>{if(!Z.has(H.id)&&v8(await r6(J))){U.print(h8);return}await J.authority(),await H.run(U)}})),B=W.find((H)=>H.id==="check-quotas");if(B)B.run=async(H)=>{await C7(J);let U=await r6(J),j=v8(U)?void 0:await X.store.read();if(!j)H.print(D3);else if(j.status!=="ready")H.print("The local account store could not be read.");else for(let q of j.rows){H.print(DB(q));try{if(X.pollQuota&&q.credentialEpoch!==void 0){let _=await X.pollQuota(q);await X.store.recordQuota(q.id,{credentialEpoch:q.credentialEpoch,...q.identity!==void 0?{identity:q.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===q.id):void 0;for(let _ of LB(O??q,(X.now??Date.now)()))H.print(_)}let N=U.routes;for(let q of J.snapshot()?.rows??[]){if(H.print(`Vault ${y8(q)}: ${q.enabled?q.state:"declined"}`),!N.has(q.routeId)){H.print(" quota check skipped: account is not enabled and active");continue}let F=await J.pollQuota(q.routeId);if(!F.ok)H.print(` quota check failed: ${F.error??"vault unavailable"}`);let O=J.snapshot()?.rows.find((_)=>_.routeId===q.routeId);for(let _ of LB({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 V1({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 ${y8(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!Q?[D3]:Q.status==="ready"?Q.rows.map((H)=>DB(H)):["The local account store could not be read."]],actions:W,...X.terminal?{terminal:X.terminal}:{}})}function FB(X){return s(X)?{...X}:{}}function E7(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 P$(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 r6(J);if(!v8(Z))return z;let W=[...Z.status.accounts.map((B)=>({id:B.routeId,label:y8(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 r6(J),Z=FB(Q.settings.killswitch);if(!v8(z)||!Q.settings.killswitch)return Q;let W=FB(Z.accounts);for(let B of z.status.accounts)W[B.routeId]=a6({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 PB(X,J){let $=i9(X),Y=i9({command:X.command,title:X.title,store:P$(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 r6(J),U=v8(H),j=U?Y:$,K=(await j.open(B)).menu.sections.find((L)=>L.id===W);if(!K)throw new k6("unavailable","The account menu is unavailable.");if(!U)return{lines:K.lines,items:K.items.map((L)=>({...L,actions:L.actions.map((P)=>E7(j,W,P,L.id))})),actions:K.actions.map((L)=>E7(j,W,L))};let q=new Map(H.status.accounts.map((L)=>[L.routeId,L])),F=(X.now??Date.now)(),O=(L)=>({id:"check",label:L?"Check this account":"Check now",group:"Actions",run:async()=>{let A=[...(await r6(J)).routes].filter((T)=>!L||T===L);if(L&&A.length===0)throw new k6("unavailable","This vault account cannot be checked right now.");for(let T of A){let k=await J.pollQuota(T);if(!k.ok)throw new k6("quota-check-failed",`${T}: ${k.error??"vault unavailable"}`)}return`Checked quota for ${A.length} account${A.length===1?"":"s"}.`}});if(W==="quota"){let L=(P,A)=>R8(f0(P.quota,X.quota?.scope),{now:F,form:A});return{lines:H.status.accounts.filter((P)=>!H.routes.has(P.routeId)).map((P)=>`${y8(P)} (${P.enabled?P.state:"disabled"}): ${L(P,"compact")}`),items:H.status.accounts.filter((P)=>H.routes.has(P.routeId)).map((P)=>({id:P.routeId,label:y8(P),group:"Accounts",status:L(P,"compact"),detail:L(P,"full"),actions:[O(P.routeId)]})),actions:H.routes.size>0?[O()]:[]}}let _=K.items.map((L)=>{let P=q.get(L.id),A=P&&W==="accounts"?`Vault · ${P.credentialType==="oauth"?"login":"API key"} · ${P.state} · ${P.enabled?"enabled":"declined"}`:L.detail;return{id:L.id,label:L.label,detail:A,group:L.group,status:P&&W==="accounts"?P.enabled?P.state:"disabled":L.status,...L.facts?{facts:L.facts}:{},actions:P&&W!=="limits"?[]:L.actions.map((T)=>E7(j,W,T,L.id))}}),C=K.actions.filter((L)=>W==="limits"||W==="routing"&&L.id==="mode").map((L)=>E7(j,W,L));return{lines:W==="accounts"?[`${H.status.accounts.length} vault account${H.status.accounts.length===1?"":"s"}`,`${H.routes.size} can route`,D3]:K.lines,items:_,actions:C}},Q=i9({...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 r6(J);if(v8(H))return{lines:[D3]};return W.build(B)}})}),z=async()=>{if(!v8(await r6(J)))return{menu:$,error:void 0};let W=await C7(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 r6(J)).routes.size===0||W.sectionId==="limits"&&W.itemId!==void 0&&!(await r6(J)).status.accounts.some((j)=>j.routeId===W.itemId)))return{...await Z(H,B),ok:!1,code:"vault-local-action",text:h8};return U.apply(W,B)}}}var p6="openai",_$="OpenAI accounts",U1="main",_B="that account is already your main account, so it was not added again",e6=Z0("commands"),AB=new Set(["__proto__","constructor","prototype"]);function TB(X,J){let $={version:1,accounts:[],killswitch:X},Y=s(X.accounts)?Object.keys(X.accounts):[],G={};for(let Z of new Set([U1,...J,...Y])){if(AB.has(Z))continue;let W=a6($,Z===U1?void 0:Z);G[Z]={primary:W.primary,secondary:W.secondary}}let Q=a6($,void 0),z={...X};return delete z.main,z.accounts=G,z.defaults={primary:Q.primary,secondary:Q.secondary},z.schema=t1,z}function RB(X,J){let $=s(X.accounts)?{...X.accounts}:{};for(let G of new Set([U1,...J])){if(AB.has(G)||Object.hasOwn($,G))continue;$[G]={primary:C9.primary,secondary:C9.secondary}}let Y=s(X.defaults)?X.defaults:{primary:C9.primary,secondary:C9.secondary};return{...X,accounts:$,defaults:Y,schema:t1}}function O$(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!==t1)X.killswitch=TB(Y,J),$=!0;return $}async function OB(X){let J=await X.read();return J.status==="ready"?J.rows.map(($)=>$.id):[]}function I7(X){let J=async()=>{let Y=await X.readSettings();if(Y.status==="error")return Y;let G=structuredClone(Y.settings);return O$(G,await OB(X)),{...Y,settings:G}},$=async(Y,G)=>{let Q=await OB(X);return X.updateSettings(async(z)=>{O$(z,Q);let Z=await Y(z)??z;if(s(Z.killswitch)&&Z.killswitch.schema!==t1)Z.killswitch=RB(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 b7(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),N=W.identity?j.find((F)=>F.identity===W.identity):void 0;if(N?.id===U1)throw new k6("main-account",_B);let K=N??j.find((F)=>F.id===W.id&&F.id!==U1);if(!K||W.credential.type!=="oauth")return X.add(W,B);let q=await G(K.id,W.credential,W.identity!==void 0?{identity:W.identity}:{},B?.extraLocks?{extraLocks:B.extraLocks}:void 0);return e6.info("account signed in again",{id:K.id}),{id:q.id,outcome:"rotated",credential:q.credential,credentialEpoch:q.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 K1(X,J,$){await I7(X).updateSettings((Y)=>{$(Y);return},J?{extraLocks:J}:{})}var MM=["version","accounts","commonAuthPool"];function A$(X,J){return async($)=>{let Y;if(await I7(X).updateSettings((G)=>{let Q={...G,version:1,accounts:[]},z=$(Q)??Q;Y=z;let Z={...z};for(let W of MM)delete Z[W];return Z},J?{extraLocks:J}:{}),!Y)throw Error("the settings write did not run");return Y}}var CB="migration";function M$(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:p6,title:_$,sections:[{id:CB,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 TM($)}var _M=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function AM(X){let J=X.toLowerCase().replace(/[-_]/g,"");if(_M.has(J))return!0;return J.endsWith("token")||J.endsWith("key")||J.endsWith("secret")}function S7(X,J,$){if(Array.isArray(X))return X.map((G,Q)=>S7(G,`${J}[${Q}]`,$));if(!s(X))return X;let Y={};for(let[G,Q]of Object.entries(X)){if(AM(G)){$.push(`${J}.${G}`);continue}Y[G]=S7(Q,`${J}.${G}`,$)}return Y}function TM(X){let J=[],$=S7(X,"menu",J);if(J.length>0)e6.warn("credential-shaped field stripped before RPC",{fields:J});return $}function EB(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 SB(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
96
 
97
97
  ${G.url}
98
98
 
@@ -104,31 +104,31 @@ ${G.url}
104
104
 
105
105
  ${G.instructions}
106
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 t6.warn("account add rejected (main identity)",{id:Z.id}),new b6("main-account",FB);return t6.info("account added",{id:Z.id}),AB(Z)});return{status:"pending",message:Q,completion:z}}}}function _$(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),t6.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 A$(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}`,K3($.host,$.name,$.enrollment),...J4($.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:y8(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?.(),`${y8(Q)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await J.accept(Q.routeId),await X.changed?.(),`${y8(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?.(),j3(J,z);return J.waitForApproval(X.wait).then(async(Z)=>{await X.changed?.();let W=j3(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:[...J4(J.name,z),"Waiting for the approval; you are told here when it lands."].join(`
108
- `)}}}]}}}}async function DB(X,J,$){if(!k8(J))return r6(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 SB(J,X);if(!z.eligible)return r6(J,"not_eligible",IB(z));Y=z.chatgptAccountId}if(!Y)return r6(J,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");t6.info("reset redemption decision",{accountKey:J,retry:$});let Q=await gW({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)=>I8({accessToken:z.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:z.chatgptAccountId}),hasActiveRateLimitMark:(z)=>X.quotaManager.isRateLimited(z)},{accountKey:J,expectedChatgptAccountId:Y,retry:$});return t6.info("reset redemption outcome",{accountKey:J,code:Q.outcome.kind}),bB(Q,X,Y)}catch(G){let Q=MM(J,G,Y);return t6.info("reset redemption outcome",{accountKey:J,code:Q.code}),Q}}function T$(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===U1?"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 SB(J,X);return{ok:$.eligible,text:`${OM($)}
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 e6.warn("account add rejected (main identity)",{id:Z.id}),new k6("main-account",_B);return e6.info("account added",{id:Z.id}),EB(Z)});return{status:"pending",message:Q,completion:z}}}}function T$(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),e6.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 R$(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}`,N3($.host,$.name,$.enrollment),...J4($.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:y8(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?.(),`${y8(Q)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await J.accept(Q.routeId),await X.changed?.(),`${y8(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?.(),q3(J,z);return J.waitForApproval(X.wait).then(async(Z)=>{await X.changed?.();let W=q3(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:[...J4(J.name,z),"Waiting for the approval; you are told here when it lands."].join(`
108
+ `)}}}]}}}}async function MB(X,J,$){if(!x8(J))return t6(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 xB(J,X);if(!z.eligible)return t6(J,"not_eligible",wB(z));Y=z.chatgptAccountId}if(!Y)return t6(J,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");e6.info("reset redemption decision",{accountKey:J,retry:$});let Q=await cW({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)=>b8({accessToken:z.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:z.chatgptAccountId}),hasActiveRateLimitMark:(z)=>X.quotaManager.isRateLimited(z)},{accountKey:J,expectedChatgptAccountId:Y,retry:$});return e6.info("reset redemption outcome",{accountKey:J,code:Q.outcome.kind}),vB(Q,X,Y)}catch(G){let Q=SM(J,G,Y);return e6.info("reset redemption outcome",{accountKey:J,code:Q.code}),Q}}function C$(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===U1?"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 xB(J,X);return{ok:$.eligible,text:`${EM($)}
109
109
 
110
- ${IB($)}`}}},{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 DB(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 DB(X,J,!0);return{ok:$,text:Y}}}]}))})}}var RB=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],CB=["primary","secondary"];function R$(X){let J={command:u6,title:O$,store:D$(E7(S7(X.store,{...X.rowLocks?{rowLocks:X.rowLocks}:{}}))),...X.extraLocks?{extraLocks:X.extraLocks}:{},accounts:{...X.login?{login:TB(X.login)}:{},...X.protect?{protect:X.protect}:{},...X.describeIdentity?{describeIdentity:X.describeIdentity}:{}},quota:X.quotaCheck?{check:X.quotaCheck}:{},routing:{orderedVariants:RB,formerMainId:U1},limits:{labels:CB},...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?NB(J,X.vault):i9(J),Y=(G)=>{let{sessionId:Q}=G,z=G.notify.bind(G);return{...Q!==void 0?{sessionId:Q}:{},notify:z}};return{command:u6,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:u6,menu:P$(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:u6,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:P$(Z.blockers)};let W=await $.apply(G,z);if(W.ok)await X.afterApply?.();return W}}}function EB(X){let J=[X.primary?.usedPercent,X.secondary?.usedPercent].filter(($)=>$!==void 0);return J.length>0?Math.max(...J):void 0}function FM(X,J){let $=[X.primary,X.secondary].filter((G)=>G!==void 0),Y=$.filter((G)=>V3(G,J));return(Y.length>0?Y:$).sort((G,Q)=>Q.usedPercent-G.usedPercent)[0]?.resetsAt}function PM(X,J){if(!X)return!1;let $=[X.primary,X.secondary].filter((Y)=>Y!==void 0);if($.length===0)return!1;return $.every((Y)=>!V3(Y,J))}async function SB(X,J){let $;try{$=await J.resolveResetTarget(X);let Y=$.accountKey==="main"?void 0:$.chatgptAccountId,[G,Q]=await Promise.all([I8({accessToken:$.accessToken,fetchImpl:J.fetchImpl,now:J.now,accountId:$.chatgptAccountId}),X$(J.fetchImpl,$.accessToken,Y)]),z=M7(Q.credits),Z=fW(Q.credits),W=Q.availableCount??G.resetCreditsAvailable??(Z>0?Z:void 0),B=G.resetCreditsApplicable,H=eJ(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:EB(G),resetTime:FM(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 t6.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 OM(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 IB(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 r6(X,J,$,Y={}){if(Object.keys(Y).length>0)t6.debug("reset step details",{accountKey:X,code:J,...Y});return{ok:J==="reset"||J==="already_redeemed",code:J,text:$}}function MM(X,J,$){if(J instanceof a6){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 r6(X,J.kind,`## Reset credit
110
+ ${wB($)}`}}},{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 MB(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 MB(X,J,!0);return{ok:$,text:Y}}}]}))})}}var IB=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],bB=["primary","secondary"];function E$(X){let J={command:p6,title:_$,store:P$(I7(b7(X.store,{...X.rowLocks?{rowLocks:X.rowLocks}:{}}))),...X.extraLocks?{extraLocks:X.extraLocks}:{},accounts:{...X.login?{login:SB(X.login)}:{},...X.protect?{protect:X.protect}:{},...X.describeIdentity?{describeIdentity:X.describeIdentity}:{}},quota:X.quotaCheck?{check:X.quotaCheck}:{},routing:{orderedVariants:IB,formerMainId:U1},limits:{labels:bB},...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?PB(J,X.vault):i9(J),Y=(G)=>{let{sessionId:Q}=G,z=G.notify.bind(G);return{...Q!==void 0?{sessionId:Q}:{},notify:z}};return{command:p6,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:p6,menu:M$(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:p6,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:M$(Z.blockers)};let W=await $.apply(G,z);if(W.ok)await X.afterApply?.();return W}}}function kB(X){let J=[X.primary?.usedPercent,X.secondary?.usedPercent].filter(($)=>$!==void 0);return J.length>0?Math.max(...J):void 0}function RM(X,J){let $=[X.primary,X.secondary].filter((G)=>G!==void 0),Y=$.filter((G)=>K3(G,J));return(Y.length>0?Y:$).sort((G,Q)=>Q.usedPercent-G.usedPercent)[0]?.resetsAt}function CM(X,J){if(!X)return!1;let $=[X.primary,X.secondary].filter((Y)=>Y!==void 0);if($.length===0)return!1;return $.every((Y)=>!K3(Y,J))}async function xB(X,J){let $;try{$=await J.resolveResetTarget(X);let Y=$.accountKey==="main"?void 0:$.chatgptAccountId,[G,Q]=await Promise.all([b8({accessToken:$.accessToken,fetchImpl:J.fetchImpl,now:J.now,accountId:$.chatgptAccountId}),$$(J.fetchImpl,$.accessToken,Y)]),z=A7(Q.credits),Z=pW(Q.credits),W=Q.availableCount??G.resetCreditsAvailable??(Z>0?Z:void 0),B=G.resetCreditsApplicable,H=J$(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:kB(G),resetTime:RM(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 e6.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 EM(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 wB(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 t6(X,J,$,Y={}){if(Object.keys(Y).length>0)e6.debug("reset step details",{accountKey:X,code:J,...Y});return{ok:J==="reset"||J==="already_redeemed",code:J,text:$}}function SM(X,J,$){if(J instanceof o6){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 t6(X,J.kind,`## Reset credit
112
112
 
113
113
  ${G[J.kind]}
114
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 r6(X,Y,`## Reset credit
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 t6(X,Y,`## Reset credit
116
116
 
117
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
118
 
119
- Code: \`${Y}\``);if(J instanceof W1)return r6(X,J.kind,`## Reset credit
119
+ Code: \`${Y}\``);if(J instanceof W1)return t6(X,J.kind,`## Reset credit
120
120
 
121
121
  No redemption was attempted: reset credit availability could not be loaded.
122
122
 
123
- Code: \`${J.kind}\``);return t6.warn("reset command failed before a known result",{accountKey:X,error:J?.message??String(J)}),r6(X,"error",`## Reset credit
123
+ Code: \`${J.kind}\``);return e6.warn("reset command failed before a known result",{accountKey:X,error:J?.message??String(J)}),t6(X,"error",`## Reset credit
124
124
 
125
- The reset request failed before a known result: internal command failure — see plugin log.`)}async function bB(X,J,$){let{accountKey:Y}=X.target,G=X.outcome.kind;if(X.finalizeStateWriteFailed)return r6(Y,G,`## Reset credit result
125
+ The reset request failed before a known result: internal command failure — see plugin log.`)}async function vB(X,J,$){let{accountKey:Y}=X.target,G=X.outcome.kind;if(X.finalizeStateWriteFailed)return t6(Y,G,`## Reset credit result
126
126
 
127
127
  Account: **${X.target.label}** (\`${Y}\`)
128
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)t6.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&&PM(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?`
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(N){z.error=N?.message??String(N)}let Z=!z.ok&&z.error!==void 0;if(Z)e6.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&&CM(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
130
 
131
- quota re-check failed — see log.`:"";return r6(Y,G,`## Reset credit result
131
+ quota re-check failed — see log.`:"";return t6(Y,G,`## Reset credit result
132
132
 
133
133
  Account: **${X.target.label}** (\`${Y}\`)
134
134
 
@@ -136,37 +136,37 @@ Code: \`${G}\`
136
136
 
137
137
  ${U}${j}${H===void 0?"":`
138
138
 
139
- Remaining applicable credits: **${H}**`}`,{verifiedFresh:B,afterUsedPercent:EB(W?.quota??{}),remainingCredits:H})}if(G==="ambiguous_local")return r6(Y,G,`## Reset credit result
139
+ Remaining applicable credits: **${H}**`}`,{verifiedFresh:B,afterUsedPercent:kB(W?.quota??{}),remainingCredits:H})}if(G==="ambiguous_local")return t6(Y,G,`## Reset credit result
140
140
 
141
141
  Account: **${X.target.label}** (\`${Y}\`)
142
142
 
143
143
  Code: \`${G}\`
144
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 r6(Y,G,`## Reset credit result
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 t6(Y,G,`## Reset credit result
146
146
 
147
147
  Account: **${X.target.label}** (\`${Y}\`)
148
148
 
149
149
  The redemption outcome is unknown (\`${G}\`).
150
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 r6(Y,G,`## Reset credit result
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 t6(Y,G,`## Reset credit result
152
152
 
153
153
  Account: **${X.target.label}** (\`${Y}\`)
154
154
 
155
155
  Code: \`${G}\`
156
156
 
157
- ${Q[G]??"The server returned a no-op result. No reset was confirmed."}`)}var C$=Z0("quota"),kB="the account holds a tombstone from the removed vault custody, not a credential";function _M(X){return X?.status===401}async function Y4(X,J={}){let $=X.whamFn;if(!$)throw Error("whamFn is required for refreshAllQuota");let Y=[],G=X.logger??C$,Q=(K)=>{Y.push(K);let N={pid:process.pid,accountId:K.account,status:K.ok?"ok":"error",...K.error?{error:K.error}:{}};if(K.ok)G.debug("quota refresh succeeded",N);else G.warn("quota refresh failed",N)},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((N)=>typeof N==="number"&&Number.isFinite(N)&&N<=X.now()&&X.now()-N<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(C6(K)){if(q=z9(U),!q)Q({account:"main",ok:!1,error:T0(K)?kB:"main account row is missing from the account pool"})}else if(K.type==="oauth"){let N=W&&j!==void 0&&W.main.mainAccountId===j?W.main.quota:void 0;if(H(X.quotaManager.peekMainForPolicy(j)?.checkedAt,N?.primary?.checkedAt,N?.secondary?.checkedAt,N?.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:e0(K)})}if(U)for(let K of U.accounts){let N=q!==void 0&&K===q;if(!N&&J.accountKey&&(J.accountKey==="main"||K.id!==J.accountKey))continue;if(!N&&X.isOAuthAccountFn(K)&&G9(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=N?K.accountId??j:void 0,O=(_,C,L)=>{if(N)X.quotaManager.setMain(C,_,F,!0);else X.quotaManager.setFallback(K.id,_,C,!0,L)};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,L=N?W&&F!==void 0&&W.main.mainAccountId===F?W.main.quota:void 0:_&&C!==void 0&&_.accountId===C?_.quota:void 0;if(H(N?X.quotaManager.peekMainForPolicy(F)?.checkedAt:X.quotaManager.peekFallbackForPolicy(K.id,C)?.checkedAt,L?.primary?.checkedAt,L?.secondary?.checkedAt,L?.checkedAt)){Q({account:K.id,ok:!0});continue}if(X.respectBackoff&&(N?X.quotaManager.isBackedOff():X.quotaManager.isFallbackBackedOff(K.id,K.access))){Q({account:K.id,ok:!0});continue}let P=K.lastRefreshError;if(r0(P,K.refresh,X.now())){Q({account:K.id,ok:!1,error:e8(P,X.now()),permanent:!0});continue}if(T0(K)){Q({account:K.id,ok:!1,error:kB});continue}let A;try{A=N?await X.fallbackManager.refreshAccount(K,U,{asPoolMain:!0}):await X.fallbackManager.refreshAccount(K,U)}catch(k){C$.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:K.id,error:e0(k)}),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(k){if(!_M(k))throw k;if(C$.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:K.id}),A=await X.fallbackManager.refreshAccount(K,U,N?{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:e0(_)})}}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}import{types as AM}from"node:util";var TM=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,RM=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function hB(X){return X.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,(J,$,Y)=>{if($)return String.fromCharCode(Number.parseInt($,16));return{b:"\b",f:"\f",n:`
158
- `,r:"\r",t:"\t"}[Y]??Y??J})}function CM(X,J){if(!J)return X;let $=X.split(J).join("[credential]"),Y=J.replace(/\s/g,"");if(!Y)return $;let G=$.replace(/\s/g,"");if(!G.includes(Y))return $;let Q=[];for(let W=0;W<$.length;W++){let B=$[W]??"";if(!/\s/.test(B))Q.push(W)}let z=[],Z=0;for(let W=G.indexOf(Y);W>=0;W=G.indexOf(Y,W+Y.length)){let B=Q[W]??Z,H=(Q[W+Y.length-1]??B)+1;z.push($.slice(Z,B),"[credential]"),Z=H}return z.length?z.join("")+$.slice(Z):$}function xB(X,J){let $=CM(X,J);return yB($).replaceAll("***REDACTED***","[credential]")}function G4(X,J){let $=xB(X,J),Y=hB($),G=xB(Y,J);return G===Y?$:G}function wB(X){let J=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(X);if(!J)return;let $=J[3]??"",Y=(J[2]??"")+$,G=0;while(Y[G]==="0")G++;if(G===Y.length)return"0";let Q=Y.length;while(Y[Q-1]==="0")Q--;let z=J[4]??"0",Z=z.startsWith("-")||z.startsWith("+")?1:0;while(z[Z]==="0")Z++;let W=z.slice(Z)||"0";if(W.length>16)return;let B=BigInt((z.startsWith("-")?"-":"")+W)-BigInt($.length)+BigInt(Y.length-Q);return`${J[1]}${Y.slice(G,Q)}e${B}`}function fB(X,J){let $=J?wB(J):void 0;return X.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(Y)=>{if(!Y.startsWith('"'))return J&&(Y===J||$!==void 0&&wB(Y)===$||(J==="Infinity"||J==="-Infinity")&&/^[-\d]/.test(Y)&&String(Number(Y))===J)?'"[credential]"':Y;let G=hB(Y.slice(1,-1)),Q=G4(G,J);return Q===G?Y:JSON.stringify(Q)})}function E$(X,J){let $=fB(X,J);try{return JSON.parse(X),$}catch{return G4($,J)}}var EM=16384,SM=65536,IM=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function bM(X){try{let J=X6(JSON.parse(X),"request_id");if(typeof J==="string")return J;if(typeof J!=="number")return;let $=0,Y,G=!0,Q=!1,z;for(let Z of X.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let W=Z[0];if(W==="{"||W==="["){$++;continue}if(W==="}"||W==="]"){$--;continue}if($!==1)continue;if(W===","){G=!0,Q=!1,Y=void 0;continue}if(W===":"){Q=!0;continue}if(G&&W.startsWith('"')){Y=JSON.parse(W),G=!1;continue}if(Q&&Y==="request_id"&&!W.startsWith('"'))z=W;Q=!1}return z}catch{return}}function kM(X,J){let $=E$(X,J);if(Buffer.byteLength($,"utf8")<=SM)return $;let Y=IM.flatMap((Q)=>Q.exec($)?.[0]??[]);for(let Q of["FreeUsageLimitError","GoUsageLimitError"])if($.includes(Q))Y.push(Q);let G={retry:Y};try{let Q=JSON.parse($);if(X6(Q,"type")==="error")G.type="error";let z=X6(Q,"error"),Z={};for(let B of["code","type"]){let H=X6(z,B);if(typeof H==="string")Z[B]=H.slice(0,256)}if(Object.keys(Z).length)G.error=Z;let W={};for(let B of["workspace","limitName"]){let H=X6(X6(Q,"metadata"),B);if(typeof H==="string")W[B]=H.slice(0,256)}if(Object.keys(W).length)G.metadata=W}catch{}return JSON.stringify(G)}function I7(X){if(!X||typeof X!=="object")return!1;let J=X;for(let $=0;J&&$<16;$++){if(AM.isProxy(J))return!1;J=Object.getPrototypeOf(J)}return J===null}function X6(X,J){if(!I7(X))return;let $=Object.getOwnPropertyDescriptor(X,J);return $&&"value"in $?$.value:void 0}function D3(X,J){return G4(X,J).slice(0,EM)}function Q4(X,J){let $=Object.getOwnPropertyDescriptor(X,J)?.get;if(!$)throw Error(`Missing native ${J} accessor`);return $}var xM=Q4(DOMException.prototype,"message"),wM=Q4(DOMException.prototype,"name");function K8(X,J){let $=X6(X,"message"),Y=X6(X,"name");if(I7(X)&&X instanceof DOMException)try{$=xM.call(X),Y=wM.call(X)}catch{}let G=Error(D3(typeof $==="string"?$:typeof X==="string"?X:"Provider request failed",J));for(let U of Object.getOwnPropertyNames(G))if(U!=="message")Reflect.deleteProperty(G,U);Object.defineProperty(G,"name",{value:typeof Y==="string"?D3(Y,J):"Error",configurable:!0,writable:!0});let Q=(U,j,q)=>{let K=X6(U,q);if(typeof K==="string"||typeof K==="number"&&Number.isFinite(K)||typeof K==="boolean")Object.defineProperty(j,q,{value:typeof K==="string"?D3(K,J):K,enumerable:!0,configurable:!0,writable:!0})};for(let U of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=X6(X,U);if(typeof j==="number"&&Number.isFinite(j))Q(X,G,U)}for(let U of["code","type","isRetryable"])Q(X,G,U);for(let U of["error","data"]){let j=X6(X,U),q=Object.create(null);for(let N of["type","code","message","resets_at","resets_in_seconds"])Q(j,q,N);let K=X6(j,"error");if(I7(K)){let N=Object.create(null);for(let F of["type","code","message","resets_at","resets_in_seconds"])Q(K,N,F);q.error=N}if(Object.keys(q).length)Object.defineProperty(G,U,{value:q,enumerable:!0})}let z=X6(X,"responseHeaders");if(z&&typeof z==="object"){let U={};for(let j of["retry-after-ms","retry-after"]){let q=X6(z,j);if(typeof q==="string")U[j]=D3(q,J)}Object.defineProperty(G,"responseHeaders",{value:U,enumerable:!0})}let Z=X6(X,"responseBody");if(typeof Z==="string")Object.defineProperty(G,"responseBody",{value:kM(Z,J),enumerable:!0});let W=X6(X,"request_id"),B=X6(z,"x-request-id"),H=typeof W==="string"?W:typeof B==="string"?B:typeof Z==="string"?bM(E$(Z,J)):void 0;if(typeof H==="string")Object.defineProperty(G,"request_id",{value:D3(H,J),enumerable:!0});for(let U of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(U);if(X6(X,j)===!0)Object.defineProperty(G,j,{value:!0})}return G}function vM(X,J){if(!X.includes("error")&&(!X.includes("\\u00")||!TM.test(X)&&!RM.test(X)))return X;let $;try{$=JSON.parse(X)}catch{return X}if($?.type==="error"||$?.error||$?.response?.error)return fB(X,J);return X}var yM=Q4(Response.prototype,"status"),hM=Q4(Response.prototype,"statusText"),fM=Q4(Response.prototype,"headers"),gM=Q4(Response.prototype,"body"),mM=Response.prototype.text,vB=Headers.prototype.entries;async function j1(X,J,$="http"){try{let q=function(K){let N=j&&K.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,N+K.slice(N.length).replace(/^data: ?([^\r\n]*)/gm,(F,O)=>F.slice(0,F.length-O.length)+vM(O,J))};if(!I7(X))throw Error("Invalid provider response");let Y=yM.call(X),G=fM.call(X),Q=gM.call(X),z=new Headers;for(let[K,N]of vB.call(G))z.append(K,N);let Z={status:Y,statusText:G4(hM.call(X),J),headers:z};if(Y<200||Y>299){for(let[N,F]of vB.call(G)){if(G4(N,J?.toLowerCase())!==N){Z.headers.delete(N);continue}try{Z.headers.set(N,G4(F,J))}catch{Z.headers.delete(N)}}Z.headers.delete("content-length");let K=await mM.call(X);return new Response(E$(K,J),Z)}if(!Q||$==="http")return X;Z.headers.delete("content-length");let W=ReadableStream.prototype.getReader.call(Q),B=new TextDecoder("utf-8",{ignoreBOM:!0}),H=new TextEncoder,U="",j=!0;return new Response(new ReadableStream({async pull(K){try{for(;;){let N=await W.read();U+=B.decode(N.value,{stream:!N.done});let F=!1;for(;;){let O=/\r?\n\r?\n/.exec(U);if(!O)break;let _=O.index+O[0].length;K.enqueue(H.encode(q(U.slice(0,_)))),U=U.slice(_),F=!0}if(N.done){if(U)K.enqueue(H.encode(q(U)));K.close();return}if(F)return}}catch(N){K.error(K8(N,J))}},async cancel(K){try{await W.cancel(K)}catch(N){throw K8(N,J)}finally{W.releaseLock()}}}),Z)}catch(Y){throw K8(Y,J)}}import{readFile as s_}from"node:fs/promises";import{readFileSync as uM}from"node:fs";import{homedir as pM,tmpdir as cM}from"node:os";import{join as x7}from"node:path";var lM="https://chatgpt.com/backend-api/codex/responses",dM="openai-auth.json",I9={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 w7(){let X=process.env[I9.configDir]?.trim();if(X)return X;return x7(process.env.XDG_CONFIG_HOME||x7(pM(),".config"),"opencode")}function V0(){return process.env[I9.configFile]?.trim()||x7(w7(),dM)}function iM(){try{let X=JSON.parse(uM(V0(),"utf8"));return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:{}}catch{return{}}}function nM(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 b7(X,J,$){let Y=nM(X);if(Y!==void 0)return Y;if(typeof J==="boolean")return J;return $}function sM(){let X=iM(),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:b7(I9.webSockets,X.webSockets,!1),rawWebSocket:b7(I9.rawWebSocket,X.rawWebSocket,!1),responsesLite:b7(I9.responsesLite,X.responsesLite,!1),dump:b7(I9.dump,J,!1),dumpDir:process.env[I9.dumpDir]?.trim()||(typeof X.dumpDir==="string"&&X.dumpDir.trim()?X.dumpDir.trim():x7(cM(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[I9.codexApiEndpoint]?.trim()||(typeof X.codexApiEndpoint==="string"&&X.codexApiEndpoint.trim()?X.codexApiEndpoint.trim():lM)}}var k7;function p6(){if(!k7)k7=sM();return k7}function gB(){return k7=void 0,p6()}import{realpathSync as mB}from"node:fs";import{homedir as aM}from"node:os";import{basename as oM,dirname as rM,join as y7,resolve as pB}from"node:path";function tM(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return y7(process.env.XDG_CONFIG_HOME||y7(aM(),".config"),"opencode")}function cB(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||y7(tM(),uJ)}function v7(X,J){let $=pB(X);return J==="win32"||J==="darwin"?$.toLowerCase():$}function uB(X){try{return mB.native(X)}catch{try{return y7(mB.native(rM(X)),oM(X))}catch{return}}}function eM(X,J,$=process.platform){if(v7(X,$)===v7(J,$))return!0;let Y=uB(X),G=uB(J);return Y!==void 0&&G!==void 0&&v7(Y,$)===v7(G,$)}function S$(X=cB()){let J=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(J){if(eM(X,J))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${pB(X)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return J}return pJ(X)}function M0(X=cB()){return{configPath:X,statePath:S$(X)}}import{createHash as R_}from"node:crypto";import{readFile as C_}from"node:fs/promises";import{homedir as E_}from"node:os";import{join as ZH,resolve as S_}from"node:path";import{createHash as X_}from"node:crypto";import{readFileSync as J_}from"node:fs";import{readFile as $_}from"node:fs/promises";import{resolve as Y_}from"node:path";var z4="openai",G_="common-auth-placeholder:v1:openai",q1=Object.freeze({type:"oauth",access:"",refresh:G_,expires:0});function O3(X){if(!e6(X))return!1;return X.type===q1.type&&X.access===q1.access&&X.refresh===q1.refresh&&X.expires===q1.expires}var h7="openaiAuthPool",Q_=120000,nB="pool-migration",b$="slot-transfer-origin-unknown",k$="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.",g7=Object.freeze({mainRefreshTtlMs:Q_,fallbackTtlMs:aJ,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function f7(X,J,$){return X.kind==="placeholder"&&!J&&!$.pending}class F3 extends Error{constructor(X){super(`timed out waiting for the legacy ${X} lock`);this.name="LegacyLockContention"}}function e6(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}function z_(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:{...g7,...X.legacyLocks},leaseWait:X.leaseWait??{timeoutMs:4000,pollMs:50},store:Q8({provider:z4,configPath:X.paths.configPath,statePath:X.paths.statePath,quota:m8,now:J,...X.store}),onStep:async($)=>{await X.onStep?.($)}}}async function W4(X){let J;try{J=await $_(X,"utf8")}catch(Y){if(Y.code==="ENOENT")return{};throw Y}let $=JSON.parse(J);if(!e6($))throw Error("config root is not an object");return $}async function P3(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 F3(J);await X.sleep(X.locks.retryMs)}}async function sB(X,J,$={}){let Y={...g7,...$},G=performance.now();for(;;){let Q=await g0({name:g8,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 F3(g8);await new Promise((z)=>setTimeout(z,Y.retryMs))}}async function M3(X,J){let $=X.locks.saveTtlMs,Y=await P3(X,"save",X.paths.configPath,$);try{let G=await P3(X,"save",X.paths.statePath,$);try{let Q=await W4(X.paths.configPath);if(!await J(Q))return;await M6(X.paths.configPath,Q,{beforeRename:async()=>{await Y.assertOwned(),await G.assertOwned()}})}finally{await G.release().catch(()=>{})}}finally{await Y.release().catch(()=>{})}}function Z_(X){if(!e6(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 aB(X,J){if(!e6(X)||!J)return!1;return q6(X).pending?.credentialFingerprint===$8({type:"oauth",refresh:J})}function oB(X,J){let $;try{$=JSON.parse(J_(X,"utf8"))}catch{return!1}return aB($,J)}class m7 extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var W_=600000;async function rB(X,J,$={}){let Y=$.now??Date.now,G=(W)=>{let B=q6(W).pending;return B&&aB(W,J)&&Y()-B.recordedAt>=W_?B:void 0},Q=G(await W4(X.configPath));if(!Q)return!1;let z={...g7,...$.legacyLocks},Z=await g0({name:nB,path:X.configPath,ttlMs:z.mainRefreshTtlMs,now:Y});if(!Z)return!1;try{let W=await W4(X.configPath),B=q6(W).migratedAt!==void 0,H=await Q8({provider:z4,configPath:X.configPath,statePath:X.statePath,quota:m8,now:Y}).read();if(B&&H.status!=="ready")return!1;let U;if(H.status==="ready"){let q=H.rows.find((N)=>N.id===Q.rowId&&!N.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?v$({type:"oauth",access:$.slotAccess,refresh:J}):Q.slotFingerprint}let j=!1;if(await M3({paths:X,now:Y,locks:z,sleep:(q)=>new Promise((K)=>setTimeout(K,q))},(q)=>{let K=q6(q),N=G(q);if(!N||N.recordedAt!==Q.recordedAt)return!1;let{pending:F,...O}=K;return u7(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 q6(X){let J=X[h7];if(!e6(J))return{};let $=Z_(J.pending);return{...typeof J.migratedAt==="number"?{migratedAt:J.migratedAt}:{},...$?{pending:$}:{},...typeof J.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:J.declinedSlotFingerprint}:{}}}function u7(X,J){let Y={...e6(X[h7])?X[h7]:{}};for(let G of["migratedAt","pending","declinedSlotFingerprint"])delete Y[G];Object.assign(Y,J),X[h7]=Y}function B_(X){let J=X?V6(X):void 0;return J?U6(J):void 0}function H_(X){let J=v$({type:"oauth",...X}),$=B_(X.access);return{kind:"real",credential:X,fingerprint:J,credentialFingerprint:$8({type:"oauth",refresh:X.refresh}),...$?{identity:$}:{}}}function tB(X){if(O3(X))return{kind:"placeholder",...e6(X)&&typeof X.accountId==="string"?{origin:X.accountId}:{}};let J=QH(X);if(!J?.refresh.trim())return{kind:"empty"};return H_(J)}async function _3(X){let J=await zH({client:{auth:{get:($)=>X.slot.get($),all:()=>X.slot.all()}},now:X.now,sleep:X.sleep});if(J.kind==="real")return tB(J.oauth);return J.kind==="slot-absent"||J.kind==="indeterminate"?{kind:J.kind}:{kind:J.kind}}async function p7(X,J){if(!O3(J))return!1;let $=await W4(X.configPath),Y=await Q8({provider:z4,configPath:X.configPath,statePath:X.statePath,quota:m8}).read();if(Y.status==="error")return!1;let G=Y.status==="ready"?Y.rows.some((Q)=>Q.id==="main"):Y.roster.some((Q)=>e6(Q)&&Q.id==="main");return f7({kind:"placeholder"},G,q6($))}async function V_(X){let J=X.now()+X.leaseWait.timeoutMs;for(;;){let $=await _3(X);if($.kind!=="real")return $;if(!await eB(X,$.credential.refresh))return $;if(X.now()>=J)return{kind:"retry"};await X.sleep(X.leaseWait.pollMs)}}async function eB(X,J){let $=await b0(X.paths),Y=$?.refresh?.mainRefreshLeaseUntil;return Boolean(Y&&Y>X.now()&&$?.refresh?.mainRefreshLeaseTokenHash===z8(J))}function U_(X){return X.length>0&&X.trim()===X&&!["__proto__","constructor","prototype","main"].includes(X)}function K_(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&&U_($.identity)&&!W.has($.identity)?$.identity:G()),operation:"add",rowFingerprint:null,...Q,carryLegacyMain:!1}}function j_(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:{...K_(X,$,Y,G,z),slotFingerprint:Y.fingerprint,credentialFingerprint:Y.credentialFingerprint,recordedAt:Q},credential:Y.credential,fresh:!0}}async function q_(X,J,$){let Y={type:"oauth",access:$.access,refresh:$.refresh,...$.expires!==void 0?{expires:$.expires}:{}},G=J.identity?{identity:J.identity}:{},Q={extraLocks:f8(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 N_(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 L_(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 D_(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===k6(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 L_(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 dJ(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 Z4(X,J,$={}){await M3(X,(Y)=>{let G=q6(Y);if(delete Y.mainAccountId,J==="migrate"&&G.migratedAt===void 0)F_(Y);return u7(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 F_(X){let J=X.routing;if(J===void 0)X.routing={mode:"main-first"};else if(e6(J)&&J.mode===void 0)X.routing={...J,mode:"main-first"}}async function x$(X){await M3(X,(J)=>{let $=q6(J);if(!$.pending)return!1;let{pending:Y,...G}=$;return u7(J,G),!0})}async function P_(X,J){await M3(X,($)=>{let Y=q6($);if(J.identity)$.mainAccountId=J.identity;return u7($,{...Y,pending:J}),!0})}async function O_(X,J,$,Y){let G=await P3(X,g8,X.paths.configPath,X.locks.mainRefreshTtlMs);try{return await M_(X,J,$,Y)}finally{await G.release().catch(()=>{})}}async function M_(X,J,$,Y){let G=(B)=>({status:"completed",rowId:$.rowId,operation:Y,placeholder:B}),Q=await _3(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!==I$(X))return{status:"foreign-placeholder"};return await Z4(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 x$(X),await X.onStep("after-record-clear"),{status:"restart"};if(Q.kind!=="real"||Q.fingerprint!==$.slotFingerprint)return await Z4(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:z4}}),Z=z===void 0||z===null?void 0:tB(z);if(Z?.kind!=="real"||Z.fingerprint!==$.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await X.slot.set({path:{id:z4},body:{...q1,accountId:I$(X)}})}catch(B){if(B instanceof d7)return{status:"retry",reason:"slot-changed"};throw B}await X.onStep("after-placeholder-write");let W=await X.slot.get({path:{id:z4}});if(!O3(W))return{status:"retry",reason:"placeholder-overwritten"};if(e6(W)&&W.accountId===void 0)return{status:"untagged-placeholder"};if(e6(W)&&W.accountId!==I$(X))return{status:"foreign-placeholder"};return await Z4(X,J),await X.onStep("after-record-clear"),G("written")}async function __(X,J,$){let{record:Y}=$;if($.fresh)await P_(X,Y),await X.onStep("after-record-write");if(await eB(X,$.credential.refresh))return{status:"restart"};let G=await _3(X);if(G.kind!=="real"||G.fingerprint!==Y.slotFingerprint)return{status:"restart"};return await q_(X,Y,$.credential),await X.onStep("after-row-write"),XH(X,J,Y,$.fresh?Y.operation:"resumed")}async function XH(X,J,$,Y){let G=await N_(X,$);if(!G)return{status:"retry",reason:"verify-failed"};if(await X.onStep("after-verify"),$.carryLegacyMain)await D_(X,G),await X.onStep("after-carry-over");let Q=await O_(X,J,$,Y);if(Q.status==="untagged-placeholder"){await X.store.disable($.rowId,b$,{extraLocks:f8(X.paths,$.rowId,X.locks),attribution:{credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}}}),await Z4(X,J);let z=`${X.paths.configPath}\x00${$.rowId}`;if(!iB.has(z))iB.add(z),X.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${k$}`,{rowId:$.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(Q.status!=="foreign-placeholder")return Q;return await X.store.remove($.rowId,{extraLocks:f8(X.paths,$.rowId,X.locks),protect:(z,Z)=>Z.row?.fingerprint!==$.credentialFingerprint?"the transfer row changed before rollback":void 0}),await x$(X),await w$(X),{status:"refused",reason:"placeholder-without-main"}}var lB=new Set,dB=new Set,iB=new Set;function I$(X){return`openai-auth-pool:${X_("sha256").update(Y_(X.paths.configPath)).digest("hex")}`}async function A_(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 JH(X,J,$){let Y=z_(X),G=Y.slot.migrationDisabledReason?.();if(G){let B=Y.slot.path??B4();if(!dB.has(B))dB.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 W4(Y.paths.configPath)}catch(B){return{status:"error",reason:B instanceof Error?B.message:String(B)}}let z=await $H(Y,J,Q);if(z){if(z.status==="already-migrated"&&"mainAccountId"in Q)await w$(Y);return z}if($){let B=await A_($);if(B.length>0){let H=`${Y.paths.configPath}\x00${B.map((U)=>`${U.pid}@${U.version}`).join(",")}`;if(!lB.has(H))lB.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 P3(Y,"pool-slot-transfer",Y.slot.path??B4(),Y.locks.mainRefreshTtlMs),Z=await P3(Y,nB,Y.paths.configPath,Y.locks.mainRefreshTtlMs)}catch(B){if(await W?.release().catch(()=>{}),B instanceof F3)return{status:"retry",reason:"lock-contention"};throw B}try{return await T_(Y,J)}catch(B){if(B instanceof F3)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 $H(X,J,$){let Y=q6($);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&&f7(await _3(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 T_(X,J){let $;for(let Y=0;Y<4;Y++){let G=await W4(X.paths.configPath),Q=await $H(X,J,G);if(Q){if(Q.status==="already-migrated")await w$(X);return Q}let z=await X.store.read(),Z=q6(G);if(z.status==="pending-migration"){if(f7(await _3(X),z.roster.some((U)=>e6(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 V_(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(f7(W,z.rows.some((U)=>U.id==="main"),Z))return{status:"refused",reason:"placeholder-without-main"};let B=j_(J,Z,z.rows,W,$,X.now(),X.newId);if(B.kind==="nothing"){if(J==="migrate")await Z4(X,J),await X.onStep("after-marker-write");return{status:"nothing-to-import",slot:B.slot}}if(B.kind==="drop-record"){await x$(X),await X.onStep("after-record-clear");continue}if(B.kind==="ambiguous")return await Z4(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 XH(X,J,B.record,"resumed"):await __(X,J,B);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function w$(X){await M3(X,(J)=>{if(!("mainAccountId"in J))return!1;if(q6(J).pending)return!1;return delete J.mainAccountId,!0})}function c7(X){return JH(X,"migrate",X.fence)}function l7(X){return JH(X,"adopt")}class YH extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function f8(X,J,$={}){let Y={...g7,...$},G={renew:Y.renew,timeoutMs:Y.timeoutMs,retryMs:Y.retryMs,...Y.renewIntervalMs!==void 0?{renewIntervalMs:Y.renewIntervalMs}:{}};return[{name:g8,path:X.configPath,ttlMs:Y.mainRefreshTtlMs,...G},{name:oJ(J),path:X.configPath,ttlMs:Y.fallbackTtlMs,...G}]}async function GH(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=z8(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 YH}return $(W,B)};return X.store.refresh(J,Z,{...Y,extraLocks:f8(X.paths,J,X.legacyLocks)})}var I_="openai",WH=250,g8="main-refresh";function v$(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 R_("sha256").update(Y(J)).update(J).update(Y($)).update($).digest("hex")}function KH(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 QH(X){let J=KH(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 A3(X){if(N1(X)&&X.type==="api"&&typeof X.key==="string")return{kind:"api"};let J=KH(X);if(!J)return{kind:"indeterminate"};return T0(J)?{kind:"tombstone",oauth:J}:{kind:"real",oauth:J}}async function BH(X){return X.auth.get({path:{id:I_}})}async function HH(X){return Object.keys(await X.auth.all()).length>0}async function zH(X){let J=await BH(X.client);if(J!==void 0)return A3(J);let $=await HH(X.client),Y=X.now();if(await X.sleep(WH),X.now()-Y<WH)return{kind:"indeterminate"};let G=await BH(X.client);if(G!==void 0)return A3(G);let Q=await HH(X.client);return $&&Q?{kind:"slot-absent"}:{kind:"indeterminate"}}function B4(X=process.env,J=E_()){let $=X.XDG_DATA_HOME||ZH(J,".local","share");return ZH($,"opencode","auth.json")}function N1(X){return!!X&&typeof X==="object"&&!Array.isArray(X)}var VH=(X)=>X===void 0||typeof X==="string";function b_(X){if(!N1(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&&VH(X.accountId)&&VH(X.enterpriseUrl);case"api":return typeof X.key==="string"&&(X.metadata===void 0||N1(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 y$(X,J=process.env){let $=J.OPENCODE_AUTH_CONTENT;if($)try{let G=JSON.parse($);return N1(G)?G:{}}catch{}let Y;try{Y=JSON.parse(await C_(X,"utf8"))}catch{return{}}if(!N1(Y))return{};return Object.fromEntries(Object.entries(Y).filter(([,G])=>b_(G)))}function UH(X){if(!X.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(X.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class d7 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function k_(X){let J=X.env??process.env,$=X.path??B4(J),Y=new Map;return{path:S_($),migrationDisabledReason:()=>UH(J)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(G){let Q=(await y$($,J))[G.path.id];return Y.set(G.path.id,JSON.stringify(Q)),Q},async all(){return y$($,J)},async set(G){if(UH(J))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let Q=(await y$($,J))[G.path.id];if(O3(G.body)&&(!Y.has(G.path.id)||Y.get(G.path.id)!==JSON.stringify(Q)))throw new d7;let z=await X.set(G);if(N1(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 jH(X,J={}){let $=N1(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:k_({...J,set:(G)=>Y.call($,G)})}}import{readFileSync as x_}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 v_(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 H4(X,J={}){return Q8({provider:"openai",configPath:X.configPath,statePath:X.statePath,quota:m8,...J})}function h$(X){try{let J=JSON.parse(x_(X,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return q6(J).migratedAt!==void 0}catch{return!1}}async function i7(X,J){if(!h$(X.configPath))return;let $=await J.read();return $.status==="ready"?$.rows:void 0}function n7(X,J){if(X===U8)return w_;if(q6(J.config).pending?.rowId===X)return v_(X);return}function y_(X,J){return f8(X,U8,J.legacyLocks).filter(($)=>$.name===g8)}function W9(X,J={}){return y_(X,J)}var V4="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 L1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function qH(X){let J=X.storage,$=z9(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)&&!r0(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 h_,readFile as f_}from"node:fs/promises";import{homedir as g_}from"node:os";import{join as U4}from"node:path";function LH(){return process.env.XDG_STATE_HOME||U4(g_(),".local","state")}function m_(X=LH()){return U4(X,"cortexkit","openai-auth","processes")}function u_(X=LH()){return U4(X,"cortexkit","openai-auth","rpc")}function p_(X){try{return process.kill(X,0),!0}catch(J){return J.code==="EPERM"}}function NH(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 c_(X,J){let $=NH(X),Y=NH(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 f$(X){try{return{ok:!0,names:await h_(X)}}catch(J){let $=J.code;if($==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:$,error:`${X}: ${String(J)}`}}}async function l_(X,J){let $;try{$=await f_(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 K4(X){let J=X.isAlive??p_,$=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 N=K.exec(q),F=N?Number(N[1]):Number.NaN;return Number.isSafeInteger(F)&&F>=1?F:void 0},Z=m_(X.stateHome),W=new Set,B=await f$(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 N=U4(Z,q),F=await l_(N,K);if(F.kind==="gone")continue;if(W.add(K),!Q(K))continue;if(F.kind==="unreadable"){G({pid:K,version:"unknown",detail:N});continue}let O=c_(F.version,X.currentVersion);if(O===void 0||O<0)G({pid:K,version:F.version,detail:N})}let H=X.rpcDir??u_(X.stateHome),U=await f$(H);if(!U.ok)G({pid:"unknown",version:"unknown",detail:U.error});for(let q of U.ok?U.names:[]){if(!s7(q))continue;let K=U4(H,q),N=await f$(K);if(!N.ok){if(N.code==="ENOTDIR")continue;G({pid:"unknown",version:"unknown",detail:N.error});continue}for(let F of N.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:U4(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 b9="1.0.2";import{readFile as FH}from"node:fs/promises";function a7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}async function PH(X){let J=await cJ(X.configPath),$=[];try{let G=JSON.parse(await FH(X.statePath,"utf8"));if(a7(G)){let Q=G.accounts;if(a7(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 d_(X){try{let J=JSON.parse(await FH(X.configPath,"utf8"));return a7(J)&&a7(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var DH="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 OH(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 i_(X,J){let $=X.lastRefreshError;return r0($,X.refresh,J)&&$!==void 0&&$.nextRetryAt!==void 0&&$.nextRetryAt-$.checkedAt>=E5}function n_(X){let J=[],$=[],Y=X.now??Date.now(),G=OH(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. ${DH}`});else if(C6(X.auth)){if(!z9(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. ${DH}`})}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(!i_(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 MH(X){let J=($)=>{if($.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(C6(await X.readAuth()))return;let Y=OH(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(),d_(X.paths)]),z=n_({auth:G.type==="missing"?void 0:G,storage:$,orphanStateIds:Y.orphanStateIds,retiredCustodyMode:Q,now:X.now()}),Z=await Q8({provider:"openai",quota:m8,configPath:X.paths.configPath,statePath:X.paths.statePath}).read();if(Z.status==="ready")for(let W of Z.rows){if(W.disabledReason!==b$)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. ${k$}`})}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 a_=AH,_H="OpenAI accounts",o_="ChatGPT accounts in the vault",r_="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 t_(){let{redirectUri:X}=await y5(),J=await w5(),$=k2(crypto.getRandomValues(new Uint8Array(32)).buffer),Y=v5(X,J,$),G=h5(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{J9($)}}}}async function e_(X){let{deviceData:J,url:$,instructions:Y}=await f5(X);return{url:$,instructions:Y,method:"auto",async callback(){try{let G=await g5(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 TH({client:X,getAuth:J,getPaths:$=()=>M0(V0()),fetchImpl:Y=fetch,packageVersion:G=b9,dependencies:Q,onMainSlotWritten:z,vault:Z}){let W={authorizeBrowser:Q?.authorizeBrowser??t_,authorizeHeadless:Q?.authorizeHeadless??(()=>e_(G)),beginAccountLogin:Q?.beginAccountLogin??x2,loadAccounts:Q?.loadAccounts??b0,mutateAccounts:Q?.mutateAccounts??L7,readStoreIds:Q?.readStoreIds??PH,openBrowser:Q?.openBrowser??a_,now:Q?.now??Date.now,openAccountPool:Q?.openAccountPool??H4,migrationBlockers:Q?.migrationBlockers??(async()=>{let L=await K4({currentVersion:G});return L.open?[]:L.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 L=$(),P=W.openAccountPool(L);if((await P.read()).status==="ready")return V$(P);return((await W.loadAccounts(L))?.accounts.length??0)>0},U=async(L)=>{if(await sB($().configPath,async()=>{if(Z&&await Z.authority()!=="local")return!1;if(C6(await B()))return!1;return await X.auth.set({path:{id:"openai"},body:{type:"oauth",...L}}),!0}))await z?.().catch(()=>{})},j=(L)=>({begin:async({headless:P,signal:A})=>{if(Z&&await Z.authority()!=="local")throw Error(h8);let T=await W.beginAccountLogin({version:G,headless:P,...A?{signal:A}:{}});return{url:T.url,instructions:T.instructions,completion:T.completion.then(async(k)=>{if(Z&&await Z.authority()!=="local")throw Error(h8);let p=await L.read(),i=p.status==="ready"?p.rows.find((w)=>w.id===U8)?.identity:void 0;if(k.accountId&&i&&k.accountId===i)throw Error("that account is already the OpenCode main credential");return{id:k.id,credential:{type:"oauth",refresh:k.refresh,...k.access!==void 0?{access:k.access}:{},...k.expires!==void 0?{expires:k.expires}:{}},...k.accountId!==void 0?{identity:k.accountId}:{},...k.label!==void 0?{label:k.label}:{}}})}},openBrowser:(P)=>W.openBrowser(P)}),q=async(L)=>{if(Z&&await Z.authority()!=="local")throw Error(h8);let P=L.credential;if(P?.type!=="oauth"||!P.access)throw Error("no usable access token for a quota check");let A=await I8({accessToken:P.access,fetchImpl:Y,now:W.now,...L.identity?{accountId:L.identity}:{},accountKey:L.id});return S9(A,W.now(),!0)},K=(L)=>MH({paths:$(),migrated:L,readAuth:B,loadAccounts:W.loadAccounts,readStoreIds:W.readStoreIds,mutateAccounts:W.mutateAccounts,setMainAuth:U,now:W.now}),N=(L,P)=>({title:_H,store:S7(P,{rowLocks:(A)=>f8(L,A)}),...W.terminal?{terminal:W.terminal}:{},login:j(P),protect:(A,T)=>n7(A,T),extraLocks:W9(L),pollQuota:q,doctor:K(!0),status:async()=>{let A=await Z?.status();if(Z&&await Z.authority()!=="local"&&A)return[K3(Z.host,Z.name,A.enrollment)];return[`Routing: ${(await W.loadAccounts(L))?.routing?.mode??"main-first"}`,...Z?[K3(Z.host,Z.name,(await Z.status()).enrollment)]:[]]},...Z?{extraActions:[F(Z)]}:{}}),F=(L)=>{let P=L.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 L.authority();if(P){if(T!=="local")await L.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 ${L.name}…`);let k,p=await L.waitForApproval({...W.vaultWait,onPending:(i)=>{let X0=i.state==="pending"?i.requestId??i.retryCode??"":i.state;if(X0===k)return;k=X0;for(let w of J4(L.name,i))A.print(w);A.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});A.print(j3(L,p).text)}}},O=async()=>{let L=await W.migrationBlockers();return V1({title:_H,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.",...L.length>0?["These processes still hold the move back:",...L.map((P)=>` ${P.pid==="unknown"?"processes that could not be read":`pid ${P.pid}`}: version ${P.version}`)]:[]],actions:[q3({checks:K(!1)})],...W.terminal?{terminal:W.terminal}:{}})},_=async(L)=>{let P=$(),A=W.openAccountPool(P);if(Z&&await Z.authority()!=="local")return L3(N(P,A),Z);if(await i7(P,A)===void 0)return O();let T=N(P,A);return Z?L3(T,Z):q$(T)},C=(L)=>async()=>{if(Z&&await Z.authority()!=="local")throw Error(h8);let P=await L();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:L$({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:o_,type:"oauth",authorize:async()=>({url:"",instructions:r_,method:"auto",callback:async()=>{if(await X3(Z.paths,Z.name)!=="vault")return{type:"failed"};try{let L=JSON.parse(await s_(B4(),"utf8"));if(!L||typeof L!=="object"||Array.isArray(L)||Object.hasOwn(L,"openai"))return{type:"failed"}}catch(L){if(L.code!=="ENOENT")return{type:"failed"}}return{...q1,type:"success"}}})}]:[]]}var g$={rpcRoot:"openai-auth",directoryPrefix:SH,registrationSessionId:"process"};function o7(X,J){RH(g$,X,J)}function IH(X=0,J){return CH(g$,X,J)}function bH(X){return EH(g$,X)}var r7=Z0("commands");function j4(X){return{configPath:X.accountStoragePath,statePath:X.accountStatePath}}function m$(X){return`${String(X.startHour).padStart(2,"0")}-${String(X.endHour).padStart(2,"0")}`}function XA(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 JA="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 $A(X){let J=($)=>K1(X.store(),W9(j4(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=D7(await X.loadAccounts(j4(X))),G=Y?.enabled===!0,Q=Y?.subagents===!0,z=$.status(),Z=z.window?m$(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 r7.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?JA:"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:m$(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=XA(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 ${m$(H)} local hours.`}}]}}}}var kH=["error","warn","info","debug","trace"];function YA(X){return{title:"Diagnostics",build:async()=>{let J=p6(),Y=(await X.loadAccounts(j4(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 K1(X.store(),W9(j4(X)),(Z)=>{Z.dump={...Z.dump??{},enabled:Q}});let z=gB();return r7.info(Q?"request dump enabled":"request dump disabled"),Q?`Request dumps are on, written to ${z.dumpDir}.
157
+ ${Q[G]??"The server returned a no-op result. No reset was confirmed."}`)}function sf(X,J,$){let Y=X.get(J.sessionId),G=new Set(J.validPinnedAccountIds);if(Y&&!J.excludeAccountIds.includes(Y.accountId)&&v4(Y,G,J.wireAccountIdByAccount[Y.accountId])){if(J.persist){let W=J.quotaCheckedAtByAccount[Y.accountId];$(J.sessionId,{accountId:Y.accountId,inputBytes:J.requestBytes,...Y.wireIdentity!==void 0?{wireIdentity:Y.wireIdentity}:{},...W!==void 0?{quotaCheckedAt:W}:{}})}return{accountId:Y.accountId}}let Q=new Map(Object.entries(J.quotaCheckedAtByAccount)),z=X5(X,Q,J.sessionId),Z=J.select(z);if(!Z)return;if(J.persist){let W=J.wireAccountIdByAccount[Z.accountId];$(J.sessionId,{accountId:Z.accountId,inputBytes:J.requestBytes,...W!==void 0?{wireIdentity:W}:{},...Z.quotaCheckedAt!==void 0?{quotaCheckedAt:Z.quotaCheckedAt}:{}})}return{accountId:Z.accountId}}import{statSync as IM}from"node:fs";var yB=30000,bM=8,kM=1800000;function P3(X){return X.identity?`identity:${X.identity}`:`row:${X.id}`}function S$(X){try{let J=IM(X);return`${J.ino}:${J.size}:${J.mtimeMs}`}catch{return"-"}}function Y4(X){let J=X.credential;if(J?.type!=="oauth")return;return{access:J.access??"",expires:J.expires,refresh:J.refresh}}function I$(X,J){try{return V7(X,J)}catch{return X}}function hB(X,J,$){let Y=P3(J);X.set(Y,[...X.get(Y)??[],{credentialEpoch:J.credentialEpoch,identity:J.identity,observation:$}].slice(-bM))}function fB(X,J,$){let Y=X;for(let G of J.get(P3(X))??[]){if(!($-G.observation.checkedAt<=kM)||G.credentialEpoch!==X.credentialEpoch||G.identity!==X.identity)continue;Y={...Y,quota:I$(Y.quota,G.observation)}}return Y}function gB(X,J,$,Y){let G=s6(X);if(typeof J?.status==="number"||k5(J)){let z=p1({error:J,now:$,refreshToken:X,...Y?{previous:{message:"",checkedAt:$,nextRetryAt:Y.nextRetryAt,retryCount:Y.retryCount,tokenHash:Y.tokenHash}}:{}});return{nextRetryAt:z.nextRetryAt,tokenHash:G,retryCount:z.retryCount}}return{nextRetryAt:$+yB,tokenHash:G,retryCount:Y?.tokenHash===G?Y.retryCount:0}}function mB(X,J,$,Y){let G=new Map;for(let Q of X){if(Y(Q,$))continue;let z=J.get(Q.id);G.set(Q.id,z&&z.nextRetryAt>$?z.nextRetryAt:$+yB)}return G}var b$=Z0("quota"),uB="the account holds a tombstone from the removed vault custody, not a credential";function xM(X){return X?.status===401}async function G4(X,J={}){let $=X.whamFn;if(!$)throw Error("whamFn is required for refreshAllQuota");let Y=[],G=X.logger??b$,Q=(K)=>{Y.push(K);let q={pid:process.pid,accountId:K.account,status:K.ok?"ok":"error",...K.error?{error:K.error}:{}};if(K.ok)G.debug("quota refresh succeeded",q);else G.warn("quota refresh failed",q)},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((q)=>typeof q==="number"&&Number.isFinite(q)&&q<=X.now()&&X.now()-q<z),U=await X.loadAccounts(X.paths).catch(()=>{return}),j=U?.mainAccountId??X.storageMainAccountId,N;if(!J.accountKey||J.accountKey==="main")try{let K=await X.getAuth();if(C6(K)){if(N=Z9(U),!N)Q({account:"main",ok:!1,error:T0(K)?uB:"main account row is missing from the account pool"})}else if(K.type==="oauth"){let q=W&&j!==void 0&&W.main.mainAccountId===j?W.main.quota:void 0;if(H(X.quotaManager.peekMainForPolicy(j)?.checkedAt,q?.primary?.checkedAt,q?.secondary?.checkedAt,q?.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:e0(K)})}if(U)for(let K of U.accounts){let q=N!==void 0&&K===N;if(!q&&J.accountKey&&(J.accountKey==="main"||K.id!==J.accountKey))continue;if(!q&&X.isOAuthAccountFn(K)&&Q9(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=q?K.accountId??j:void 0,O=(_,C,L)=>{if(q)X.quotaManager.setMain(C,_,F,!0);else X.quotaManager.setFallback(K.id,_,C,!0,L)};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,L=q?W&&F!==void 0&&W.main.mainAccountId===F?W.main.quota:void 0:_&&C!==void 0&&_.accountId===C?_.quota:void 0;if(H(q?X.quotaManager.peekMainForPolicy(F)?.checkedAt:X.quotaManager.peekFallbackForPolicy(K.id,C)?.checkedAt,L?.primary?.checkedAt,L?.secondary?.checkedAt,L?.checkedAt)){Q({account:K.id,ok:!0});continue}if(X.respectBackoff&&(q?X.quotaManager.isBackedOff():X.quotaManager.isFallbackBackedOff(K.id,K.access))){Q({account:K.id,ok:!0});continue}let P=K.lastRefreshError;if(r0(P,K.refresh,X.now())){Q({account:K.id,ok:!1,error:X9(P,X.now()),permanent:!0});continue}if(T0(K)){Q({account:K.id,ok:!1,error:uB});continue}let A;try{A=q?await X.fallbackManager.refreshAccount(K,U,{asPoolMain:!0}):await X.fallbackManager.refreshAccount(K,U)}catch(k){b$.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:K.id,error:e0(k)}),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(k){if(!xM(k))throw k;if(b$.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:K.id}),A=await X.fallbackManager.refreshAccount(K,U,q?{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:e0(_)})}}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}import{types as wM}from"node:util";var vM=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,yM=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function iB(X){return X.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,(J,$,Y)=>{if($)return String.fromCharCode(Number.parseInt($,16));return{b:"\b",f:"\f",n:`
158
+ `,r:"\r",t:"\t"}[Y]??Y??J})}function hM(X,J){if(!J)return X;let $=X.split(J).join("[credential]"),Y=J.replace(/\s/g,"");if(!Y)return $;let G=$.replace(/\s/g,"");if(!G.includes(Y))return $;let Q=[];for(let W=0;W<$.length;W++){let B=$[W]??"";if(!/\s/.test(B))Q.push(W)}let z=[],Z=0;for(let W=G.indexOf(Y);W>=0;W=G.indexOf(Y,W+Y.length)){let B=Q[W]??Z,H=(Q[W+Y.length-1]??B)+1;z.push($.slice(Z,B),"[credential]"),Z=H}return z.length?z.join("")+$.slice(Z):$}function pB(X,J){let $=hM(X,J);return dB($).replaceAll("***REDACTED***","[credential]")}function Q4(X,J){let $=pB(X,J),Y=iB($),G=pB(Y,J);return G===Y?$:G}function cB(X){let J=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(X);if(!J)return;let $=J[3]??"",Y=(J[2]??"")+$,G=0;while(Y[G]==="0")G++;if(G===Y.length)return"0";let Q=Y.length;while(Y[Q-1]==="0")Q--;let z=J[4]??"0",Z=z.startsWith("-")||z.startsWith("+")?1:0;while(z[Z]==="0")Z++;let W=z.slice(Z)||"0";if(W.length>16)return;let B=BigInt((z.startsWith("-")?"-":"")+W)-BigInt($.length)+BigInt(Y.length-Q);return`${J[1]}${Y.slice(G,Q)}e${B}`}function nB(X,J){let $=J?cB(J):void 0;return X.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(Y)=>{if(!Y.startsWith('"'))return J&&(Y===J||$!==void 0&&cB(Y)===$||(J==="Infinity"||J==="-Infinity")&&/^[-\d]/.test(Y)&&String(Number(Y))===J)?'"[credential]"':Y;let G=iB(Y.slice(1,-1)),Q=Q4(G,J);return Q===G?Y:JSON.stringify(Q)})}function k$(X,J){let $=nB(X,J);try{return JSON.parse(X),$}catch{return Q4($,J)}}var fM=16384,gM=65536,mM=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function uM(X){try{let J=X6(JSON.parse(X),"request_id");if(typeof J==="string")return J;if(typeof J!=="number")return;let $=0,Y,G=!0,Q=!1,z;for(let Z of X.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let W=Z[0];if(W==="{"||W==="["){$++;continue}if(W==="}"||W==="]"){$--;continue}if($!==1)continue;if(W===","){G=!0,Q=!1,Y=void 0;continue}if(W===":"){Q=!0;continue}if(G&&W.startsWith('"')){Y=JSON.parse(W),G=!1;continue}if(Q&&Y==="request_id"&&!W.startsWith('"'))z=W;Q=!1}return z}catch{return}}function pM(X,J){let $=k$(X,J);if(Buffer.byteLength($,"utf8")<=gM)return $;let Y=mM.flatMap((Q)=>Q.exec($)?.[0]??[]);for(let Q of["FreeUsageLimitError","GoUsageLimitError"])if($.includes(Q))Y.push(Q);let G={retry:Y};try{let Q=JSON.parse($);if(X6(Q,"type")==="error")G.type="error";let z=X6(Q,"error"),Z={};for(let B of["code","type"]){let H=X6(z,B);if(typeof H==="string")Z[B]=H.slice(0,256)}if(Object.keys(Z).length)G.error=Z;let W={};for(let B of["workspace","limitName"]){let H=X6(X6(Q,"metadata"),B);if(typeof H==="string")W[B]=H.slice(0,256)}if(Object.keys(W).length)G.metadata=W}catch{}return JSON.stringify(G)}function k7(X){if(!X||typeof X!=="object")return!1;let J=X;for(let $=0;J&&$<16;$++){if(wM.isProxy(J))return!1;J=Object.getPrototypeOf(J)}return J===null}function X6(X,J){if(!k7(X))return;let $=Object.getOwnPropertyDescriptor(X,J);return $&&"value"in $?$.value:void 0}function O3(X,J){return Q4(X,J).slice(0,fM)}function z4(X,J){let $=Object.getOwnPropertyDescriptor(X,J)?.get;if(!$)throw Error(`Missing native ${J} accessor`);return $}var cM=z4(DOMException.prototype,"message"),lM=z4(DOMException.prototype,"name");function j8(X,J){let $=X6(X,"message"),Y=X6(X,"name");if(k7(X)&&X instanceof DOMException)try{$=cM.call(X),Y=lM.call(X)}catch{}let G=Error(O3(typeof $==="string"?$:typeof X==="string"?X:"Provider request failed",J));for(let U of Object.getOwnPropertyNames(G))if(U!=="message")Reflect.deleteProperty(G,U);Object.defineProperty(G,"name",{value:typeof Y==="string"?O3(Y,J):"Error",configurable:!0,writable:!0});let Q=(U,j,N)=>{let K=X6(U,N);if(typeof K==="string"||typeof K==="number"&&Number.isFinite(K)||typeof K==="boolean")Object.defineProperty(j,N,{value:typeof K==="string"?O3(K,J):K,enumerable:!0,configurable:!0,writable:!0})};for(let U of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=X6(X,U);if(typeof j==="number"&&Number.isFinite(j))Q(X,G,U)}for(let U of["code","type","isRetryable"])Q(X,G,U);for(let U of["error","data"]){let j=X6(X,U),N=Object.create(null);for(let q of["type","code","message","resets_at","resets_in_seconds"])Q(j,N,q);let K=X6(j,"error");if(k7(K)){let q=Object.create(null);for(let F of["type","code","message","resets_at","resets_in_seconds"])Q(K,q,F);N.error=q}if(Object.keys(N).length)Object.defineProperty(G,U,{value:N,enumerable:!0})}let z=X6(X,"responseHeaders");if(z&&typeof z==="object"){let U={};for(let j of["retry-after-ms","retry-after"]){let N=X6(z,j);if(typeof N==="string")U[j]=O3(N,J)}Object.defineProperty(G,"responseHeaders",{value:U,enumerable:!0})}let Z=X6(X,"responseBody");if(typeof Z==="string")Object.defineProperty(G,"responseBody",{value:pM(Z,J),enumerable:!0});let W=X6(X,"request_id"),B=X6(z,"x-request-id"),H=typeof W==="string"?W:typeof B==="string"?B:typeof Z==="string"?uM(k$(Z,J)):void 0;if(typeof H==="string")Object.defineProperty(G,"request_id",{value:O3(H,J),enumerable:!0});for(let U of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(U);if(X6(X,j)===!0)Object.defineProperty(G,j,{value:!0})}return G}function dM(X,J){if(!X.includes("error")&&(!X.includes("\\u00")||!vM.test(X)&&!yM.test(X)))return X;let $;try{$=JSON.parse(X)}catch{return X}if($?.type==="error"||$?.error||$?.response?.error)return nB(X,J);return X}var iM=z4(Response.prototype,"status"),nM=z4(Response.prototype,"statusText"),sM=z4(Response.prototype,"headers"),aM=z4(Response.prototype,"body"),oM=Response.prototype.text,lB=Headers.prototype.entries;async function j1(X,J,$="http"){try{let N=function(K){let q=j&&K.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,q+K.slice(q.length).replace(/^data: ?([^\r\n]*)/gm,(F,O)=>F.slice(0,F.length-O.length)+dM(O,J))};if(!k7(X))throw Error("Invalid provider response");let Y=iM.call(X),G=sM.call(X),Q=aM.call(X),z=new Headers;for(let[K,q]of lB.call(G))z.append(K,q);let Z={status:Y,statusText:Q4(nM.call(X),J),headers:z};if(Y<200||Y>299){for(let[q,F]of lB.call(G)){if(Q4(q,J?.toLowerCase())!==q){Z.headers.delete(q);continue}try{Z.headers.set(q,Q4(F,J))}catch{Z.headers.delete(q)}}Z.headers.delete("content-length");let K=await oM.call(X);return new Response(k$(K,J),Z)}if(!Q||$==="http")return X;Z.headers.delete("content-length");let W=ReadableStream.prototype.getReader.call(Q),B=new TextDecoder("utf-8",{ignoreBOM:!0}),H=new TextEncoder,U="",j=!0;return new Response(new ReadableStream({async pull(K){try{for(;;){let q=await W.read();U+=B.decode(q.value,{stream:!q.done});let F=!1;for(;;){let O=/\r?\n\r?\n/.exec(U);if(!O)break;let _=O.index+O[0].length;K.enqueue(H.encode(N(U.slice(0,_)))),U=U.slice(_),F=!0}if(q.done){if(U)K.enqueue(H.encode(N(U)));K.close();return}if(F)return}}catch(q){K.error(j8(q,J))}},async cancel(K){try{await W.cancel(K)}catch(q){throw j8(q,J)}finally{W.releaseLock()}}}),Z)}catch(Y){throw j8(Y,J)}}import{readFile as GA}from"node:fs/promises";import{readFileSync as rM}from"node:fs";import{homedir as tM,tmpdir as eM}from"node:os";import{join as v7}from"node:path";var X_="https://chatgpt.com/backend-api/codex/responses",J_="openai-auth.json",b9={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 y7(){let X=process.env[b9.configDir]?.trim();if(X)return X;return v7(process.env.XDG_CONFIG_HOME||v7(tM(),".config"),"opencode")}function V0(){return process.env[b9.configFile]?.trim()||v7(y7(),J_)}function $_(){try{let X=JSON.parse(rM(V0(),"utf8"));return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:{}}catch{return{}}}function Y_(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 x7(X,J,$){let Y=Y_(X);if(Y!==void 0)return Y;if(typeof J==="boolean")return J;return $}function G_(){let X=$_(),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:x7(b9.webSockets,X.webSockets,!1),rawWebSocket:x7(b9.rawWebSocket,X.rawWebSocket,!1),responsesLite:x7(b9.responsesLite,X.responsesLite,!1),dump:x7(b9.dump,J,!1),dumpDir:process.env[b9.dumpDir]?.trim()||(typeof X.dumpDir==="string"&&X.dumpDir.trim()?X.dumpDir.trim():v7(eM(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[b9.codexApiEndpoint]?.trim()||(typeof X.codexApiEndpoint==="string"&&X.codexApiEndpoint.trim()?X.codexApiEndpoint.trim():X_)}}var w7;function c6(){if(!w7)w7=G_();return w7}function sB(){return w7=void 0,c6()}import{realpathSync as aB}from"node:fs";import{homedir as Q_}from"node:os";import{basename as z_,dirname as Z_,join as f7,resolve as rB}from"node:path";function W_(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return f7(process.env.XDG_CONFIG_HOME||f7(Q_(),".config"),"opencode")}function tB(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||f7(W_(),cJ)}function h7(X,J){let $=rB(X);return J==="win32"||J==="darwin"?$.toLowerCase():$}function oB(X){try{return aB.native(X)}catch{try{return f7(aB.native(Z_(X)),z_(X))}catch{return}}}function B_(X,J,$=process.platform){if(h7(X,$)===h7(J,$))return!0;let Y=oB(X),G=oB(J);return Y!==void 0&&G!==void 0&&h7(Y,$)===h7(G,$)}function x$(X=tB()){let J=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(J){if(B_(X,J))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${rB(X)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return J}return lJ(X)}function M0(X=tB()){return{configPath:X,statePath:x$(X)}}import{createHash as y_}from"node:crypto";import{readFile as h_}from"node:fs/promises";import{homedir as f_}from"node:os";import{join as qH,resolve as g_}from"node:path";import{createHash as H_}from"node:crypto";import{readFileSync as V_}from"node:fs";import{readFile as U_}from"node:fs/promises";import{resolve as K_}from"node:path";var Z4="openai",j_="common-auth-placeholder:v1:openai",N1=Object.freeze({type:"oauth",access:"",refresh:j_,expires:0});function A3(X){if(!X8(X))return!1;return X.type===N1.type&&X.access===N1.access&&X.refresh===N1.refresh&&X.expires===N1.expires}var g7="openaiAuthPool",N_=120000,$H="pool-migration",v$="slot-transfer-origin-unknown",y$="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.",u7=Object.freeze({mainRefreshTtlMs:N_,fallbackTtlMs:rJ,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function m7(X,J,$){return X.kind==="placeholder"&&!J&&!$.pending}class M3 extends Error{constructor(X){super(`timed out waiting for the legacy ${X} lock`);this.name="LegacyLockContention"}}function X8(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}function q_(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:{...u7,...X.legacyLocks},leaseWait:X.leaseWait??{timeoutMs:4000,pollMs:50},store:z8({provider:Z4,configPath:X.paths.configPath,statePath:X.paths.statePath,quota:m8,now:J,...X.store}),onStep:async($)=>{await X.onStep?.($)}}}async function B4(X){let J;try{J=await U_(X,"utf8")}catch(Y){if(Y.code==="ENOENT")return{};throw Y}let $=JSON.parse(J);if(!X8($))throw Error("config root is not an object");return $}async function _3(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 M3(J);await X.sleep(X.locks.retryMs)}}async function YH(X,J,$={}){let Y={...u7,...$},G=performance.now();for(;;){let Q=await g0({name:g8,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 M3(g8);await new Promise((z)=>setTimeout(z,Y.retryMs))}}async function T3(X,J){let $=X.locks.saveTtlMs,Y=await _3(X,"save",X.paths.configPath,$);try{let G=await _3(X,"save",X.paths.statePath,$);try{let Q=await B4(X.paths.configPath);if(!await J(Q))return;await M6(X.paths.configPath,Q,{beforeRename:async()=>{await Y.assertOwned(),await G.assertOwned()}})}finally{await G.release().catch(()=>{})}}finally{await Y.release().catch(()=>{})}}function L_(X){if(!X8(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 GH(X,J){if(!X8(X)||!J)return!1;return N6(X).pending?.credentialFingerprint===Y8({type:"oauth",refresh:J})}function QH(X,J){let $;try{$=JSON.parse(V_(X,"utf8"))}catch{return!1}return GH($,J)}class p7 extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var D_=600000;async function zH(X,J,$={}){let Y=$.now??Date.now,G=(W)=>{let B=N6(W).pending;return B&&GH(W,J)&&Y()-B.recordedAt>=D_?B:void 0},Q=G(await B4(X.configPath));if(!Q)return!1;let z={...u7,...$.legacyLocks},Z=await g0({name:$H,path:X.configPath,ttlMs:z.mainRefreshTtlMs,now:Y});if(!Z)return!1;try{let W=await B4(X.configPath),B=N6(W).migratedAt!==void 0,H=await z8({provider:Z4,configPath:X.configPath,statePath:X.statePath,quota:m8,now:Y}).read();if(B&&H.status!=="ready")return!1;let U;if(H.status==="ready"){let N=H.rows.find((q)=>q.id===Q.rowId&&!q.invalid),K=N?.fingerprint??null;if(B&&N&&K===Q.credentialFingerprint)return!1;if(N&&K!==Q.credentialFingerprint&&K!==Q.rowFingerprint)U=$.slotAccess!==void 0?g$({type:"oauth",access:$.slotAccess,refresh:J}):Q.slotFingerprint}let j=!1;if(await T3({paths:X,now:Y,locks:z,sleep:(N)=>new Promise((K)=>setTimeout(K,N))},(N)=>{let K=N6(N),q=G(N);if(!q||q.recordedAt!==Q.recordedAt)return!1;let{pending:F,...O}=K;return c7(N,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 N6(X){let J=X[g7];if(!X8(J))return{};let $=L_(J.pending);return{...typeof J.migratedAt==="number"?{migratedAt:J.migratedAt}:{},...$?{pending:$}:{},...typeof J.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:J.declinedSlotFingerprint}:{}}}function c7(X,J){let Y={...X8(X[g7])?X[g7]:{}};for(let G of["migratedAt","pending","declinedSlotFingerprint"])delete Y[G];Object.assign(Y,J),X[g7]=Y}function F_(X){let J=X?V6(X):void 0;return J?U6(J):void 0}function P_(X){let J=g$({type:"oauth",...X}),$=F_(X.access);return{kind:"real",credential:X,fingerprint:J,credentialFingerprint:Y8({type:"oauth",refresh:X.refresh}),...$?{identity:$}:{}}}function ZH(X){if(A3(X))return{kind:"placeholder",...X8(X)&&typeof X.accountId==="string"?{origin:X.accountId}:{}};let J=jH(X);if(!J?.refresh.trim())return{kind:"empty"};return P_(J)}async function R3(X){let J=await NH({client:{auth:{get:($)=>X.slot.get($),all:()=>X.slot.all()}},now:X.now,sleep:X.sleep});if(J.kind==="real")return ZH(J.oauth);return J.kind==="slot-absent"||J.kind==="indeterminate"?{kind:J.kind}:{kind:J.kind}}async function l7(X,J){if(!A3(J))return!1;let $=await B4(X.configPath),Y=await z8({provider:Z4,configPath:X.configPath,statePath:X.statePath,quota:m8}).read();if(Y.status==="error")return!1;let G=Y.status==="ready"?Y.rows.some((Q)=>Q.id==="main"):Y.roster.some((Q)=>X8(Q)&&Q.id==="main");return m7({kind:"placeholder"},G,N6($))}async function O_(X){let J=X.now()+X.leaseWait.timeoutMs;for(;;){let $=await R3(X);if($.kind!=="real")return $;if(!await WH(X,$.credential.refresh))return $;if(X.now()>=J)return{kind:"retry"};await X.sleep(X.leaseWait.pollMs)}}async function WH(X,J){let $=await b0(X.paths),Y=$?.refresh?.mainRefreshLeaseUntil;return Boolean(Y&&Y>X.now()&&$?.refresh?.mainRefreshLeaseTokenHash===s6(J))}function M_(X){return X.length>0&&X.trim()===X&&!["__proto__","constructor","prototype","main"].includes(X)}function __(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&&M_($.identity)&&!W.has($.identity)?$.identity:G()),operation:"add",rowFingerprint:null,...Q,carryLegacyMain:!1}}function A_(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:{...__(X,$,Y,G,z),slotFingerprint:Y.fingerprint,credentialFingerprint:Y.credentialFingerprint,recordedAt:Q},credential:Y.credential,fresh:!0}}async function T_(X,J,$){let Y={type:"oauth",access:$.access,refresh:$.refresh,...$.expires!==void 0?{expires:$.expires}:{}},G=J.identity?{identity:J.identity}:{},Q={extraLocks:f8(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 R_(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 C_(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 E_(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===x6(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 C_(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 nJ(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 W4(X,J,$={}){await T3(X,(Y)=>{let G=N6(Y);if(delete Y.mainAccountId,J==="migrate"&&G.migratedAt===void 0)S_(Y);return c7(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 S_(X){let J=X.routing;if(J===void 0)X.routing={mode:"main-first"};else if(X8(J)&&J.mode===void 0)X.routing={...J,mode:"main-first"}}async function h$(X){await T3(X,(J)=>{let $=N6(J);if(!$.pending)return!1;let{pending:Y,...G}=$;return c7(J,G),!0})}async function I_(X,J){await T3(X,($)=>{let Y=N6($);if(J.identity)$.mainAccountId=J.identity;return c7($,{...Y,pending:J}),!0})}async function b_(X,J,$,Y){let G=await _3(X,g8,X.paths.configPath,X.locks.mainRefreshTtlMs);try{return await k_(X,J,$,Y)}finally{await G.release().catch(()=>{})}}async function k_(X,J,$,Y){let G=(B)=>({status:"completed",rowId:$.rowId,operation:Y,placeholder:B}),Q=await R3(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!==w$(X))return{status:"foreign-placeholder"};return await W4(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 h$(X),await X.onStep("after-record-clear"),{status:"restart"};if(Q.kind!=="real"||Q.fingerprint!==$.slotFingerprint)return await W4(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:Z4}}),Z=z===void 0||z===null?void 0:ZH(z);if(Z?.kind!=="real"||Z.fingerprint!==$.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await X.slot.set({path:{id:Z4},body:{...N1,accountId:w$(X)}})}catch(B){if(B instanceof n7)return{status:"retry",reason:"slot-changed"};throw B}await X.onStep("after-placeholder-write");let W=await X.slot.get({path:{id:Z4}});if(!A3(W))return{status:"retry",reason:"placeholder-overwritten"};if(X8(W)&&W.accountId===void 0)return{status:"untagged-placeholder"};if(X8(W)&&W.accountId!==w$(X))return{status:"foreign-placeholder"};return await W4(X,J),await X.onStep("after-record-clear"),G("written")}async function x_(X,J,$){let{record:Y}=$;if($.fresh)await I_(X,Y),await X.onStep("after-record-write");if(await WH(X,$.credential.refresh))return{status:"restart"};let G=await R3(X);if(G.kind!=="real"||G.fingerprint!==Y.slotFingerprint)return{status:"restart"};return await T_(X,Y,$.credential),await X.onStep("after-row-write"),BH(X,J,Y,$.fresh?Y.operation:"resumed")}async function BH(X,J,$,Y){let G=await R_(X,$);if(!G)return{status:"retry",reason:"verify-failed"};if(await X.onStep("after-verify"),$.carryLegacyMain)await E_(X,G),await X.onStep("after-carry-over");let Q=await b_(X,J,$,Y);if(Q.status==="untagged-placeholder"){await X.store.disable($.rowId,v$,{extraLocks:f8(X.paths,$.rowId,X.locks),attribution:{credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}}}),await W4(X,J);let z=`${X.paths.configPath}\x00${$.rowId}`;if(!JH.has(z))JH.add(z),X.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${y$}`,{rowId:$.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(Q.status!=="foreign-placeholder")return Q;return await X.store.remove($.rowId,{extraLocks:f8(X.paths,$.rowId,X.locks),protect:(z,Z)=>Z.row?.fingerprint!==$.credentialFingerprint?"the transfer row changed before rollback":void 0}),await h$(X),await f$(X),{status:"refused",reason:"placeholder-without-main"}}var eB=new Set,XH=new Set,JH=new Set;function w$(X){return`openai-auth-pool:${H_("sha256").update(K_(X.paths.configPath)).digest("hex")}`}async function w_(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 HH(X,J,$){let Y=q_(X),G=Y.slot.migrationDisabledReason?.();if(G){let B=Y.slot.path??H4();if(!XH.has(B))XH.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 B4(Y.paths.configPath)}catch(B){return{status:"error",reason:B instanceof Error?B.message:String(B)}}let z=await VH(Y,J,Q);if(z){if(z.status==="already-migrated"&&"mainAccountId"in Q)await f$(Y);return z}if($){let B=await w_($);if(B.length>0){let H=`${Y.paths.configPath}\x00${B.map((U)=>`${U.pid}@${U.version}`).join(",")}`;if(!eB.has(H))eB.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 _3(Y,"pool-slot-transfer",Y.slot.path??H4(),Y.locks.mainRefreshTtlMs),Z=await _3(Y,$H,Y.paths.configPath,Y.locks.mainRefreshTtlMs)}catch(B){if(await W?.release().catch(()=>{}),B instanceof M3)return{status:"retry",reason:"lock-contention"};throw B}try{return await v_(Y,J)}catch(B){if(B instanceof M3)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 VH(X,J,$){let Y=N6($);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&&m7(await R3(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 v_(X,J){let $;for(let Y=0;Y<4;Y++){let G=await B4(X.paths.configPath),Q=await VH(X,J,G);if(Q){if(Q.status==="already-migrated")await f$(X);return Q}let z=await X.store.read(),Z=N6(G);if(z.status==="pending-migration"){if(m7(await R3(X),z.roster.some((U)=>X8(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 O_(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(m7(W,z.rows.some((U)=>U.id==="main"),Z))return{status:"refused",reason:"placeholder-without-main"};let B=A_(J,Z,z.rows,W,$,X.now(),X.newId);if(B.kind==="nothing"){if(J==="migrate")await W4(X,J),await X.onStep("after-marker-write");return{status:"nothing-to-import",slot:B.slot}}if(B.kind==="drop-record"){await h$(X),await X.onStep("after-record-clear");continue}if(B.kind==="ambiguous")return await W4(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 BH(X,J,B.record,"resumed"):await x_(X,J,B);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function f$(X){await T3(X,(J)=>{if(!("mainAccountId"in J))return!1;if(N6(J).pending)return!1;return delete J.mainAccountId,!0})}function d7(X){return HH(X,"migrate",X.fence)}function i7(X){return HH(X,"adopt")}class UH extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function f8(X,J,$={}){let Y={...u7,...$},G={renew:Y.renew,timeoutMs:Y.timeoutMs,retryMs:Y.retryMs,...Y.renewIntervalMs!==void 0?{renewIntervalMs:Y.renewIntervalMs}:{}};return[{name:g8,path:X.configPath,ttlMs:Y.mainRefreshTtlMs,...G},{name:tJ(J),path:X.configPath,ttlMs:Y.fallbackTtlMs,...G}]}async function KH(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=s6(W.refresh),U=async()=>{let j=await b0(X.paths),N=j?.refresh?.mainRefreshLeaseUntil;return Boolean(N&&N>G()&&j?.refresh?.mainRefreshLeaseTokenHash===H)};if(await U()){let j=G()+z.timeoutMs;while(G()<j&&await U())await Q(z.pollMs);throw new UH}return $(W,B)};return X.store.refresh(J,Z,{...Y,extraLocks:f8(X.paths,J,X.legacyLocks)})}var m_="openai",LH=250,g8="main-refresh";function g$(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 y_("sha256").update(Y(J)).update(J).update(Y($)).update($).digest("hex")}function MH(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 jH(X){let J=MH(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 C3(X){if(q1(X)&&X.type==="api"&&typeof X.key==="string")return{kind:"api"};let J=MH(X);if(!J)return{kind:"indeterminate"};return T0(J)?{kind:"tombstone",oauth:J}:{kind:"real",oauth:J}}async function DH(X){return X.auth.get({path:{id:m_}})}async function FH(X){return Object.keys(await X.auth.all()).length>0}async function NH(X){let J=await DH(X.client);if(J!==void 0)return C3(J);let $=await FH(X.client),Y=X.now();if(await X.sleep(LH),X.now()-Y<LH)return{kind:"indeterminate"};let G=await DH(X.client);if(G!==void 0)return C3(G);let Q=await FH(X.client);return $&&Q?{kind:"slot-absent"}:{kind:"indeterminate"}}function H4(X=process.env,J=f_()){let $=X.XDG_DATA_HOME||qH(J,".local","share");return qH($,"opencode","auth.json")}function q1(X){return!!X&&typeof X==="object"&&!Array.isArray(X)}var PH=(X)=>X===void 0||typeof X==="string";function u_(X){if(!q1(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&&PH(X.accountId)&&PH(X.enterpriseUrl);case"api":return typeof X.key==="string"&&(X.metadata===void 0||q1(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 m$(X,J=process.env){let $=J.OPENCODE_AUTH_CONTENT;if($)try{let G=JSON.parse($);return q1(G)?G:{}}catch{}let Y;try{Y=JSON.parse(await h_(X,"utf8"))}catch{return{}}if(!q1(Y))return{};return Object.fromEntries(Object.entries(Y).filter(([,G])=>u_(G)))}function OH(X){if(!X.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(X.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class n7 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function p_(X){let J=X.env??process.env,$=X.path??H4(J),Y=new Map;return{path:g_($),migrationDisabledReason:()=>OH(J)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(G){let Q=(await m$($,J))[G.path.id];return Y.set(G.path.id,JSON.stringify(Q)),Q},async all(){return m$($,J)},async set(G){if(OH(J))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let Q=(await m$($,J))[G.path.id];if(A3(G.body)&&(!Y.has(G.path.id)||Y.get(G.path.id)!==JSON.stringify(Q)))throw new n7;let z=await X.set(G);if(q1(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 _H(X,J={}){let $=q1(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:p_({...J,set:(G)=>Y.call($,G)})}}import{readFileSync as c_}from"node:fs";var l_="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 d_(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 V4(X,J={}){return z8({provider:"openai",configPath:X.configPath,statePath:X.statePath,quota:m8,...J})}function u$(X){try{let J=JSON.parse(c_(X,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return N6(J).migratedAt!==void 0}catch{return!1}}async function s7(X,J){if(!u$(X.configPath))return;let $=await J.read();return $.status==="ready"?$.rows:void 0}function a7(X,J){if(X===U8)return l_;if(N6(J.config).pending?.rowId===X)return d_(X);return}function i_(X,J){return f8(X,U8,J.legacyLocks).filter(($)=>$.name===g8)}function B9(X,J={}){return i_(X,J)}var U4="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 L1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function AH(X){let J=X.storage,$=Z9(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)&&!r0(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 n_,readFile as s_}from"node:fs/promises";import{homedir as a_}from"node:os";import{join as K4}from"node:path";function RH(){return process.env.XDG_STATE_HOME||K4(a_(),".local","state")}function o_(X=RH()){return K4(X,"cortexkit","openai-auth","processes")}function r_(X=RH()){return K4(X,"cortexkit","openai-auth","rpc")}function t_(X){try{return process.kill(X,0),!0}catch(J){return J.code==="EPERM"}}function TH(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 e_(X,J){let $=TH(X),Y=TH(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 p$(X){try{return{ok:!0,names:await n_(X)}}catch(J){let $=J.code;if($==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:$,error:`${X}: ${String(J)}`}}}async function XA(X,J){let $;try{$=await s_(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 j4(X){let J=X.isAlive??t_,$=X.selfPid??process.pid,Y=new Map,G=(N)=>{let K=N.pid==="unknown"?`dir:${N.detail}`:N.pid;if(!Y.has(K))Y.set(K,N)},Q=(N)=>{try{return J(N)}catch{return!0}},z=(N,K)=>{let q=K.exec(N),F=q?Number(q[1]):Number.NaN;return Number.isSafeInteger(F)&&F>=1?F:void 0},Z=o_(X.stateHome),W=new Set,B=await p$(Z);if(!B.ok)G({pid:"unknown",version:"unknown",detail:B.error});for(let N of B.ok?B.names:[]){let K=z(N,/^(\d+)\.json$/);if(K===void 0||K===$)continue;let q=K4(Z,N),F=await XA(q,K);if(F.kind==="gone")continue;if(W.add(K),!Q(K))continue;if(F.kind==="unreadable"){G({pid:K,version:"unknown",detail:q});continue}let O=e_(F.version,X.currentVersion);if(O===void 0||O<0)G({pid:K,version:F.version,detail:q})}let H=X.rpcDir??r_(X.stateHome),U=await p$(H);if(!U.ok)G({pid:"unknown",version:"unknown",detail:U.error});for(let N of U.ok?U.names:[]){if(!o7(N))continue;let K=K4(H,N),q=await p$(K);if(!q.ok){if(q.code==="ENOTDIR")continue;G({pid:"unknown",version:"unknown",detail:q.error});continue}for(let F of q.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:K4(K,F)})}}let j=(N)=>N.pid==="unknown"?Number.POSITIVE_INFINITY:N.pid;return Y.size===0?{open:!0}:{open:!1,blockers:[...Y.values()].sort((N,K)=>j(N)-j(K))}}var k9="1.0.3";import{readFile as EH}from"node:fs/promises";function r7(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}async function SH(X){let J=await dJ(X.configPath),$=[];try{let G=JSON.parse(await EH(X.statePath,"utf8"));if(r7(G)){let Q=G.accounts;if(r7(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 JA(X){try{let J=JSON.parse(await EH(X.configPath,"utf8"));return r7(J)&&r7(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var CH="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 IH(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 $A(X,J){let $=X.lastRefreshError;return r0($,X.refresh,J)&&$!==void 0&&$.nextRetryAt!==void 0&&$.nextRetryAt-$.checkedAt>=I5}function YA(X){let J=[],$=[],Y=X.now??Date.now(),G=IH(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. ${CH}`});else if(C6(X.auth)){if(!Z9(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. ${CH}`})}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(!$A(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 bH(X){let J=($)=>{if($.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(C6(await X.readAuth()))return;let Y=IH(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(),JA(X.paths)]),z=YA({auth:G.type==="missing"?void 0:G,storage:$,orphanStateIds:Y.orphanStateIds,retiredCustodyMode:Q,now:X.now()}),Z=await z8({provider:"openai",quota:m8,configPath:X.paths.configPath,statePath:X.paths.statePath}).read();if(Z.status==="ready")for(let W of Z.rows){if(W.disabledReason!==v$)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. ${y$}`})}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 QA=xH,kH="OpenAI accounts",zA="ChatGPT accounts in the vault",ZA="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 WA(){let{redirectUri:X}=await f5(),J=await y5(),$=w2(crypto.getRandomValues(new Uint8Array(32)).buffer),Y=h5(X,J,$),G=g5(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{$9($)}}}}async function BA(X){let{deviceData:J,url:$,instructions:Y}=await m5(X);return{url:$,instructions:Y,method:"auto",async callback(){try{let G=await u5(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 wH({client:X,getAuth:J,getPaths:$=()=>M0(V0()),fetchImpl:Y=fetch,packageVersion:G=k9,dependencies:Q,onMainSlotWritten:z,vault:Z}){let W={authorizeBrowser:Q?.authorizeBrowser??WA,authorizeHeadless:Q?.authorizeHeadless??(()=>BA(G)),beginAccountLogin:Q?.beginAccountLogin??v2,loadAccounts:Q?.loadAccounts??b0,mutateAccounts:Q?.mutateAccounts??F7,readStoreIds:Q?.readStoreIds??SH,openBrowser:Q?.openBrowser??QA,now:Q?.now??Date.now,openAccountPool:Q?.openAccountPool??V4,migrationBlockers:Q?.migrationBlockers??(async()=>{let L=await j4({currentVersion:G});return L.open?[]:L.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 L=$(),P=W.openAccountPool(L);if((await P.read()).status==="ready")return K$(P);return((await W.loadAccounts(L))?.accounts.length??0)>0},U=async(L)=>{if(await YH($().configPath,async()=>{if(Z&&await Z.authority()!=="local")return!1;if(C6(await B()))return!1;return await X.auth.set({path:{id:"openai"},body:{type:"oauth",...L}}),!0}))await z?.().catch(()=>{})},j=(L)=>({begin:async({headless:P,signal:A})=>{if(Z&&await Z.authority()!=="local")throw Error(h8);let T=await W.beginAccountLogin({version:G,headless:P,...A?{signal:A}:{}});return{url:T.url,instructions:T.instructions,completion:T.completion.then(async(k)=>{if(Z&&await Z.authority()!=="local")throw Error(h8);let p=await L.read(),i=p.status==="ready"?p.rows.find((w)=>w.id===U8)?.identity:void 0;if(k.accountId&&i&&k.accountId===i)throw Error("that account is already the OpenCode main credential");return{id:k.id,credential:{type:"oauth",refresh:k.refresh,...k.access!==void 0?{access:k.access}:{},...k.expires!==void 0?{expires:k.expires}:{}},...k.accountId!==void 0?{identity:k.accountId}:{},...k.label!==void 0?{label:k.label}:{}}})}},openBrowser:(P)=>W.openBrowser(P)}),N=async(L)=>{if(Z&&await Z.authority()!=="local")throw Error(h8);let P=L.credential;if(P?.type!=="oauth"||!P.access)throw Error("no usable access token for a quota check");let A=await b8({accessToken:P.access,fetchImpl:Y,now:W.now,...L.identity?{accountId:L.identity}:{},accountKey:L.id});return I9(A,W.now(),!0)},K=(L)=>bH({paths:$(),migrated:L,readAuth:B,loadAccounts:W.loadAccounts,readStoreIds:W.readStoreIds,mutateAccounts:W.mutateAccounts,setMainAuth:U,now:W.now}),q=(L,P)=>({title:kH,store:b7(P,{rowLocks:(A)=>f8(L,A)}),...W.terminal?{terminal:W.terminal}:{},login:j(P),protect:(A,T)=>a7(A,T),extraLocks:B9(L),pollQuota:N,doctor:K(!0),status:async()=>{let A=await Z?.status();if(Z&&await Z.authority()!=="local"&&A)return[N3(Z.host,Z.name,A.enrollment)];return[`Routing: ${(await W.loadAccounts(L))?.routing?.mode??"main-first"}`,...Z?[N3(Z.host,Z.name,(await Z.status()).enrollment)]:[]]},...Z?{extraActions:[F(Z)]}:{}}),F=(L)=>{let P=L.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 L.authority();if(P){if(T!=="local")await L.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 ${L.name}…`);let k,p=await L.waitForApproval({...W.vaultWait,onPending:(i)=>{let X0=i.state==="pending"?i.requestId??i.retryCode??"":i.state;if(X0===k)return;k=X0;for(let w of J4(L.name,i))A.print(w);A.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});A.print(q3(L,p).text)}}},O=async()=>{let L=await W.migrationBlockers();return V1({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.",...L.length>0?["These processes still hold the move back:",...L.map((P)=>` ${P.pid==="unknown"?"processes that could not be read":`pid ${P.pid}`}: version ${P.version}`)]:[]],actions:[L3({checks:K(!1)})],...W.terminal?{terminal:W.terminal}:{}})},_=async(L)=>{let P=$(),A=W.openAccountPool(P);if(Z&&await Z.authority()!=="local")return F3(q(P,A),Z);if(await s7(P,A)===void 0)return O();let T=q(P,A);return Z?F3(T,Z):L$(T)},C=(L)=>async()=>{if(Z&&await Z.authority()!=="local")throw Error(h8);let P=await L();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:F$({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:zA,type:"oauth",authorize:async()=>({url:"",instructions:ZA,method:"auto",callback:async()=>{if(await $3(Z.paths,Z.name)!=="vault")return{type:"failed"};try{let L=JSON.parse(await GA(H4(),"utf8"));if(!L||typeof L!=="object"||Array.isArray(L)||Object.hasOwn(L,"openai"))return{type:"failed"}}catch(L){if(L.code!=="ENOENT")return{type:"failed"}}return{...N1,type:"success"}}})}]:[]]}var c$={rpcRoot:"openai-auth",directoryPrefix:fH,registrationSessionId:"process"};function t7(X,J){vH(c$,X,J)}function gH(X=0,J){return yH(c$,X,J)}function mH(X){return hH(c$,X)}var e7=Z0("commands");function N4(X){return{configPath:X.accountStoragePath,statePath:X.accountStatePath}}function l$(X){return`${String(X.startHour).padStart(2,"0")}-${String(X.endHour).padStart(2,"0")}`}function HA(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 VA="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 UA(X){let J=($)=>K1(X.store(),B9(N4(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=P7(await X.loadAccounts(N4(X))),G=Y?.enabled===!0,Q=Y?.subagents===!0,z=$.status(),Z=z.window?l$(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 e7.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?VA:"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:l$(z.window)}:{}}],run:async({values:W})=>{let B=W.window;if(typeof B!=="string"||B.trim()==="")return await J((N)=>{delete N.startHour,delete N.endHour}),X.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let H=HA(B);if(!H.ok)return{ok:!1,text:`Invalid window: ${H.reason}`};let{startHour:U,endHour:j}=H;return await J((N)=>{N.startHour=U,N.endHour=j}),X.setCacheKeepWindow?.({startHour:U,endHour:j}),`Warming limited to ${l$(H)} local hours.`}}]}}}}var uH=["error","warn","info","debug","trace"];function KA(X){return{title:"Diagnostics",build:async()=>{let J=c6(),Y=(await X.loadAccounts(N4(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 K1(X.store(),B9(N4(X)),(Z)=>{Z.dump={...Z.dump??{},enabled:Q}});let z=sB();return e7.info(Q?"request dump enabled":"request dump disabled"),Q?`Request dumps are on, written to ${z.dumpDir}.
159
159
 
160
- 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:kH.map((G)=>({value:G,label:G})),value:kH.includes(Y)?Y:"info"}],run:async({values:G})=>{let Q=String(G.level);return await K1(X.store(),W9(j4(X)),(z)=>{z.logging={...z.logging??{},level:Q}}),t7(Q),r7.info("log level changed",{level:Q}),`Log level set to ${Q}.`}}]}}}}async function GA(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 xH(X){let J=j4(X),$=W9(J),Y=X.resolveResetTarget&&X.refreshResetTargetQuota&&X.fetchImpl&&X.now&&X.randomUUID?T$({configPath:J.configPath,statePath:J.statePath,quotaManager:X.quotaManager,loadAccounts:X.loadAccounts,mutateAccounts:M$(X.store(),$),resolveResetTarget:X.resolveResetTarget,refreshResetTargetQuota:X.refreshResetTargetQuota,fetchImpl:X.fetchImpl,now:X.now,randomUUID:X.randomUUID,accountKeys:()=>GA(X)}):void 0,G=X.beginAccountLogin;return R$({store:X.store(),...X.vault?{vault:X.vault}:{},...X.now?{now:X.now}:{},extraLocks:$,rowLocks:(Q)=>f8(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)=>n7(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 b6("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(`
161
- `))}}:{},cache:$A(X),diagnostics:YA(X),extras:[...Y?[Y]:[],_$({...X.getStickyRouting?{getPin:X.getStickyRouting}:{},...X.clearStickyRouting?{clearPin:X.clearStickyRouting}:{}}),...X.vault?[A$({vault:X.vault,changed:X.afterWrite})]:[]],afterApply:async()=>{await X.afterWrite?.(),await X.refreshSidebar?.().catch(()=>{})}})}function wH(X){return(J,$="info")=>{r7.info("menu notification",{sessionId:X,kind:$}),o7({command:u6,notify:{message:J,kind:$}},X)}}function vH(X,J){return xH(X).open({...J!==void 0?{sessionId:J}:{},notify:wH(J)})}function yH(X,J){return xH(X).apply(J,{...J.sessionId!==void 0?{sessionId:J.sessionId}:{},notify:wH(J.sessionId)})}function hH(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(`
162
- `)}var QA=300000,zA=30000,fH=240000,ZA="bg-quota-refresh",WA=120000;function u$(X,J){return g0({name:ZA,ttlMs:WA,path:X,renew:!0,...J})}function gH(X,J=Y4,$=()=>u$(X.paths.configPath)){return BA(X,J,$)}function BA(X,J,$){return mH(async()=>J({...X,respectBackoff:!0,skipFresherThanMs:fH}),$,[])}async function mH(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 uH(X,J,$){return mH(async()=>{return await X.refreshDueTokens(J),X.pollRows(J,{skipReadWithinMs:fH})},$,[])}class p${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)*zA);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},QA+$),"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 c$(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 T3(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 HA=300000,VA=3600000,UA=1800000,KA=60000,jA=32,qA=8388608,NA=30000,LA=600000;function u8(X,J){return typeof X==="number"&&Number.isFinite(X)&&X>0?X:J}function e7(X){return X instanceof Error?X.message:String(X)}class R3{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=u8(X.ttlMs,HA),this.tickIntervalMs=u8(X.tickIntervalMs,KA),this.leadMs=u8(X.leadMs,this.tickIntervalMs+15000),this.maxIdleWarmMs=u8(X.maxIdleWarmMs,VA),this.maxSubagentIdleMs=u8(X.maxSubagentIdleMs,UA),this.maxTargets=u8(X.maxTargets,jA),this.maxBytes=u8(X.maxBytes,qA),this.warmTimeoutMs=u8(X.warmTimeoutMs,NA),this.backoff=X.backoffMs??LA,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&&!T3(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=u8(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?u8(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:e7(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&&!T3(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:e7(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:e7(H)});return}if(!this.isCurrent(X,J))return;if(this.retireIfExpired(X,J))return;let G=r4([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:e7(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 l$(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 d$(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 XX(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"),l$(X.body))J.set("x-openai-internal-codex-responses-lite","true");return{...X,headers:J,body:d$(X.body)}}function cH(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 lH(X){return c$(X?.cachekeep)}var i$=1800000,DA=2,FA=2*i$+900000,PA=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/;function OA(X){try{let $=JSON.parse(X).model;if(typeof $!=="string")return!1;let Y=PA.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 MA(X){if(!OA(X.bodyText))return;if(!X.isSubagent)return{ttlMs:i$};return{ttlMs:i$,maxWarms:DA,maxIdleMs:FA}}function _A(X){let $=JSON.parse(X);return $.store=!1,delete $.max_output_tokens,delete $.max_tokens,delete $.max_completion_tokens,JSON.stringify($)}function n$(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function dH(X){if(!X||typeof X!=="object")return n$();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 AA(X){try{let J=JSON.parse(X);return dH(J.usage)}catch{return n$()}}function TA(X){let J,$=[],Y,G=()=>{if(!$.length)return;let Q=$.join(`
163
- `).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=dH(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??n$()}function iH(X,J,$=Date.now()){if(!J)return;if(X.route==="sticky-balanced"){let G=X.stickyAssignments?.[p8(J)];if(!G)return;if(G.lastSeenAt<$-pH)return;return G.accountId}let Y=X.activeRouting?.[J];if(!Y||Y.route!==X.route)return;return Y.activeId}function RA(X){let{logger:J,activeAccount:$}=X;return{buildBody:(Y)=>_A(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{}J?.debug("cachekeep warm request",{...j,headerKeys:Object.keys(U),hasChatGptAccountId:"ChatGPT-Account-Id"in U});try{let q=await X.fetchImpl(X.codexResponsesUrl,XX({method:"POST",headers:U,body:G,signal:Q}));return await j1(q,H,"event-stream")}catch(q){throw K8(q,H)}};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?TA(G):AA(G),W=o9(Y.headers);return{...Z,quota_primary_pct:W.primary?.usedPercent??null,quota_secondary_pct:W.secondary?.usedPercent??null}},profile:MA,...$?{activeAccount:(Y,G)=>$(G.meta.routingSessionId)}:{}}}function nH(X){let{fetchImpl:J,getMainToken:$,refreshFallback:Y,vault:G,codexResponsesUrl:Q,activeAccount:z,logger:Z,...W}=X;return new R3({...W,logger:Z,adapter:RA({fetchImpl:J,getMainToken:$,refreshFallback:Y,vault:G,codexResponsesUrl:Q,activeAccount:z,logger:Z})})}import{readFileSync as CA,statSync as EA}from"node:fs";var SA=60000,IA=15000,sH=30000,s$=2000,a$=1e4;async function E3(X,J){let $,Y=await Promise.race([X.then(()=>!0,()=>!0),new Promise((G)=>{$=setTimeout(()=>G(!1),J),$.unref?.()})]);return clearTimeout($),Y}var bA=8,kA=1800000;function xA(X){if(!G6(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=V6(X);return J?U6(J):void 0}function aH(X){try{let J=EA(X);return`${J.ino}:${J.size}:${J.mtimeMs}`}catch{return"-"}}function vA(X){try{let J=JSON.parse(CA(X,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return;return q6(J).migratedAt}catch{return}}function yA(X){if(X.type!=="oauth")return!1;return X.candidate||X.torn===!0&&X.enabled}function JX(X){return X.identity?`identity:${X.identity}`:`row:${X.id}`}function C3(X){let J=X.credential;if(J?.type!=="oauth")return;return{access:J.access??"",expires:J.expires,refresh:J.refresh}}class o${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 E3(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 YX(J,this.deps.readBudgetMs??$X,()=>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}|${aH(X.configPath)}|${aH(X.statePath)}`}storeFor(X){if(this.store?.configPath===X.configPath)return this.store.store;let J=Q8({provider:"openai",configPath:X.configPath,statePath:X.statePath,quota:m8,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(vA($.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(JX($))??[]).filter((Z)=>J-Z.observation.checkedAt<=kA);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 B7(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,E3(X,this.deps.vaultFirstRosterBackgroundWaitMs??a$).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(!yA(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??IA))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 $=JX(X),Y=[...this.pending.get($)??[],{credentialEpoch:X.credentialEpoch,identity:X.identity,observation:J}].slice(-bA);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:C3(G)?.access===$))return;let Z=S9(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=JX($),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(JX($));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??s$);let Y=this.now(),G=nJ(J),Q=[];for(let z of X){if(!z.candidate||this.vaultOwned(z))continue;let Z=C3(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<=SA)Q.push(H)}await Promise.all(Q)}refreshBackedOff(X,J,$=this.now()){let Y=C3(X);if(!Y)return!1;let G=z8(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&&r0(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=C3($);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=$?C3($)?.refresh:void 0,G,Q=(z,Z)=>{return G=Z.credentialEpoch,this.deps.refreshProvider(z,Z)};try{let z=await GH({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=z8(J),Q=this.backoff.get(X);if(typeof $?.status==="number"||I5($)){let Z=p1({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+sH,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+sH)}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=xA(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 oH=60000,r$=900000,hA={set(X,J){let $=setTimeout(X,J);return $.unref?.(),$},clear(X){clearTimeout(X)}};function fA(X){return X.status==="completed"||X.status==="already-migrated"||X.status==="nothing-to-import"||X.status==="ambiguous"}function rH(X){return X.status==="deferred"||X.status==="retry"||X.status==="error"}function tH(X){let J=X.log??Z0("pool-migration"),$=X.timers??hA,Y=X.random??Math.random,G=X.migrate??c7,Q=X.adopt??l7,z=X.fence??(()=>K4({currentVersion:X.version})),Z=!1,W=!1,B=!1,H=0,U,j=Promise.resolve(),q,K,N,F=!1;function O(){if(F)return;F=!0,J.warn(V4,{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 L(w){if(W)return;if(U!==void 0)$.clear(U);U=$.set(()=>{U=void 0,C(i)},w)}function P(){let w=Math.min(oH*2**Math.min(H,10),r$);return H++,A(w)}let A=(w)=>Math.round(w*(1-0.2*Y()));async function T(){if(!await X.paused?.())return!1;return L(A(oH)),!0}async function k(){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)}),L(P());return}if(w.status==="refused"){if(w.reason==="placeholder-without-main")O();L(A(r$));return}if(fA(w)){if(B=!0,H=0,w.status==="completed")J.info("account pool migration completed",{rowId:w.rowId});await p();return}if(rH(w)){if(w.status!=="deferred")J.warn("account pool migration will be tried again",{outcome:w});L(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!==N)N=G0,J.info("host login adoption waits for older plugin versions",{blockers:J0.blockers});L(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)}),L(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(rH(w)){J.warn("host login adoption will be tried again",{outcome:w}),L(P());return}if(H=0,B)L(A(r$))}async function i(){if(W)return;if(B)await p();else await k()}function X0(){if(q)return q;let w=C(async()=>{if(q=void 0,!W)if(B)await p();else await k()});return q=w,w}return{start(){if(Z||W)return;Z=!0,C(k)},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 c6="main",XV=5;function JV(X){if(X==="ordered")return"roster";return X==="fallback-first"?"fallback-first":"main-first"}function t$(X){return X.reason==="exhausted"||X.reason==="budget-spent"}function $V(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 eH(X,J,$){if(J.refused.find((G)=>!t$(G)&&$.get(G.id)!==!1))return{reason:"quota-unknown"};return $V(X[0],J,$)}function YV(X){let J=X.replayable!==!1,$=J?X.placement:"main-first",Y=oX({rows:X.rows,placement:$,formerMainId:c6,killswitch:X.killswitch,rateLimitMarks:X.rateLimitMarks,refreshBackoff:X.refreshBackoff,now:X.now,requestPull:X.requestPull}),G=k1(X.rows.map((Z)=>Z.id),$,c6),Q=new Set(Y.admission.refused.filter((Z)=>t$(Z)&&X.killswitch.get(Z.id)!==!1).map((Z)=>Z.id)),z=G.filter((Z)=>Q.has(Z));if(!J){let Z=G.includes(c6),W=Z?c6: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?$V(c6,Y.admission,X.killswitch):eH(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:eH(G,Y.admission,X.killswitch)}}function e$(X){let J=p9({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 GV(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 Y5({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 QV(X,J,$,Y){let G=GV(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 zV(X,J,$){let Y=X.killswitch.get($)===!1,G=GV(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&&t$(Q))return{kind:"last-path"};return{kind:"none"}}function ZV(X,J,$,Y){let G=X.killswitch.get($);return $5({quota:J.projections.get($),now:X.now,...Y===void 0?{}:{status:Y},...G===void 0?{}:{killswitchPasses:G}})}var D1={"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.",...Y$};function $Y(X){return X!==void 0&&X in Y$}function gA(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===c6)return!0;if(G9(J,{accountId:G.identity}))return!1;return H3(x8(G.quota),J,$)})}function BV(X){let J=X.vault;return[...(J?[]:gA(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)=>H3(x8(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 mA(X){return X.flatMap((J)=>J.row?[J.row]:[])}function XY(X,J){let $=X.now(),Y=new Map;if(Q9(X.storage))for(let W of J)Y.set(W.id,Z1(x8(W.quota),X.storage,W.id===c6?void 0:W.id,$));let G=J.map((W)=>({id:W.id,kind:W.kind,...G6(W.quota)?{quota:W.quota}:{}})),Q=mA(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 WV(X){let J=X.find(($)=>$.id===c6);return{main:J?x8(J.quota):void 0,fallbacks:X.filter(($)=>$.id!==c6).map(($)=>{let Y=x8($.quota);return{accountId:$.id,...Y?{quota:Y}:{}}})}}async function JY(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 HV(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=BV(X);if(X.mode==="sticky-balanced"&&X.sessionId&&X.replayable&&X.body!==void 0){let $=await pA(X,J,X.sessionId,X.body);if($)return $}return uA(X,J)}async function uA(X,J){let $=JV(X.mode),Y=YV({...XY(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,WV(J),X.vault?J.length===0?X.vault.noRouteCause():void 0:J.length===0?"no-accounts":"unusable"),servedId:c6};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=iJ(X.storage),z=[],Z=new Set,W,B=!1;for(;;){let H=rX(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 JY(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"},WV(J),B?"vault-refused":X.vault?"vault-empty":"unusable"),servedId:c6}}async function pA(X,J,$,Y){let G=Buffer.byteLength(Y,"utf8"),Q=new Map(J.map((O)=>[O.id,O])),z=XY(X,J),Z=e$(z),W={requestBytes:G,reservePercent:(O)=>s6(X.storage,O===c6?void 0:O),resetCredits:X.resetCredits,onEmptyWeightedSet:()=>{X.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},B=(O,_)=>(C,L)=>{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)=>QV(O,W,P,A),persist:L})},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=zV(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 N=Q.get(j);if(!N)return;let F=await JY(X,N);if(!F)return;if(F.status===401||F.status===403||F.status===429){let O=BV(X);z=XY(X,O),Z=e$(z),H=B(z,Z);let _=ZV(z,Z,j,F.status);if(_.action==="migrate"){let C=j;if(q(_.reason)&&j!==C){let L=O.find((A)=>A.id===j),P=L?await JY(X,L):void 0;if(L&&P){let A=F;F=P,A.body?.cancel().catch(()=>{}),N=L}else j=C}}}return{response:F,servedId:N.id}}function S3(X){return typeof X==="number"&&Number.isFinite(X)}function cA(X){if(!G6(X))return;let J=X.budget;if(J?.kind!=="reading")return;let{limit:$,used:Y,remaining:G,usedPercent:Q,remainingPercent:z}=J;if(!S3($)||!S3(Y)||!S3(G)||!S3(Q)||!S3(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 YY(X,J){let $=x8(X),Y=cA(X);if(!$&&!Y)return null;let G=G6(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 VV(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:YY(G.quota),killed:!1,enabled:J.has(G.routeId)})),route:$?.routing?.mode??"main-first",lastUpdated:Y}}function UV(X,J,$,Y=()=>{return}){let G=X.find((z)=>z.id===U8),Q=G?Y(G.id):void 0;return{main:{quota:G?YY(G.quota,Q):null,...G?.identity!==void 0?{mainAccountId:G.identity}:{},killed:!1,...Q!==void 0?{resetCredits:Q}:{}},fallbacks:X.filter((z)=>z.id!==U8&&z.enabled).map((z)=>{let Z=Y(z.id);return{id:z.id,label:z.label,...z.identity!==void 0?{accountId:z.identity}:{},quota:YY(z.quota,Z),killed:!1,enabled:!0,...Z!==void 0?{resetCredits:Z}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:$,accountPool:!0}}import{randomUUID as lA}from"node:crypto";import{chmod as dA,mkdir as iA,rename as nA,rm as jV,writeFile as sA}from"node:fs/promises";import{homedir as aA}from"node:os";import{join as GY}from"node:path";function qV(){let X=process.env.XDG_STATE_HOME||GY(aA(),".local","state");return GY(X,"cortexkit","openai-auth","processes")}function NV(X=process.pid,J=qV()){return GY(J,`${X}.json`)}var GX=0,KV;async function oA(X,J){await iA(X,{recursive:!0,mode:448}),await dA(X,448);let $=NV(J.pid,X),Y=`${$}.${lA()}.tmp`;try{await sA(Y,`${JSON.stringify(J)}
164
- `,{mode:384}),await nA(Y,$)}catch(G){throw await jV(Y,{force:!0}).catch(()=>{}),G}return $}async function LV(X){let J=X.pid??process.pid,$=X.dir??qV();KV??=(X.now??Date.now)(),GX++;let Y;try{Y=await oA($,{pid:J,version:X.version,startedAt:KV})}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,GX=Math.max(0,GX-1),GX>0)return;await jV(NV(J,$),{force:!0}).catch((Q)=>{X.logger.warn("process heartbeat not removed",{dir:$,error:Q instanceof Error?Q.message:String(Q)})})}}}import{resolve as QX}from"node:path";var rA=60000,tA=240000,DV=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),FV=globalThis,I3=FV[DV]??new Map;FV[DV]=I3;function PV(X,J){let $=Boolean(X.connectScoped||X.connectEnrollment),Y=QX(X.stateDir),G=QX((X.connectionFile??e9)()),Q=JSON.stringify([X.host,Y,G,QX(J.configPath),QX(J.statePath)]),z={reservedRouteIds:X.reservedRouteIds??(()=>[])},Z=$?void 0:I3.get(Q);if(!Z){let H=new Set;if(Z={vault:new G$({...X,stateDir:Y,connectionFile:()=>G,...!$?{projectRoot:Y}:{},reservedRouteIds:()=>new Set([...H].flatMap((j)=>[...j.reservedRouteIds()]))}),holders:H,firstRoster:Promise.withResolvers(),started:!1},!$)I3.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(tA)};W.vault.start(),W.vault.firstRoster().finally(()=>{W.firstRoster.resolve(),H()}),W.quotaPoll=setInterval(H,rA),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(),!$&&I3.get(Q)===W)I3.delete(Q)}}}var TV=900000,eA=0.016666666666666666,OV=0.000001;function zY(X,J){for(let $ of[X?.primary?.checkedAt,X?.checkedAt,J])if(typeof $==="number"&&Number.isFinite($))return $;return}function ZY(X){if(X.status===401||X.status===403)return{action:"migrate",reason:"permanent"};if(!X.quota)return{action:"retain",reason:"unknown"};let J=zY(X.quota,X.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||X.now-J>TV)return{action:"retain",reason:"stale"};if(X.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let $=QY(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=AV(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 MV(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,eA);return Y/Q}function _V(X,J){if(X<J)return-1;if(X>J)return 1;return 0}function XT(X,J){if(!X.quota)return;let $=zY(X.quota,X.quotaCheckedAt);if($===void 0||J-$>TV)return;let Y=QY(X.quota).map(({key:z,window:Z})=>{return MV(Z,X.reservePercent[z]??0,J)}),G=X.quota.spendControl;if(G&&Number.isFinite(G.remainingPercent))Y.push(MV(G,0,J));let Q=Y.length>0?Math.min(...Y):0;return Q>0?{candidate:X,quotaCheckedAt:$,weight:Q}:void 0}function RV(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)=>XT(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,OV),W=((X.pendingBytes.get(z.candidate.accountId)??0)+X.requestBytes)/Math.max(z.weight,OV);return Z-W||Q.candidate.configuredOrder-z.candidate.configuredOrder||_V(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||_V(G.accountId,Q.accountId)})[0];if(!Y)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Y.accountId,quotaCheckedAt:zY(Y.quota,Y.quotaCheckedAt),source:"mode-fallback"}}import{createHash as PT}from"node:crypto";import{createHash as JT,randomBytes as $T}from"node:crypto";import{chmod as YT,lstat as CV,mkdir as GT,open as QT,readdir as kV,readFile as EV,rename as zT,unlink as VY,writeFile as ZT}from"node:fs/promises";import{join as zX,resolve as WY}from"node:path";var WT=100,BY="session-unknown",BT=300000,HT=60000,VT=600000,UT=/\.(body|meta|request|response)\.json$/,KT=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,jT=/\.[a-f0-9]{24}\.partial$/;function xV(X){let J=X.replace(UT,"");if(J===X||!KT.test(J))return;return J}function qT(X){let J=X.replace(jT,"");return J!==X&&xV(J)!==void 0}async function SV(X){let{dir:J,maxBytes:$}=X,Y=X.now??Date.now(),G=X.minAgeMs??HT,Q=X.partialStaleMs??VT,z={removed:0,freedBytes:0};if(!($>0))return z;try{if((await CV(J)).isSymbolicLink())return z;let Z=new Set((X.protectedPaths??[]).map((F)=>WY(F))),W=await kV(J,{withFileTypes:!0}),B=[];await Promise.all(W.map(async(F)=>{if(!F.isFile())return;let O=qT(F.name),_=O?void 0:xV(F.name);if(!O&&_===void 0)return;let C=zX(J,F.name);try{let L=await CV(C);if(!L.isFile())return;B.push({path:C,size:L.size,mtimeMs:L.mtimeMs,group:_})}catch{}}));let H=B.reduce((F,O)=>F+O.size,0),U=0,j=0,q=async(F)=>{try{await VY(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(WY(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 N=[...K.entries()].sort(([F,O],[_,C])=>O.newest-C.newest||F.localeCompare(_));for(let[,F]of N){if(H<=$)break;if(Y-F.newest<G)continue;if(F.files.some((O)=>Z.has(WY(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 NT(X,J,$){for(let Y=0;;Y+=1){let G=`${X}.${$?$():$T(12).toString("hex")}.partial`,Q=!1,z;try{z=await QT(G,"wx",384),Q=!0,await z.writeFile(J,"utf8"),await z.chmod(384),await z.close(),z=void 0,await zT(G,X);return}catch(Z){if(await z?.close().catch(()=>{}),Q)await VY(G).catch(()=>{});if(Z.code==="EEXIST"&&Y===0)continue;throw Z}}}function HY(X){return X.length<=16?X:`${X.slice(0,12)}…`}function b3(X,J){let $=X.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!$)return J;return $.slice(0,80)}function IV(X){return JT("sha256").update(X).digest("hex")}function LT(X){return X.toLowerCase().replace(/[-_]/g,"")}function bV(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function DT(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 FT=0;function wV(X){let J=X.enabled===!0,$=X.pid??process.pid,Y=X.now??Date.now,G=X.logger,Q=new Set((X.secretKeys??[]).map(LT)),z=T2({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 k=z.redact({[T]:null})[T];return k===null?void 0:k}function U(T){if(Array.isArray(T))return T.map(U);if(bV(T)){let k={};for(let[p,i]of Object.entries(T)){let X0=H(p);if(Z.has(p))k[p]=z.redactStrings(i);else if(X0!==void 0)k[p]=X0;else k[p]=U(i)}return k}return z.redactStrings(T)}function j(T){let k;try{k=JSON.parse(T)}catch{return{text:z.redactStrings(T),parsed:void 0}}let p=U(k),i=JSON.stringify(p);return{text:JSON.stringify(k)===i?T:i,parsed:bV(p)?p:void 0}}async function q(T,k,p,i){let X0=`-${b3(k,BY)}-${b3(p,"channel")}`,w;try{w=await kV(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 EV(zX(T,G0),"utf8"))?.baselineKey!==i)continue;return await EV(zX(T,G0.replace(/\.meta\.json$/,".body.json")),"utf8")}catch{}return}function K(T,k){if(!W.has(T))while(W.size>=WT){let p=W.keys().next().value;if(p===void 0)break;W.delete(p)}W.set(T,k)}async function N(T){if(!J)return;let k=++FT,p=T.session?.trim()||BY,i=B(),X0=new Date(Y()).toISOString(),w=[X0.replace(/[:.]/g,"-"),String($),String(k).padStart(6,"0"),b3(p,BY),b3(T.channel,"channel"),...T.phase?[b3(T.phase,"phase")]:[]].join("-"),J0=zX(i,w),G0={body:`${J0}.body.json`,metadata:`${J0}.meta.json`,request:`${J0}.request.json`},L0=IV(`${T.channel}\x00${p}`);try{await GT(i,{recursive:!0,mode:448}),await YT(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:HY(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:IV(T.bodyText),diff:DT(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)=>ZT(e,c,{encoding:"utf8",mode:384,flag:"wx"}),t=[[G0.body,m0.text],[G0.metadata,`${JSON.stringify(r,null,2)}
160
+ 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:uH.map((G)=>({value:G,label:G})),value:uH.includes(Y)?Y:"info"}],run:async({values:G})=>{let Q=String(G.level);return await K1(X.store(),B9(N4(X)),(z)=>{z.logging={...z.logging??{},level:Q}}),XX(Q),e7.info("log level changed",{level:Q}),`Log level set to ${Q}.`}}]}}}}async function jA(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 pH(X){let J=N4(X),$=B9(J),Y=X.resolveResetTarget&&X.refreshResetTargetQuota&&X.fetchImpl&&X.now&&X.randomUUID?C$({configPath:J.configPath,statePath:J.statePath,quotaManager:X.quotaManager,loadAccounts:X.loadAccounts,mutateAccounts:A$(X.store(),$),resolveResetTarget:X.resolveResetTarget,refreshResetTargetQuota:X.refreshResetTargetQuota,fetchImpl:X.fetchImpl,now:X.now,randomUUID:X.randomUUID,accountKeys:()=>jA(X)}):void 0,G=X.beginAccountLogin;return E$({store:X.store(),...X.vault?{vault:X.vault}:{},...X.now?{now:X.now}:{},extraLocks:$,rowLocks:(Q)=>f8(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)=>a7(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 k6("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(`
161
+ `))}}:{},cache:UA(X),diagnostics:KA(X),extras:[...Y?[Y]:[],T$({...X.getStickyRouting?{getPin:X.getStickyRouting}:{},...X.clearStickyRouting?{clearPin:X.clearStickyRouting}:{}}),...X.vault?[R$({vault:X.vault,changed:X.afterWrite})]:[]],afterApply:async()=>{await X.afterWrite?.(),await X.refreshSidebar?.().catch(()=>{})}})}function cH(X){return(J,$="info")=>{e7.info("menu notification",{sessionId:X,kind:$}),t7({command:p6,notify:{message:J,kind:$}},X)}}function lH(X,J){return pH(X).open({...J!==void 0?{sessionId:J}:{},notify:cH(J)})}function dH(X,J){return pH(X).apply(J,{...J.sessionId!==void 0?{sessionId:J.sessionId}:{},notify:cH(J.sessionId)})}function iH(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(`
162
+ `)}var NA=300000,qA=30000,nH=240000,LA="bg-quota-refresh",DA=120000;function d$(X,J){return g0({name:LA,ttlMs:DA,path:X,renew:!0,...J})}function sH(X,J=G4,$=()=>d$(X.paths.configPath)){return FA(X,J,$)}function FA(X,J,$){return aH(async()=>J({...X,respectBackoff:!0,skipFresherThanMs:nH}),$,[])}async function aH(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 oH(X,J,$){return aH(async()=>{return await X.refreshDueTokens(J),X.pollRows(J,{skipReadWithinMs:nH})},$,[])}class i${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)*qA);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},NA+$),"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 n$(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 E3(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 PA=300000,OA=3600000,MA=1800000,_A=60000,AA=32,TA=8388608,RA=30000,CA=600000;function u8(X,J){return typeof X==="number"&&Number.isFinite(X)&&X>0?X:J}function JX(X){return X instanceof Error?X.message:String(X)}class S3{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=u8(X.ttlMs,PA),this.tickIntervalMs=u8(X.tickIntervalMs,_A),this.leadMs=u8(X.leadMs,this.tickIntervalMs+15000),this.maxIdleWarmMs=u8(X.maxIdleWarmMs,OA),this.maxSubagentIdleMs=u8(X.maxSubagentIdleMs,MA),this.maxTargets=u8(X.maxTargets,AA),this.maxBytes=u8(X.maxBytes,TA),this.warmTimeoutMs=u8(X.warmTimeoutMs,RA),this.backoff=X.backoffMs??CA,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&&!E3(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=u8(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?u8(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:JX(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&&!E3(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:JX(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:JX(H)});return}if(!this.isCurrent(X,J))return;if(this.retireIfExpired(X,J))return;let G=e4([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:JX(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 s$(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 a$(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 $X(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"),s$(X.body))J.set("x-openai-internal-codex-responses-lite","true");return{...X,headers:J,body:a$(X.body)}}function tH(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 eH(X){return n$(X?.cachekeep)}var o$=1800000,EA=2,SA=2*o$+900000,IA=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/;function bA(X){try{let $=JSON.parse(X).model;if(typeof $!=="string")return!1;let Y=IA.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 kA(X){if(!bA(X.bodyText))return;if(!X.isSubagent)return{ttlMs:o$};return{ttlMs:o$,maxWarms:EA,maxIdleMs:SA}}function xA(X){let $=JSON.parse(X);return $.store=!1,delete $.max_output_tokens,delete $.max_tokens,delete $.max_completion_tokens,JSON.stringify($)}function r$(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function XV(X){if(!X||typeof X!=="object")return r$();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 wA(X){try{let J=JSON.parse(X);return XV(J.usage)}catch{return r$()}}function vA(X){let J,$=[],Y,G=()=>{if(!$.length)return;let Q=$.join(`
163
+ `).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=XV(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??r$()}function JV(X,J,$=Date.now()){if(!J)return;if(X.route==="sticky-balanced"){let G=X.stickyAssignments?.[p8(J)];if(!G)return;if(G.lastSeenAt<$-rH)return;return G.accountId}let Y=X.activeRouting?.[J];if(!Y||Y.route!==X.route)return;return Y.activeId}function yA(X){let{logger:J,activeAccount:$}=X;return{buildBody:(Y)=>xA(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 N=JSON.parse(G);j={warmBodyKeys:Object.keys(N),stream:N.stream,max_output_tokens:N.max_output_tokens,store:N.store,has_stream_options:"stream_options"in N,has_max_tokens:"max_tokens"in N,model:N.model}}catch{}J?.debug("cachekeep warm request",{...j,headerKeys:Object.keys(U),hasChatGptAccountId:"ChatGPT-Account-Id"in U});try{let N=await X.fetchImpl(X.codexResponsesUrl,$X({method:"POST",headers:U,body:G,signal:Q}));return await j1(N,H,"event-stream")}catch(N){throw j8(N,H)}};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?vA(G):wA(G),W=o9(Y.headers);return{...Z,quota_primary_pct:W.primary?.usedPercent??null,quota_secondary_pct:W.secondary?.usedPercent??null}},profile:kA,...$?{activeAccount:(Y,G)=>$(G.meta.routingSessionId)}:{}}}function $V(X){let{fetchImpl:J,getMainToken:$,refreshFallback:Y,vault:G,codexResponsesUrl:Q,activeAccount:z,logger:Z,...W}=X;return new S3({...W,logger:Z,adapter:yA({fetchImpl:J,getMainToken:$,refreshFallback:Y,vault:G,codexResponsesUrl:Q,activeAccount:z,logger:Z})})}import{readFileSync as hA}from"node:fs";var fA=60000,gA=15000,t$=2000,e$=1e4;async function I3(X,J){let $,Y=await Promise.race([X.then(()=>!0,()=>!0),new Promise((G)=>{$=setTimeout(()=>G(!1),J),$.unref?.()})]);return clearTimeout($),Y}function mA(X){if(!G6(X.quota))return;let J=f0(X.quota);return J.limits.some(($)=>$.kind==="reading")?J.checkedAt:void 0}function uA(X){if(!X)return;let J=V6(X);return J?U6(J):void 0}function pA(X){try{let J=JSON.parse(hA(X,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return;return N6(J).migratedAt}catch{return}}function cA(X){if(X.type!=="oauth")return!1;return X.candidate||X.torn===!0&&X.enabled}class XY{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;quotaPulls=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 I3(J,X)}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}async current(){if(this.disposed)return this.peek();let X=this.filesKey();if(this.snapshot.key===X)return this.peek();let J=this.startRead(X),$=await GX(J,this.deps.readBudgetMs??YX,()=>this.snapshot);return{active:$.active,rows:$.rows}}async load(){if(this.disposed)return this.peek();if(await this.deps.vaultAuthority?.(),this.disposed)return this.peek();let X=await this.startRead(this.filesKey());return{active:X.active,rows:X.rows}}filesKey(){let X=this.deps.paths();return`${X.configPath}|${S$(X.configPath)}|${S$(X.statePath)}`}storeFor(X){if(this.store?.configPath===X.configPath)return this.store.store;let J=z8({provider:"openai",configPath:X.configPath,statePath:X.statePath,quota:m8,now:this.now,pull:($)=>this.coalescedPull($),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.disposed)return Promise.resolve(this.snapshot);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(pA($.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}if(this.disposed)return 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,Z=Q.lastRefreshedAt??0;if(z>=Z)this.rotated.delete($.id);else Y={...Y,credential:Q}}return fB(Y,this.pending,J)})}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,I3(X,this.deps.vaultFirstRosterBackgroundWaitMs??e$).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(!cA(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.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set(X,$);let G=this.storeFor(this.deps.paths());return G.requestReading(X),G.pullsSettled()}coalescedPull(X){let J=JSON.stringify([this.deps.paths().configPath,X.id,X.credentialEpoch,X.identity]),$=this.quotaPulls.get(J);if($)return $;let Y=this.pull(X).finally(()=>this.quotaPulls.delete(J));return this.quotaPulls.set(J,Y),Y}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){hB(this.pending,X,J),this.replaceRow(X.id,($)=>({...$,quota:I$($.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=uA($);if(!(Q&&G.identity?Q===G.identity:Y4(G)?.access===$))return;let Z=I9(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=P3($),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(P3($));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??t$);let Y=this.now(),G=aJ(J),Q=[];for(let z of X){if(!z.candidate||this.vaultOwned(z))continue;let Z=Y4(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<=fA)Q.push(H)}await Promise.all(Q)}refreshBackedOff(X,J,$=this.now()){let Y=Y4(X);if(!Y)return!1;let G=s6(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&&r0(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=Y4($);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=$?Y4($)?.refresh:void 0,G,Q=(z,Z)=>{return G=Z.credentialEpoch,this.deps.refreshProvider(z,Z)};try{let z=await KH({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;this.backoff.set(X,gB(J,$,this.now(),this.backoff.get(X)))}refreshBackoffFor(X){return mB(X,this.backoff,this.now(),(J,$)=>this.usableToken(J,$))}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=mA(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(),...this.inflightRead?[this.inflightRead.promise]:[]];if(await Promise.allSettled(X),await this.store?.store.pullsSettled(),this.writes.size===0&&this.refreshing.size===0&&!this.inflightRead)return}}}var YV=60000,JY=900000,lA={set(X,J){let $=setTimeout(X,J);return $.unref?.(),$},clear(X){clearTimeout(X)}};function dA(X){return X.status==="completed"||X.status==="already-migrated"||X.status==="nothing-to-import"||X.status==="ambiguous"}function GV(X){return X.status==="deferred"||X.status==="retry"||X.status==="error"}function QV(X){let J=X.log??Z0("pool-migration"),$=X.timers??lA,Y=X.random??Math.random,G=X.migrate??d7,Q=X.adopt??i7,z=X.fence??(()=>j4({currentVersion:X.version})),Z=!1,W=!1,B=!1,H=0,U,j=Promise.resolve(),N,K,q,F=!1;function O(){if(F)return;F=!0,J.warn(U4,{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 L(w){if(W)return;if(U!==void 0)$.clear(U);U=$.set(()=>{U=void 0,C(i)},w)}function P(){let w=Math.min(YV*2**Math.min(H,10),JY);return H++,A(w)}let A=(w)=>Math.round(w*(1-0.2*Y()));async function T(){if(!await X.paused?.())return!1;return L(A(YV)),!0}async function k(){if(W||await T()||W)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)}),L(P());return}if(w.status==="refused"){if(w.reason==="placeholder-without-main")O();L(A(JY));return}if(dA(w)){if(B=!0,H=0,w.status==="completed")J.info("account pool migration completed",{rowId:w.rowId});await p();return}if(GV(w)){if(w.status!=="deferred")J.warn("account pool migration will be tried again",{outcome:w});L(P())}}async function p(){if(W||await T()||W)return;let w;try{let J0=await z();if(W)return;if(!J0.open){let G0=JSON.stringify(J0.blockers);if(G0!==q)q=G0,J.info("host login adoption waits for older plugin versions",{blockers:J0.blockers});L(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)}),L(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(GV(w)){J.warn("host login adoption will be tried again",{outcome:w}),L(P());return}if(H=0,B)L(A(JY))}async function i(){if(W)return;if(B)await p();else await k()}function X0(){if(N)return N;let w=C(async()=>{if(N=void 0,!W)if(B)await p();else await k()});return N=w,w}return{start(){if(Z||W)return;Z=!0,C(k)},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 E6="main";function ZV(X,J,$){let Y=new Map;if(z9(J))for(let G of X)Y.set(G.id,Z1(K8(G.quota),J,G.id===E6?void 0:G.id,$));return Y}var WV=5,iA=5000;function BV(X){if(X==="ordered")return"roster";return X==="fallback-first"?"fallback-first":"main-first"}function HV(X,J=iA){let $=X.rows.filter((z)=>z.kind==="oauth"&&X.killswitch.get(z.id)!==!1&&f0(z.quota).limits.length===0);if($.length===0)return;if(a8({rows:X.rows,now:X.now,rateLimitMarks:X.rateLimitMarks,refreshBackoff:X.refreshBackoff,requestPull:()=>{}}).admitted.some((z)=>X.killswitch.get(z.id)!==!1))return;let G=[];if(a8({rows:$,now:X.now,rateLimitMarks:X.rateLimitMarks,refreshBackoff:X.refreshBackoff,requestPull:(z)=>{let Z=X.requestPull(z);if(Z)G.push(Z.catch(()=>{}))}}),G.length===0)return;let Q;return Promise.race([Promise.all(G),new Promise((z)=>{Q=setTimeout(z,J)})]).then(()=>{}).finally(()=>clearTimeout(Q))}function $Y(X){return X.reason==="exhausted"||X.reason==="budget-spent"}function VV(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 zV(X,J,$){if(J.refused.find((G)=>!$Y(G)&&$.get(G.id)!==!1))return{reason:"quota-unknown"};return VV(X[0],J,$)}function UV(X){let J=X.replayable!==!1,$=J?X.placement:"main-first",Y=tX({rows:X.rows,placement:$,formerMainId:E6,killswitch:X.killswitch,rateLimitMarks:X.rateLimitMarks,refreshBackoff:X.refreshBackoff,now:X.now,requestPull:X.requestPull}),G=k1(X.rows.map((Z)=>Z.id),$,E6),Q=new Set(Y.admission.refused.filter((Z)=>$Y(Z)&&X.killswitch.get(Z.id)!==!1).map((Z)=>Z.id)),z=G.filter((Z)=>Q.has(Z));if(!J){let Z=G.includes(E6),W=Z?E6: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?VV(E6,Y.admission,X.killswitch):zV(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:zV(G,Y.admission,X.killswitch)}}function YY(X){let J=a8({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 KV(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 Q5({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 jV(X,J,$,Y){let G=KV(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 NV(X,J,$){let Y=X.killswitch.get($)===!1,G=KV(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&&$Y(Q))return{kind:"last-path"};return{kind:"none"}}function qV(X,J,$,Y){let G=X.killswitch.get($);return G5({quota:J.projections.get($),now:X.now,...Y===void 0?{}:{status:Y},...G===void 0?{}:{killswitchPasses:G}})}var D1={"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.",...Q$};function zY(X){return X!==void 0&&X in Q$}function nA(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===E6)return!0;if(Q9(J,{accountId:G.identity}))return!1;return U3(K8(G.quota),J,$)})}function GY(X){let J=X.vault;return[...(J?[]:nA(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)=>U3(K8(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 sA(X){return X.flatMap((J)=>J.row?[J.row]:[])}function QX(X,J){let $=X.now(),Y=ZV(J,X.storage,$),G=J.map((W)=>({id:W.id,kind:W.kind,...G6(W.quota)?{quota:W.quota}:{}})),Q=sA(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 LV(X){let J=X.find(($)=>$.id===E6);return{main:J?K8(J.quota):void 0,fallbacks:X.filter(($)=>$.id!==E6).map(($)=>{let Y=K8($.quota);return{accountId:$.id,...Y?{quota:Y}:{}}})}}async function QY(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 DV(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=GY(X),$=X.replayable===!1&&J.some((G)=>G.id===E6)?J.filter((G)=>G.id===E6):J,Y=HV(QX(X,$));if(Y)await Y,J=GY(X);if(X.mode==="sticky-balanced"&&X.sessionId&&X.replayable&&X.body!==void 0){let G=await oA(X,J,X.sessionId,X.body);if(G)return G}return aA(X,J)}async function aA(X,J){let $=BV(X.mode),Y=UV({...QX(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,LV(J),X.vault?J.length===0?X.vault.noRouteCause():void 0:J.length===0?"no-accounts":"unusable"),servedId:E6};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=sJ(X.storage),z=[],Z=new Set,W,B=!1;for(;;){let H=eX(Y.order.filter((N)=>!Z.has(N)),z,Q),U=H===void 0?void 0:G.get(H);if(!U)break;let j;try{j=await QY(X,U)}catch(N){if(X.isAbort(N)||!W||X.mode==="fallback-first")throw N;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"},LV(J),B?"vault-refused":X.vault?"vault-empty":"unusable"),servedId:E6}}async function oA(X,J,$,Y){let G=Buffer.byteLength(Y,"utf8"),Q=new Map(J.map((O)=>[O.id,O])),z=QX(X,J),Z=YY(z),W={requestBytes:G,reservePercent:(O)=>a6(X.storage,O===E6?void 0:O),resetCredits:X.resetCredits,onEmptyWeightedSet:()=>{X.log.debug("sticky routing: no fresh weighted candidates; using configured order")}},B=(O,_)=>(C,L)=>{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)=>jV(O,W,P,A),persist:L})},H=B(z,Z),U=H([],!0);if(!U)return;let j=U.accountId,N=(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=NV(z,W,j);if(K.kind==="none")return;if(K.kind==="move"){if(!N(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 q=Q.get(j);if(!q)return;let F=await QY(X,q);if(!F)return;if(F.status===401||F.status===403||F.status===429){let O=GY(X);z=QX(X,O),Z=YY(z),H=B(z,Z);let _=qV(z,Z,j,F.status);if(_.action==="migrate"){let C=j;if(N(_.reason)&&j!==C){let L=O.find((A)=>A.id===j),P=L?await QY(X,L):void 0;if(L&&P){let A=F;F=P,A.body?.cancel().catch(()=>{}),q=L}else j=C}}}return{response:F,servedId:q.id}}function b3(X){return typeof X==="number"&&Number.isFinite(X)}function rA(X){if(!G6(X))return;let J=X.budget;if(J?.kind!=="reading")return;let{limit:$,used:Y,remaining:G,usedPercent:Q,remainingPercent:z}=J;if(!b3($)||!b3(Y)||!b3(G)||!b3(Q)||!b3(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 ZY(X,J){let $=K8(X),Y=rA(X);if(!$&&!Y)return null;let G=G6(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 FV(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:ZY(G.quota),killed:!1,enabled:J.has(G.routeId)})),route:$?.routing?.mode??"main-first",lastUpdated:Y}}function PV(X,J,$,Y=()=>{return}){let G=X.find((z)=>z.id===U8),Q=G?Y(G.id):void 0;return{main:{quota:G?ZY(G.quota,Q):null,...G?.identity!==void 0?{mainAccountId:G.identity}:{},killed:!1,...Q!==void 0?{resetCredits:Q}:{}},fallbacks:X.filter((z)=>z.id!==U8&&z.enabled).map((z)=>{let Z=Y(z.id);return{id:z.id,label:z.label,...z.identity!==void 0?{accountId:z.identity}:{},quota:ZY(z.quota,Z),killed:!1,enabled:!0,...Z!==void 0?{resetCredits:Z}:{}}}),route:J?.routing?.mode??"main-first",lastUpdated:$,accountPool:!0}}import{randomUUID as tA}from"node:crypto";import{chmod as eA,mkdir as XT,rename as JT,rm as MV,writeFile as $T}from"node:fs/promises";import{homedir as YT}from"node:os";import{join as WY}from"node:path";function _V(){let X=process.env.XDG_STATE_HOME||WY(YT(),".local","state");return WY(X,"cortexkit","openai-auth","processes")}function AV(X=process.pid,J=_V()){return WY(J,`${X}.json`)}var zX=0,OV;async function GT(X,J){await XT(X,{recursive:!0,mode:448}),await eA(X,448);let $=AV(J.pid,X),Y=`${$}.${tA()}.tmp`;try{await $T(Y,`${JSON.stringify(J)}
164
+ `,{mode:384}),await JT(Y,$)}catch(G){throw await MV(Y,{force:!0}).catch(()=>{}),G}return $}async function TV(X){let J=X.pid??process.pid,$=X.dir??_V();OV??=(X.now??Date.now)(),zX++;let Y;try{Y=await GT($,{pid:J,version:X.version,startedAt:OV})}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,zX=Math.max(0,zX-1),zX>0)return;await MV(AV(J,$),{force:!0}).catch((Q)=>{X.logger.warn("process heartbeat not removed",{dir:$,error:Q instanceof Error?Q.message:String(Q)})})}}}import{resolve as ZX}from"node:path";var QT=60000,zT=240000,RV=Symbol.for("@cortexkit/openai-auth/opencode-vaults"),CV=globalThis,k3=CV[RV]??new Map;CV[RV]=k3;function EV(X,J){let $=Boolean(X.connectScoped||X.connectEnrollment),Y=ZX(X.stateDir),G=ZX((X.connectionFile??e9)()),Q=JSON.stringify([X.host,Y,G,ZX(J.configPath),ZX(J.statePath)]),z={reservedRouteIds:X.reservedRouteIds??(()=>[])},Z=$?void 0:k3.get(Q);if(!Z){let H=new Set;if(Z={vault:new z$({...X,stateDir:Y,connectionFile:()=>G,...!$?{projectRoot:Y}:{},reservedRouteIds:()=>new Set([...H].flatMap((j)=>[...j.reservedRouteIds()]))}),holders:H,firstRoster:Promise.withResolvers(),started:!1},!$)k3.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(zT)};W.vault.start(),W.vault.firstRoster().finally(()=>{W.firstRoster.resolve(),H()}),W.quotaPoll=setInterval(H,QT),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(),!$&&k3.get(Q)===W)k3.delete(Q)}}}var xV=900000,ZT=0.016666666666666666,SV=0.000001;function HY(X,J){for(let $ of[X?.primary?.checkedAt,X?.checkedAt,J])if(typeof $==="number"&&Number.isFinite($))return $;return}function VY(X){if(X.status===401||X.status===403)return{action:"migrate",reason:"permanent"};if(!X.quota)return{action:"retain",reason:"unknown"};let J=HY(X.quota,X.quotaCheckedAt);if(J===void 0||!Number.isFinite(J)||X.now-J>xV)return{action:"retain",reason:"stale"};if(X.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let $=BY(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=kV(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 IV(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,ZT);return Y/Q}function bV(X,J){if(X<J)return-1;if(X>J)return 1;return 0}function WT(X,J){if(!X.quota)return;let $=HY(X.quota,X.quotaCheckedAt);if($===void 0||J-$>xV)return;let Y=BY(X.quota).map(({key:z,window:Z})=>{return IV(Z,X.reservePercent[z]??0,J)}),G=X.quota.spendControl;if(G&&Number.isFinite(G.remainingPercent))Y.push(IV(G,0,J));let Q=Y.length>0?Math.min(...Y):0;return Q>0?{candidate:X,quotaCheckedAt:$,weight:Q}:void 0}function wV(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)=>WT(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,SV),W=((X.pendingBytes.get(z.candidate.accountId)??0)+X.requestBytes)/Math.max(z.weight,SV);return Z-W||Q.candidate.configuredOrder-z.candidate.configuredOrder||bV(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||bV(G.accountId,Q.accountId)})[0];if(!Y)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Y.accountId,quotaCheckedAt:HY(Y.quota,Y.quotaCheckedAt),source:"mode-fallback"}}import{createHash as ET}from"node:crypto";import{createHash as BT,randomBytes as HT}from"node:crypto";import{chmod as VT,lstat as vV,mkdir as UT,open as KT,readdir as mV,readFile as yV,rename as jT,unlink as NY,writeFile as NT}from"node:fs/promises";import{join as WX,resolve as UY}from"node:path";var qT=100,KY="session-unknown",LT=300000,DT=60000,FT=600000,PT=/\.(body|meta|request|response)\.json$/,OT=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,MT=/\.[a-f0-9]{24}\.partial$/;function uV(X){let J=X.replace(PT,"");if(J===X||!OT.test(J))return;return J}function _T(X){let J=X.replace(MT,"");return J!==X&&uV(J)!==void 0}async function hV(X){let{dir:J,maxBytes:$}=X,Y=X.now??Date.now(),G=X.minAgeMs??DT,Q=X.partialStaleMs??FT,z={removed:0,freedBytes:0};if(!($>0))return z;try{if((await vV(J)).isSymbolicLink())return z;let Z=new Set((X.protectedPaths??[]).map((F)=>UY(F))),W=await mV(J,{withFileTypes:!0}),B=[];await Promise.all(W.map(async(F)=>{if(!F.isFile())return;let O=_T(F.name),_=O?void 0:uV(F.name);if(!O&&_===void 0)return;let C=WX(J,F.name);try{let L=await vV(C);if(!L.isFile())return;B.push({path:C,size:L.size,mtimeMs:L.mtimeMs,group:_})}catch{}}));let H=B.reduce((F,O)=>F+O.size,0),U=0,j=0,N=async(F)=>{try{await NY(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(UY(F.path)))continue;if(Y-F.mtimeMs<Q)continue;await N(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 q=[...K.entries()].sort(([F,O],[_,C])=>O.newest-C.newest||F.localeCompare(_));for(let[,F]of q){if(H<=$)break;if(Y-F.newest<G)continue;if(F.files.some((O)=>Z.has(UY(O.path))))continue;for(let O of F.files)await N(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 AT(X,J,$){for(let Y=0;;Y+=1){let G=`${X}.${$?$():HT(12).toString("hex")}.partial`,Q=!1,z;try{z=await KT(G,"wx",384),Q=!0,await z.writeFile(J,"utf8"),await z.chmod(384),await z.close(),z=void 0,await jT(G,X);return}catch(Z){if(await z?.close().catch(()=>{}),Q)await NY(G).catch(()=>{});if(Z.code==="EEXIST"&&Y===0)continue;throw Z}}}function jY(X){return X.length<=16?X:`${X.slice(0,12)}…`}function x3(X,J){let $=X.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!$)return J;return $.slice(0,80)}function fV(X){return BT("sha256").update(X).digest("hex")}function TT(X){return X.toLowerCase().replace(/[-_]/g,"")}function gV(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)}function RT(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 CT=0;function pV(X){let J=X.enabled===!0,$=X.pid??process.pid,Y=X.now??Date.now,G=X.logger,Q=new Set((X.secretKeys??[]).map(TT)),z=C2({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 k=z.redact({[T]:null})[T];return k===null?void 0:k}function U(T){if(Array.isArray(T))return T.map(U);if(gV(T)){let k={};for(let[p,i]of Object.entries(T)){let X0=H(p);if(Z.has(p))k[p]=z.redactStrings(i);else if(X0!==void 0)k[p]=X0;else k[p]=U(i)}return k}return z.redactStrings(T)}function j(T){let k;try{k=JSON.parse(T)}catch{return{text:z.redactStrings(T),parsed:void 0}}let p=U(k),i=JSON.stringify(p);return{text:JSON.stringify(k)===i?T:i,parsed:gV(p)?p:void 0}}async function N(T,k,p,i){let X0=`-${x3(k,KY)}-${x3(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 yV(WX(T,G0),"utf8"))?.baselineKey!==i)continue;return await yV(WX(T,G0.replace(/\.meta\.json$/,".body.json")),"utf8")}catch{}return}function K(T,k){if(!W.has(T))while(W.size>=qT){let p=W.keys().next().value;if(p===void 0)break;W.delete(p)}W.set(T,k)}async function q(T){if(!J)return;let k=++CT,p=T.session?.trim()||KY,i=B(),X0=new Date(Y()).toISOString(),w=[X0.replace(/[:.]/g,"-"),String($),String(k).padStart(6,"0"),x3(p,KY),x3(T.channel,"channel"),...T.phase?[x3(T.phase,"phase")]:[]].join("-"),J0=WX(i,w),G0={body:`${J0}.body.json`,metadata:`${J0}.meta.json`,request:`${J0}.request.json`},L0=fV(`${T.channel}\x00${p}`);try{await UT(i,{recursive:!0,mode:448}),await VT(i,448);let m=W.get(L0),c0=m===void 0?void 0:"memory";if(m===void 0){if(m=await N(i,p,T.channel,L0),m!==void 0)c0="disk"}let m0=j(T.bodyText),r={id:w,createdAt:X0,pid:$,session:jY(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:fV(T.bodyText),diff:RT(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)=>NT(e,c,{encoding:"utf8",mode:384,flag:"wx"}),t=[[G0.body,m0.text],[G0.metadata,`${JSON.stringify(r,null,2)}
165
165
  `],[G0.request,`${JSON.stringify(a,null,2)}
166
- `]],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:HY(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:HY(p),error:m instanceof Error?m.message:String(m)});return}}async function F(T,k){await Promise.all(T.map(async([p],i)=>{let X0=k[i];if(X0?.status==="rejected"&&X0.reason?.code==="EEXIST")return;await VY(p).catch(()=>{})}))}let O=X.maxBytes??0,_=X.sweepIntervalMs??BT,C=0;function L(T,k){return{dir:T,maxBytes:O,protectedPaths:k,now:Y(),minAgeMs:X.sweepMinAgeMs,partialStaleMs:X.partialStaleMs,logger:G}}function P(T,k){if(!(O>0))return;let p=Y();if(p-C<_)return;C=p,SV(L(T,k))}async function A(T,k){if(!T)return;let p=U({status:k.status,requestId:k.requestId,usage:k.usage,...k.fields,complete:k.complete??!0});try{return await NT(T.responseFile,`${JSON.stringify(p,null,2)}
167
- `,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:N,dumpResponse:A,sweep:(T)=>SV(L(B(),T))}}var yV=Z0("dump"),k9="x-cortexkit-openai-auth-dump-session",OT=["chatgpt-account-id","email","org_name","organization_name"],MT=["tools"];function UY(X){return PT("sha256").update(JSON.stringify(X)).digest("hex")}function _T(X){return X!=null&&typeof X==="object"&&"type"in X&&typeof X.type==="string"?X.type:"unknown"}function AT(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:UY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:UY(J[0]),toolsCount:$.length,toolTypes:$.map(_T),toolsHash:UY($),clientMetadataKeys:Y?Object.keys(Y).sort():[]}}function TT(){return wV({dir:()=>p6().dumpDir,logger:yV,secretKeys:OT,schemaKeys:MT,summarize:AT})}var vV=TT();async function q4(X){let J=p6().dump===!0;if(vV.setEnabled(J),!J)return;let $=typeof X.bodyText==="function"?X.bodyText():X.bodyText;await vV.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 F1(X){if(!p6().dump)return;yV.debug("diagnostic",X)}import{readFile as RT}from"node:fs/promises";import{homedir as CT}from"node:os";import{join as hV}from"node:path";var ET="https://models.dev/api.json",ST="OPENCODE_OPENAI_AUTH_MODELS_CACHE",IT="OPENCODE_MODELS_PATH",bT="OPENCODE_DISABLE_MODELS_FETCH",kT=1e4,xT=300000;function x9(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)?X:null}function fV(X){if(X===void 0)return 0;return typeof X==="number"&&Number.isFinite(X)&&X>=0?X:null}function KY(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=fV(X.cache_read),G=fV(X.cache_write);if(Y===null||G===null)return null;return{input:J,output:$,cache:{read:Y,write:G}}}function wT(X){let J=x9(X);if(!J)return null;let $=KY(J);if(!$)return null;let Y=$;if(Array.isArray(J.tiers)){let z=[];for(let Z of J.tiers){let W=x9(Z);if(!W)continue;let B=x9(W.tier),H=B?.size;if(B?.type!=="context")continue;if(typeof H!=="number"||!Number.isFinite(H)||H<=0)continue;let U=KY(W);if(!U)continue;z.push({...U,tier:{type:"context",size:H}})}if(z.length>0)Y.tiers=z}let G=x9(J.context_over_200k),Q=G?KY(G):null;if(Q)Y.experimentalOver200K=Q;return Y}function gV(X){let J=x9(X),$=x9(J?.openai),Y=x9($?.models);if(!Y)return null;let G={};for(let[Q,z]of Object.entries(Y)){let Z=x9(z),W=wT(Z?.cost);if(W)G[Q]=W}return Object.keys(G).length>0?G:null}function vT(){let X=process.env[ST]?.trim();if(X)return X;let J=process.env[IT]?.trim();if(J)return J;let $=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||hV(CT(),".cache");return hV($,"opencode","models.json")}function yT(){let X=process.env[bT]?.toLowerCase();return X==="true"||X==="1"}async function hT(){try{let X=gV(JSON.parse(await RT(vT(),"utf8")));if(X)return X}catch{}if(yT())return null;try{let X=await fetch(ET,{signal:AbortSignal.timeout(kT)});if(!X.ok)return null;return gV(await X.json())}catch{return null}}var N4;function mV(){let X=Date.now();if(N4&&N4.expiresAt>X)return N4.promise;let J={expiresAt:X+xT,promise:hT()};return N4=J,J.promise.then(($)=>{if($===null&&N4===J)N4=void 0}),J.promise}function L4(X){return typeof X==="object"&&X!==null}function fT(X){if(Array.isArray(X))return X;if(L4(X)&&Array.isArray(X.data))return X.data;return[]}function gT(X){if(!L4(X)||!L4(X.info))return;return typeof X.info.role==="string"?X.info.role:void 0}function uV(X){if(!L4(X)||!L4(X.info))return null;let J=X.info,$=L4(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 pV(X,J){return{agent:X.agent??J.agent,model:X.model??J.model,variant:X.variant??J.variant}}function cV(X){return Boolean(X.agent&&X.model&&X.variant)}async function lV(X,J){if(!X||!J)return null;let $=X;if(typeof $.session?.messages!=="function")return null;let Y=[];try{Y=fT(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(gT(Y[Q])!=="assistant")continue;let z=uV(Y[Q]);if(!z)continue;if(G=pV(G,z),cV(G))return G}for(let Q=Y.length-1;Q>=0;Q--){let z=uV(Y[Q]);if(!z)continue;if(G=pV(G,z),cV(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var mT=Z0("rpc"),iV="__openaiAuthRpcServers";function nV(X){return dV({...X,isManagedDir:s7,log:mT,drain:(J,$)=>X.drain(J,$),apply:async(J)=>await X.apply(J)})}function D4(X){return JSON.stringify(jY(X))??"undefined"}function jY(X){if(Array.isArray(X))return X.map(jY);if(!s(X))return X;return Object.fromEntries(Object.keys(X).sort().map((J)=>[J,jY(X[J])]))}var uT=512,pT=2097152;function qY(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)=>qY(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)&&qY($[Q],Y[Q]))}function P1(X,J){let $=[],Y=[],G=0;for(let Q=0;Q<X.length;Q++){let z=J?.texts[Q],Z=z!==void 0&&qY(J?.snapshots[Q],X[Q]),W=Z?z:D4(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<=uT&&G<=pT}}function k3(X){return X.retainable?X:void 0}function x3(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 O1(){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 j9={};DY(j9,{withoutInternalHeaders:()=>uN,sanitizeHttpFallbackBody:()=>d$,orderCodexBody:()=>o3,hasWebSocketResponsesLiteMetadata:()=>l$,createWebSocketFetch:()=>TI,applyTurnId:()=>vN,advanceTurn:()=>KG,TITLE_HEADER:()=>UG,QUOTA_ACCOUNT_HEADER:()=>bX,OpenAIWebSocketPool:()=>j9,CODEX_BODY_KEY_ORDER:()=>xN});import{createHash as PI}from"node:crypto";var cT=Symbol.for("vercel.ai.error"),B9=class X extends Error{constructor({name:J,message:$,cause:Y}){super($);this[cT]=!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}},sV="AI_APICallError",aV=`vercel.ai.error.${sV}`,lT=Symbol.for(aV),M1=class extends B9{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:sV,message:X,cause:z});this[lT]=!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 B9.hasMarker(X,aV)}},dT="AI_EmptyResponseBodyError",Op=`vercel.ai.error.${dT}`;var iT="AI_EvaluationUnsupportedQuestionTypeError",Mp=`vercel.ai.error.${iT}`;var oV="AI_InvalidArgumentError",rV=`vercel.ai.error.${oV}`,nT=Symbol.for(rV),NY=class extends B9{constructor({message:X,cause:J,argument:$}){super({name:oV,message:X,cause:J});this[nT]=!0,this.argument=$}static isInstance(X){return B9.hasMarker(X,rV)}},sT="AI_InvalidPromptError",_p=`vercel.ai.error.${sT}`;var aT="AI_InvalidResponseDataError",Ap=`vercel.ai.error.${aT}`;var oT="AI_JSONParseError",Tp=`vercel.ai.error.${oT}`;var rT="AI_LoadAPIKeyError",Rp=`vercel.ai.error.${rT}`;var tT="AI_LoadSettingError",Cp=`vercel.ai.error.${tT}`;var eT="AI_NoContentGeneratedError",Ep=`vercel.ai.error.${eT}`;var XR="AI_NoSuchModelError",Sp=`vercel.ai.error.${XR}`;var JR="AI_NoSuchProviderReferenceError",Ip=`vercel.ai.error.${JR}`;var $R="AI_TooManyEmbeddingValuesForCallError",bp=`vercel.ai.error.${$R}`;var YR="AI_TypeValidationError",kp=`vercel.ai.error.${YR}`;var GR="AI_UnsupportedFunctionalityError",xp=`vercel.ai.error.${GR}`;var hp=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 fp=Symbol("zod_brand");class H9 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class w3 extends Error{constructor(X){super(`Encountered unidirectional transform during encode: ${X}`);this.name="ZodEncodeError"}}var ZX={};function c8(X){if(X)Object.assign(ZX,X);return ZX}var j0={};DY(j0,{unwrapMessage:()=>v3,uint8ArrayToHex:()=>IR,uint8ArrayToBase64url:()=>ER,uint8ArrayToBase64:()=>QU,stringifyPrimitive:()=>JU,shallowClone:()=>eV,safeExtend:()=>MR,required:()=>TR,randomString:()=>qR,propertyKeyTypes:()=>OY,promiseAllObject:()=>jR,primitiveTypes:()=>XU,prefixIssues:()=>U9,pick:()=>FR,partial:()=>AR,optionalKeys:()=>MY,omit:()=>PR,objectClone:()=>VR,numKeys:()=>NR,nullish:()=>h3,normalizeParams:()=>Y0,mergeDefs:()=>v9,merge:()=>_R,jsonStringifyReplacer:()=>F4,joinValues:()=>HR,issue:()=>O4,isPlainObject:()=>y9,isObject:()=>_1,hexToUint8Array:()=>SR,getSizableOrigin:()=>YU,getParsedType:()=>LR,getLengthableOrigin:()=>g3,getEnumValues:()=>y3,getElementAtPath:()=>KR,floatSafeRemainder:()=>FY,finalizeIssue:()=>q8,extend:()=>OR,escapeRegex:()=>V9,esc:()=>WX,defineLazy:()=>N0,createTransparentProxy:()=>DR,cloneDef:()=>UR,clone:()=>j8,cleanRegex:()=>f3,cleanEnum:()=>RR,captureStackTrace:()=>BX,cached:()=>P4,base64urlToUint8Array:()=>CR,base64ToUint8Array:()=>GU,assignProp:()=>w9,assertNotEqual:()=>zR,assertNever:()=>WR,assertIs:()=>ZR,assertEqual:()=>QR,assert:()=>BR,allowsEval:()=>PY,aborted:()=>h9,NUMBER_FORMAT_RANGES:()=>_Y,Class:()=>zU,BIGINT_FORMAT_RANGES:()=>$U});function QR(X){return X}function zR(X){return X}function ZR(X){}function WR(X){throw Error()}function BR(X){}function y3(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 HR(X,J="|"){return X.map(($)=>JU($)).join(J)}function F4(X,J){if(typeof J==="bigint")return J.toString();return J}function P4(X){return{get value(){{let $=X();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function h3(X){return X===null||X===void 0}function f3(X){let J=X.startsWith("^")?1:0,$=X.endsWith("$")?X.length-1:X.length;return X.slice(J,$)}function FY(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 tV=Symbol("evaluating");function N0(X,J,$){let Y=void 0;Object.defineProperty(X,J,{get(){if(Y===tV)return;if(Y===void 0)Y=tV,Y=$();return Y},set(G){Object.defineProperty(X,J,{value:G})},configurable:!0})}function VR(X){return Object.create(Object.getPrototypeOf(X),Object.getOwnPropertyDescriptors(X))}function w9(X,J,$){Object.defineProperty(X,J,{value:$,writable:!0,enumerable:!0,configurable:!0})}function v9(...X){let J={};for(let $ of X){let Y=Object.getOwnPropertyDescriptors($);Object.assign(J,Y)}return Object.defineProperties({},J)}function UR(X){return v9(X._zod.def)}function KR(X,J){if(!J)return X;return J.reduce(($,Y)=>$?.[Y],X)}function jR(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 qR(X=10){let $="";for(let Y=0;Y<X;Y++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function WX(X){return JSON.stringify(X)}var BX="captureStackTrace"in Error?Error.captureStackTrace:(...X)=>{};function _1(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}var PY=P4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(X){return!1}});function y9(X){if(_1(X)===!1)return!1;let J=X.constructor;if(J===void 0)return!0;let $=J.prototype;if(_1($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function eV(X){if(y9(X))return{...X};if(Array.isArray(X))return[...X];return X}function NR(X){let J=0;for(let $ in X)if(Object.prototype.hasOwnProperty.call(X,$))J++;return J}var LR=(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}`)}},OY=new Set(["string","number","symbol"]),XU=new Set(["string","number","bigint","boolean","symbol","undefined"]);function V9(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j8(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 DR(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 JU(X){if(typeof X==="bigint")return X.toString()+"n";if(typeof X==="string")return`"${X}"`;return`${X}`}function MY(X){return Object.keys(X).filter((J)=>{return X[J]._zod.optin==="optional"&&X[J]._zod.optout==="optional"})}var _Y={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]},$U={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function FR(X,J){let $=X._zod.def,Y=v9(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 w9(this,"shape",G),G},checks:[]});return j8(X,Y)}function PR(X,J){let $=X._zod.def,Y=v9(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 w9(this,"shape",G),G},checks:[]});return j8(X,Y)}function OR(X,J){if(!y9(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=v9(X._zod.def,{get shape(){let Q={...X._zod.def.shape,...J};return w9(this,"shape",Q),Q},checks:[]});return j8(X,G)}function MR(X,J){if(!y9(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 w9(this,"shape",Y),Y},checks:X._zod.def.checks};return j8(X,$)}function _R(X,J){let $=v9(X._zod.def,{get shape(){let Y={...X._zod.def.shape,...J._zod.def.shape};return w9(this,"shape",Y),Y},get catchall(){return J._zod.def.catchall},checks:[]});return j8(X,$)}function AR(X,J,$){let Y=v9(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 w9(this,"shape",Q),Q},checks:[]});return j8(J,Y)}function TR(X,J,$){let Y=v9(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 w9(this,"shape",Q),Q},checks:[]});return j8(J,Y)}function h9(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 U9(X,J){return J.map(($)=>{var Y;return(Y=$).path??(Y.path=[]),$.path.unshift(X),$})}function v3(X){return typeof X==="string"?X:X?.message}function q8(X,J,$){let Y={...X,path:X.path??[]};if(!X.message){let G=v3(X.inst?._zod.def?.error?.(X))??v3(J?.error?.(X))??v3($.customError?.(X))??v3($.localeError?.(X))??"Invalid input";Y.message=G}if(delete Y.inst,delete Y.continue,!J?.reportInput)delete Y.input;return Y}function YU(X){if(X instanceof Set)return"set";if(X instanceof Map)return"map";if(X instanceof File)return"file";return"unknown"}function g3(X){if(Array.isArray(X))return"array";if(typeof X==="string")return"string";return"unknown"}function O4(...X){let[J,$,Y]=X;if(typeof J==="string")return{message:J,code:"custom",input:$,inst:Y};return{...J}}function RR(X){return Object.entries(X).filter(([J,$])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function GU(X){let J=atob(X),$=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)$[Y]=J.charCodeAt(Y);return $}function QU(X){let J="";for(let $=0;$<X.length;$++)J+=String.fromCharCode(X[$]);return btoa(J)}function CR(X){let J=X.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-J.length%4)%4);return GU(J+$)}function ER(X){return QU(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function SR(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 IR(X){return Array.from(X).map((J)=>J.toString(16).padStart(2,"0")).join("")}class zU{constructor(...X){}}var ZU=(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,F4,2),Object.defineProperty(X,"toString",{value:()=>X.message,enumerable:!1})},HX=E("$ZodError",ZU),AY=E("$ZodError",ZU,{Parent:Error});function WU(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 BU(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 VX=(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 H9;if(z.issues.length){let Z=new(G?.Err??X)(z.issues.map((W)=>q8(W,Q,c8())));throw BX(Z,G?.callee),Z}return z.value};var UX=(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)=>q8(W,Q,c8())));throw BX(Z,G?.callee),Z}return z.value};var m3=(X)=>(J,$,Y)=>{let G=Y?{...Y,async:!1}:{async:!1},Q=J._zod.run({value:$,issues:[]},G);if(Q instanceof Promise)throw new H9;return Q.issues.length?{success:!1,error:new(X??HX)(Q.issues.map((z)=>q8(z,G,c8())))}:{success:!0,data:Q.value}},HU=m3(AY),u3=(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)=>q8(z,G,c8())))}:{success:!0,data:Q.value}},VU=u3(AY),UU=(X)=>(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return VX(X)(J,$,G)};var KU=(X)=>(J,$,Y)=>{return VX(X)(J,$,Y)};var jU=(X)=>async(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return UX(X)(J,$,G)};var qU=(X)=>async(J,$,Y)=>{return UX(X)(J,$,Y)};var NU=(X)=>(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return m3(X)(J,$,G)};var LU=(X)=>(J,$,Y)=>{return m3(X)(J,$,Y)};var DU=(X)=>async(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return u3(X)(J,$,G)};var FU=(X)=>async(J,$,Y)=>{return u3(X)(J,$,Y)};var PU=/^[cC][^\s-]{8,}$/,OU=/^[0-9a-z]+$/,MU=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_U=/^[0-9a-vA-V]{20}$/,AU=/^[A-Za-z0-9]{27}$/,TU=/^[a-zA-Z0-9_-]{21}$/,RU=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var CU=/^([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})$/,TY=(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 EU=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function SU(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var IU=/^(?:(?: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])$/,bU=/^(([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}|:))$/,kU=/^((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])$/,xU=/^(([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])$/,wU=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,RY=/^[A-Za-z0-9_-]*$/,vU=/^(?=.{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 yU=/^\+(?:[0-9]){6,14}[0-9]$/,hU="(?:(?:\\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])))",fU=new RegExp(`^${hU}$`);function gU(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 mU(X){return new RegExp(`^${gU(X)}$`)}function uU(X){let J=gU({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(`^${hU}T(?:${Y})$`)}var pU=(X)=>{let J=X?`[\\s\\S]{${X?.minimum??0},${X?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var cU=/^-?\d+$/,lU=/^-?\d+(?:\.\d+)?/,dU=/^(?:true|false)$/i,iU=/^null$/i;var nU=/^[^A-Z]*$/,sU=/^[^a-z]*$/;var Z6=E("$ZodCheck",(X,J)=>{var $;X._zod??(X._zod={}),X._zod.def=J,($=X._zod).onattach??($.onattach=[])}),aU={number:"number",bigint:"bigint",object:"date"},CY=E("$ZodCheckLessThan",(X,J)=>{Z6.init(X,J);let $=aU[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})}}),EY=E("$ZodCheckGreaterThan",(X,J)=>{Z6.init(X,J);let $=aU[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})}}),oU=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):FY($.value,J.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:J.value,input:$.value,inst:X,continue:!J.abort})}}),rU=E("$ZodCheckNumberFormat",(X,J)=>{Z6.init(X,J),J.format=J.format||"float64";let $=J.format?.includes("int"),Y=$?"int":"number",[G,Q]=_Y[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=cU}),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 tU=E("$ZodCheckMaxLength",(X,J)=>{var $;Z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!h3(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=g3(G);Y.issues.push({origin:z,code:"too_big",maximum:J.maximum,inclusive:!0,input:G,inst:X,continue:!J.abort})}}),eU=E("$ZodCheckMinLength",(X,J)=>{var $;Z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!h3(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=g3(G);Y.issues.push({origin:z,code:"too_small",minimum:J.minimum,inclusive:!0,input:G,inst:X,continue:!J.abort})}}),XK=E("$ZodCheckLengthEquals",(X,J)=>{var $;Z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!h3(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=g3(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})}}),p3=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=()=>{})}),JK=E("$ZodCheckRegex",(X,J)=>{p3.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})}}),$K=E("$ZodCheckLowerCase",(X,J)=>{J.pattern??(J.pattern=nU),p3.init(X,J)}),YK=E("$ZodCheckUpperCase",(X,J)=>{J.pattern??(J.pattern=sU),p3.init(X,J)}),GK=E("$ZodCheckIncludes",(X,J)=>{Z6.init(X,J);let $=V9(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})}}),QK=E("$ZodCheckStartsWith",(X,J)=>{Z6.init(X,J);let $=new RegExp(`^${V9(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})}}),zK=E("$ZodCheckEndsWith",(X,J)=>{Z6.init(X,J);let $=new RegExp(`.*${V9(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 ZK=E("$ZodCheckOverwrite",(X,J)=>{Z6.init(X,J),X._zod.check=($)=>{$.value=J.tx($.value)}});class SY{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(`
166
+ `]],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:jY(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:jY(p),error:m instanceof Error?m.message:String(m)});return}}async function F(T,k){await Promise.all(T.map(async([p],i)=>{let X0=k[i];if(X0?.status==="rejected"&&X0.reason?.code==="EEXIST")return;await NY(p).catch(()=>{})}))}let O=X.maxBytes??0,_=X.sweepIntervalMs??LT,C=0;function L(T,k){return{dir:T,maxBytes:O,protectedPaths:k,now:Y(),minAgeMs:X.sweepMinAgeMs,partialStaleMs:X.partialStaleMs,logger:G}}function P(T,k){if(!(O>0))return;let p=Y();if(p-C<_)return;C=p,hV(L(T,k))}async function A(T,k){if(!T)return;let p=U({status:k.status,requestId:k.requestId,usage:k.usage,...k.fields,complete:k.complete??!0});try{return await AT(T.responseFile,`${JSON.stringify(p,null,2)}
167
+ `,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:q,dumpResponse:A,sweep:(T)=>hV(L(B(),T))}}var lV=Z0("dump"),x9="x-cortexkit-openai-auth-dump-session",ST=["chatgpt-account-id","email","org_name","organization_name"],IT=["tools"];function qY(X){return ET("sha256").update(JSON.stringify(X)).digest("hex")}function bT(X){return X!=null&&typeof X==="object"&&"type"in X&&typeof X.type==="string"?X.type:"unknown"}function kT(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:qY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:qY(J[0]),toolsCount:$.length,toolTypes:$.map(bT),toolsHash:qY($),clientMetadataKeys:Y?Object.keys(Y).sort():[]}}function xT(){return pV({dir:()=>c6().dumpDir,logger:lV,secretKeys:ST,schemaKeys:IT,summarize:kT})}var cV=xT();async function q4(X){let J=c6().dump===!0;if(cV.setEnabled(J),!J)return;let $=typeof X.bodyText==="function"?X.bodyText():X.bodyText;await cV.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 F1(X){if(!c6().dump)return;lV.debug("diagnostic",X)}import{readFile as wT}from"node:fs/promises";import{homedir as vT}from"node:os";import{join as dV}from"node:path";var yT="https://models.dev/api.json",hT="OPENCODE_OPENAI_AUTH_MODELS_CACHE",fT="OPENCODE_MODELS_PATH",gT="OPENCODE_DISABLE_MODELS_FETCH",mT=1e4,uT=300000;function w9(X){return X!==null&&typeof X==="object"&&!Array.isArray(X)?X:null}function iV(X){if(X===void 0)return 0;return typeof X==="number"&&Number.isFinite(X)&&X>=0?X:null}function LY(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=iV(X.cache_read),G=iV(X.cache_write);if(Y===null||G===null)return null;return{input:J,output:$,cache:{read:Y,write:G}}}function pT(X){let J=w9(X);if(!J)return null;let $=LY(J);if(!$)return null;let Y=$;if(Array.isArray(J.tiers)){let z=[];for(let Z of J.tiers){let W=w9(Z);if(!W)continue;let B=w9(W.tier),H=B?.size;if(B?.type!=="context")continue;if(typeof H!=="number"||!Number.isFinite(H)||H<=0)continue;let U=LY(W);if(!U)continue;z.push({...U,tier:{type:"context",size:H}})}if(z.length>0)Y.tiers=z}let G=w9(J.context_over_200k),Q=G?LY(G):null;if(Q)Y.experimentalOver200K=Q;return Y}function nV(X){let J=w9(X),$=w9(J?.openai),Y=w9($?.models);if(!Y)return null;let G={};for(let[Q,z]of Object.entries(Y)){let Z=w9(z),W=pT(Z?.cost);if(W)G[Q]=W}return Object.keys(G).length>0?G:null}function cT(){let X=process.env[hT]?.trim();if(X)return X;let J=process.env[fT]?.trim();if(J)return J;let $=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||dV(vT(),".cache");return dV($,"opencode","models.json")}function lT(){let X=process.env[gT]?.toLowerCase();return X==="true"||X==="1"}async function dT(){try{let X=nV(JSON.parse(await wT(cT(),"utf8")));if(X)return X}catch{}if(lT())return null;try{let X=await fetch(yT,{signal:AbortSignal.timeout(mT)});if(!X.ok)return null;return nV(await X.json())}catch{return null}}var L4;function sV(){let X=Date.now();if(L4&&L4.expiresAt>X)return L4.promise;let J={expiresAt:X+uT,promise:dT()};return L4=J,J.promise.then(($)=>{if($===null&&L4===J)L4=void 0}),J.promise}function D4(X){return typeof X==="object"&&X!==null}function iT(X){if(Array.isArray(X))return X;if(D4(X)&&Array.isArray(X.data))return X.data;return[]}function nT(X){if(!D4(X)||!D4(X.info))return;return typeof X.info.role==="string"?X.info.role:void 0}function aV(X){if(!D4(X)||!D4(X.info))return null;let J=X.info,$=D4(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 oV(X,J){return{agent:X.agent??J.agent,model:X.model??J.model,variant:X.variant??J.variant}}function rV(X){return Boolean(X.agent&&X.model&&X.variant)}async function tV(X,J){if(!X||!J)return null;let $=X;if(typeof $.session?.messages!=="function")return null;let Y=[];try{Y=iT(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(nT(Y[Q])!=="assistant")continue;let z=aV(Y[Q]);if(!z)continue;if(G=oV(G,z),rV(G))return G}for(let Q=Y.length-1;Q>=0;Q--){let z=aV(Y[Q]);if(!z)continue;if(G=oV(G,z),rV(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}var sT=Z0("rpc"),XU="__openaiAuthRpcServers";function JU(X){return eV({...X,isManagedDir:o7,log:sT,drain:(J,$)=>X.drain(J,$),apply:async(J)=>await X.apply(J)})}function F4(X){return JSON.stringify(DY(X))??"undefined"}function DY(X){if(Array.isArray(X))return X.map(DY);if(!s(X))return X;return Object.fromEntries(Object.keys(X).sort().map((J)=>[J,DY(X[J])]))}var aT=512,oT=2097152;function FY(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)=>FY(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)&&FY($[Q],Y[Q]))}function P1(X,J){let $=[],Y=[],G=0;for(let Q=0;Q<X.length;Q++){let z=J?.texts[Q],Z=z!==void 0&&FY(J?.snapshots[Q],X[Q]),W=Z?z:F4(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<=aT&&G<=oT}}function w3(X){return X.retainable?X:void 0}function v3(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 O1(){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 N9={};MY(N9,{withoutInternalHeaders:()=>aq,sanitizeHttpFallbackBody:()=>a$,orderCodexBody:()=>t3,hasWebSocketResponsesLiteMetadata:()=>s$,createWebSocketFetch:()=>xI,applyTurnId:()=>cq,advanceTurn:()=>LG,TITLE_HEADER:()=>qG,QUOTA_ACCOUNT_HEADER:()=>xX,OpenAIWebSocketPool:()=>N9,CODEX_BODY_KEY_ORDER:()=>uq});import{createHash as EI}from"node:crypto";var rT=Symbol.for("vercel.ai.error"),H9=class X extends Error{constructor({name:J,message:$,cause:Y}){super($);this[rT]=!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}},$U="AI_APICallError",YU=`vercel.ai.error.${$U}`,tT=Symbol.for(YU),M1=class extends H9{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:$U,message:X,cause:z});this[tT]=!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 H9.hasMarker(X,YU)}},eT="AI_EmptyResponseBodyError",fp=`vercel.ai.error.${eT}`;var XR="AI_EvaluationUnsupportedQuestionTypeError",gp=`vercel.ai.error.${XR}`;var GU="AI_InvalidArgumentError",QU=`vercel.ai.error.${GU}`,JR=Symbol.for(QU),PY=class extends H9{constructor({message:X,cause:J,argument:$}){super({name:GU,message:X,cause:J});this[JR]=!0,this.argument=$}static isInstance(X){return H9.hasMarker(X,QU)}},$R="AI_InvalidPromptError",mp=`vercel.ai.error.${$R}`;var YR="AI_InvalidResponseDataError",up=`vercel.ai.error.${YR}`;var GR="AI_JSONParseError",pp=`vercel.ai.error.${GR}`;var QR="AI_LoadAPIKeyError",cp=`vercel.ai.error.${QR}`;var zR="AI_LoadSettingError",lp=`vercel.ai.error.${zR}`;var ZR="AI_NoContentGeneratedError",dp=`vercel.ai.error.${ZR}`;var WR="AI_NoSuchModelError",ip=`vercel.ai.error.${WR}`;var BR="AI_NoSuchProviderReferenceError",np=`vercel.ai.error.${BR}`;var HR="AI_TooManyEmbeddingValuesForCallError",sp=`vercel.ai.error.${HR}`;var VR="AI_TypeValidationError",ap=`vercel.ai.error.${VR}`;var UR="AI_UnsupportedFunctionalityError",op=`vercel.ai.error.${UR}`;var Xc=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 Jc=Symbol("zod_brand");class V9 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class y3 extends Error{constructor(X){super(`Encountered unidirectional transform during encode: ${X}`);this.name="ZodEncodeError"}}var BX={};function c8(X){if(X)Object.assign(BX,X);return BX}var j0={};MY(j0,{unwrapMessage:()=>h3,uint8ArrayToHex:()=>fR,uint8ArrayToBase64url:()=>yR,uint8ArrayToBase64:()=>KU,stringifyPrimitive:()=>BU,shallowClone:()=>ZU,safeExtend:()=>IR,required:()=>xR,randomString:()=>_R,propertyKeyTypes:()=>TY,promiseAllObject:()=>MR,primitiveTypes:()=>WU,prefixIssues:()=>K9,pick:()=>CR,partial:()=>kR,optionalKeys:()=>RY,omit:()=>ER,objectClone:()=>FR,numKeys:()=>AR,nullish:()=>g3,normalizeParams:()=>Y0,mergeDefs:()=>y9,merge:()=>bR,jsonStringifyReplacer:()=>P4,joinValues:()=>DR,issue:()=>M4,isPlainObject:()=>h9,isObject:()=>_1,hexToUint8Array:()=>hR,getSizableOrigin:()=>VU,getParsedType:()=>TR,getLengthableOrigin:()=>u3,getEnumValues:()=>f3,getElementAtPath:()=>OR,floatSafeRemainder:()=>_Y,finalizeIssue:()=>q8,extend:()=>SR,escapeRegex:()=>U9,esc:()=>HX,defineLazy:()=>q0,createTransparentProxy:()=>RR,cloneDef:()=>PR,clone:()=>N8,cleanRegex:()=>m3,cleanEnum:()=>wR,captureStackTrace:()=>VX,cached:()=>O4,base64urlToUint8Array:()=>vR,base64ToUint8Array:()=>UU,assignProp:()=>v9,assertNotEqual:()=>jR,assertNever:()=>qR,assertIs:()=>NR,assertEqual:()=>KR,assert:()=>LR,allowsEval:()=>AY,aborted:()=>f9,NUMBER_FORMAT_RANGES:()=>CY,Class:()=>jU,BIGINT_FORMAT_RANGES:()=>HU});function KR(X){return X}function jR(X){return X}function NR(X){}function qR(X){throw Error()}function LR(X){}function f3(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 DR(X,J="|"){return X.map(($)=>BU($)).join(J)}function P4(X,J){if(typeof J==="bigint")return J.toString();return J}function O4(X){return{get value(){{let $=X();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function g3(X){return X===null||X===void 0}function m3(X){let J=X.startsWith("^")?1:0,$=X.endsWith("$")?X.length-1:X.length;return X.slice(J,$)}function _Y(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 zU=Symbol("evaluating");function q0(X,J,$){let Y=void 0;Object.defineProperty(X,J,{get(){if(Y===zU)return;if(Y===void 0)Y=zU,Y=$();return Y},set(G){Object.defineProperty(X,J,{value:G})},configurable:!0})}function FR(X){return Object.create(Object.getPrototypeOf(X),Object.getOwnPropertyDescriptors(X))}function v9(X,J,$){Object.defineProperty(X,J,{value:$,writable:!0,enumerable:!0,configurable:!0})}function y9(...X){let J={};for(let $ of X){let Y=Object.getOwnPropertyDescriptors($);Object.assign(J,Y)}return Object.defineProperties({},J)}function PR(X){return y9(X._zod.def)}function OR(X,J){if(!J)return X;return J.reduce(($,Y)=>$?.[Y],X)}function MR(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 _R(X=10){let $="";for(let Y=0;Y<X;Y++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function HX(X){return JSON.stringify(X)}var VX="captureStackTrace"in Error?Error.captureStackTrace:(...X)=>{};function _1(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}var AY=O4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(X){return!1}});function h9(X){if(_1(X)===!1)return!1;let J=X.constructor;if(J===void 0)return!0;let $=J.prototype;if(_1($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function ZU(X){if(h9(X))return{...X};if(Array.isArray(X))return[...X];return X}function AR(X){let J=0;for(let $ in X)if(Object.prototype.hasOwnProperty.call(X,$))J++;return J}var TR=(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}`)}},TY=new Set(["string","number","symbol"]),WU=new Set(["string","number","bigint","boolean","symbol","undefined"]);function U9(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N8(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 RR(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 BU(X){if(typeof X==="bigint")return X.toString()+"n";if(typeof X==="string")return`"${X}"`;return`${X}`}function RY(X){return Object.keys(X).filter((J)=>{return X[J]._zod.optin==="optional"&&X[J]._zod.optout==="optional"})}var CY={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]},HU={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function CR(X,J){let $=X._zod.def,Y=y9(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 v9(this,"shape",G),G},checks:[]});return N8(X,Y)}function ER(X,J){let $=X._zod.def,Y=y9(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 v9(this,"shape",G),G},checks:[]});return N8(X,Y)}function SR(X,J){if(!h9(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=y9(X._zod.def,{get shape(){let Q={...X._zod.def.shape,...J};return v9(this,"shape",Q),Q},checks:[]});return N8(X,G)}function IR(X,J){if(!h9(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 v9(this,"shape",Y),Y},checks:X._zod.def.checks};return N8(X,$)}function bR(X,J){let $=y9(X._zod.def,{get shape(){let Y={...X._zod.def.shape,...J._zod.def.shape};return v9(this,"shape",Y),Y},get catchall(){return J._zod.def.catchall},checks:[]});return N8(X,$)}function kR(X,J,$){let Y=y9(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 v9(this,"shape",Q),Q},checks:[]});return N8(J,Y)}function xR(X,J,$){let Y=y9(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 v9(this,"shape",Q),Q},checks:[]});return N8(J,Y)}function f9(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 K9(X,J){return J.map(($)=>{var Y;return(Y=$).path??(Y.path=[]),$.path.unshift(X),$})}function h3(X){return typeof X==="string"?X:X?.message}function q8(X,J,$){let Y={...X,path:X.path??[]};if(!X.message){let G=h3(X.inst?._zod.def?.error?.(X))??h3(J?.error?.(X))??h3($.customError?.(X))??h3($.localeError?.(X))??"Invalid input";Y.message=G}if(delete Y.inst,delete Y.continue,!J?.reportInput)delete Y.input;return Y}function VU(X){if(X instanceof Set)return"set";if(X instanceof Map)return"map";if(X instanceof File)return"file";return"unknown"}function u3(X){if(Array.isArray(X))return"array";if(typeof X==="string")return"string";return"unknown"}function M4(...X){let[J,$,Y]=X;if(typeof J==="string")return{message:J,code:"custom",input:$,inst:Y};return{...J}}function wR(X){return Object.entries(X).filter(([J,$])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function UU(X){let J=atob(X),$=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)$[Y]=J.charCodeAt(Y);return $}function KU(X){let J="";for(let $=0;$<X.length;$++)J+=String.fromCharCode(X[$]);return btoa(J)}function vR(X){let J=X.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-J.length%4)%4);return UU(J+$)}function yR(X){return KU(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hR(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 fR(X){return Array.from(X).map((J)=>J.toString(16).padStart(2,"0")).join("")}class jU{constructor(...X){}}var NU=(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,P4,2),Object.defineProperty(X,"toString",{value:()=>X.message,enumerable:!1})},UX=E("$ZodError",NU),EY=E("$ZodError",NU,{Parent:Error});function qU(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 LU(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 KX=(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 V9;if(z.issues.length){let Z=new(G?.Err??X)(z.issues.map((W)=>q8(W,Q,c8())));throw VX(Z,G?.callee),Z}return z.value};var jX=(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)=>q8(W,Q,c8())));throw VX(Z,G?.callee),Z}return z.value};var p3=(X)=>(J,$,Y)=>{let G=Y?{...Y,async:!1}:{async:!1},Q=J._zod.run({value:$,issues:[]},G);if(Q instanceof Promise)throw new V9;return Q.issues.length?{success:!1,error:new(X??UX)(Q.issues.map((z)=>q8(z,G,c8())))}:{success:!0,data:Q.value}},DU=p3(EY),c3=(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)=>q8(z,G,c8())))}:{success:!0,data:Q.value}},FU=c3(EY),PU=(X)=>(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return KX(X)(J,$,G)};var OU=(X)=>(J,$,Y)=>{return KX(X)(J,$,Y)};var MU=(X)=>async(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return jX(X)(J,$,G)};var _U=(X)=>async(J,$,Y)=>{return jX(X)(J,$,Y)};var AU=(X)=>(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return p3(X)(J,$,G)};var TU=(X)=>(J,$,Y)=>{return p3(X)(J,$,Y)};var RU=(X)=>async(J,$,Y)=>{let G=Y?Object.assign(Y,{direction:"backward"}):{direction:"backward"};return c3(X)(J,$,G)};var CU=(X)=>async(J,$,Y)=>{return c3(X)(J,$,Y)};var EU=/^[cC][^\s-]{8,}$/,SU=/^[0-9a-z]+$/,IU=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bU=/^[0-9a-vA-V]{20}$/,kU=/^[A-Za-z0-9]{27}$/,xU=/^[a-zA-Z0-9_-]{21}$/,wU=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var vU=/^([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})$/,SY=(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 yU=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function hU(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var fU=/^(?:(?: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])$/,gU=/^(([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])$/,uU=/^(([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])$/,pU=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,IY=/^[A-Za-z0-9_-]*$/,cU=/^(?=.{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 lU=/^\+(?:[0-9]){6,14}[0-9]$/,dU="(?:(?:\\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])))",iU=new RegExp(`^${dU}$`);function nU(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 sU(X){return new RegExp(`^${nU(X)}$`)}function aU(X){let J=nU({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(`^${dU}T(?:${Y})$`)}var oU=(X)=>{let J=X?`[\\s\\S]{${X?.minimum??0},${X?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var rU=/^-?\d+$/,tU=/^-?\d+(?:\.\d+)?/,eU=/^(?:true|false)$/i,XK=/^null$/i;var JK=/^[^A-Z]*$/,$K=/^[^a-z]*$/;var Z6=E("$ZodCheck",(X,J)=>{var $;X._zod??(X._zod={}),X._zod.def=J,($=X._zod).onattach??($.onattach=[])}),YK={number:"number",bigint:"bigint",object:"date"},bY=E("$ZodCheckLessThan",(X,J)=>{Z6.init(X,J);let $=YK[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})}}),kY=E("$ZodCheckGreaterThan",(X,J)=>{Z6.init(X,J);let $=YK[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})}}),GK=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):_Y($.value,J.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:J.value,input:$.value,inst:X,continue:!J.abort})}}),QK=E("$ZodCheckNumberFormat",(X,J)=>{Z6.init(X,J),J.format=J.format||"float64";let $=J.format?.includes("int"),Y=$?"int":"number",[G,Q]=CY[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=rU}),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 zK=E("$ZodCheckMaxLength",(X,J)=>{var $;Z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!g3(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=u3(G);Y.issues.push({origin:z,code:"too_big",maximum:J.maximum,inclusive:!0,input:G,inst:X,continue:!J.abort})}}),ZK=E("$ZodCheckMinLength",(X,J)=>{var $;Z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!g3(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=u3(G);Y.issues.push({origin:z,code:"too_small",minimum:J.minimum,inclusive:!0,input:G,inst:X,continue:!J.abort})}}),WK=E("$ZodCheckLengthEquals",(X,J)=>{var $;Z6.init(X,J),($=X._zod.def).when??($.when=(Y)=>{let G=Y.value;return!g3(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=u3(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})}}),l3=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=()=>{})}),BK=E("$ZodCheckRegex",(X,J)=>{l3.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})}}),HK=E("$ZodCheckLowerCase",(X,J)=>{J.pattern??(J.pattern=JK),l3.init(X,J)}),VK=E("$ZodCheckUpperCase",(X,J)=>{J.pattern??(J.pattern=$K),l3.init(X,J)}),UK=E("$ZodCheckIncludes",(X,J)=>{Z6.init(X,J);let $=U9(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})}}),KK=E("$ZodCheckStartsWith",(X,J)=>{Z6.init(X,J);let $=new RegExp(`^${U9(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})}}),jK=E("$ZodCheckEndsWith",(X,J)=>{Z6.init(X,J);let $=new RegExp(`.*${U9(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 NK=E("$ZodCheckOverwrite",(X,J)=>{Z6.init(X,J),X._zod.check=($)=>{$.value=J.tx($.value)}});class xY{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(`
168
168
  `).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(`
169
- `))}}var BK={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=BK;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=h9(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 H9;if(H||q instanceof Promise)H=(H??Promise.resolve()).then(async()=>{if(await q,z.issues.length===j)return;if(!B)B=h9(z,j)});else{if(z.issues.length===j)continue;if(!B)B=h9(z,j)}}if(H)return H.then(()=>{return z});return z},Q=(z,Z,W)=>{if(h9(z))return z.aborted=!0,z;let B=G(Z,Y,W);if(B instanceof Promise){if(W.async===!1)throw new H9;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 H9;return W.then((B)=>G(B,Y,Z))}return G(W,Y,Z)}}X["~standard"]={validate:(G)=>{try{let Q=HU(X,G);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return VU(X,G).then((z)=>z.success?{value:z.data}:{issues:z.error?.issues})}},vendor:"zod",version:1}}),NX=E("$ZodString",(X,J)=>{S0.init(X,J),X._zod.pattern=[...X?._zod.bag?.patterns??[]].pop()??pU(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)=>{p3.init(X,J),NX.init(X,J)}),DK=E("$ZodGUID",(X,J)=>{J.pattern??(J.pattern=CU),k0.init(X,J)}),FK=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=TY(Y))}else J.pattern??(J.pattern=TY());k0.init(X,J)}),PK=E("$ZodEmail",(X,J)=>{J.pattern??(J.pattern=EU),k0.init(X,J)}),OK=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:vU.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})}}}),MK=E("$ZodEmoji",(X,J)=>{J.pattern??(J.pattern=SU()),k0.init(X,J)}),_K=E("$ZodNanoID",(X,J)=>{J.pattern??(J.pattern=TU),k0.init(X,J)}),AK=E("$ZodCUID",(X,J)=>{J.pattern??(J.pattern=PU),k0.init(X,J)}),TK=E("$ZodCUID2",(X,J)=>{J.pattern??(J.pattern=OU),k0.init(X,J)}),RK=E("$ZodULID",(X,J)=>{J.pattern??(J.pattern=MU),k0.init(X,J)}),CK=E("$ZodXID",(X,J)=>{J.pattern??(J.pattern=_U),k0.init(X,J)}),EK=E("$ZodKSUID",(X,J)=>{J.pattern??(J.pattern=AU),k0.init(X,J)}),SK=E("$ZodISODateTime",(X,J)=>{J.pattern??(J.pattern=uU(J)),k0.init(X,J)}),IK=E("$ZodISODate",(X,J)=>{J.pattern??(J.pattern=fU),k0.init(X,J)}),bK=E("$ZodISOTime",(X,J)=>{J.pattern??(J.pattern=mU(J)),k0.init(X,J)}),kK=E("$ZodISODuration",(X,J)=>{J.pattern??(J.pattern=RU),k0.init(X,J)}),xK=E("$ZodIPv4",(X,J)=>{J.pattern??(J.pattern=IU),k0.init(X,J),X._zod.onattach.push(($)=>{let Y=$._zod.bag;Y.format="ipv4"})}),wK=E("$ZodIPv6",(X,J)=>{J.pattern??(J.pattern=bU),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})}}}),vK=E("$ZodCIDRv4",(X,J)=>{J.pattern??(J.pattern=kU),k0.init(X,J)}),yK=E("$ZodCIDRv6",(X,J)=>{J.pattern??(J.pattern=xU),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 hK(X){if(X==="")return!0;if(X.length%4!==0)return!1;try{return atob(X),!0}catch{return!1}}var fK=E("$ZodBase64",(X,J)=>{J.pattern??(J.pattern=wU),k0.init(X,J),X._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),X._zod.check=($)=>{if(hK($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:X,continue:!J.abort})}});function kR(X){if(!RY.test(X))return!1;let J=X.replace(/[-_]/g,(Y)=>Y==="-"?"+":"/"),$=J.padEnd(Math.ceil(J.length/4)*4,"=");return hK($)}var gK=E("$ZodBase64URL",(X,J)=>{J.pattern??(J.pattern=RY),k0.init(X,J),X._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),X._zod.check=($)=>{if(kR($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:X,continue:!J.abort})}}),mK=E("$ZodE164",(X,J)=>{J.pattern??(J.pattern=yU),k0.init(X,J)});function xR(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 uK=E("$ZodJWT",(X,J)=>{k0.init(X,J),X._zod.check=($)=>{if(xR($.value,J.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:X,continue:!J.abort})}});var bY=E("$ZodNumber",(X,J)=>{S0.init(X,J),X._zod.pattern=X._zod.bag.pattern??lU,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}:{}}),$}}),pK=E("$ZodNumber",(X,J)=>{rU.init(X,J),bY.init(X,J)}),cK=E("$ZodBoolean",(X,J)=>{S0.init(X,J),X._zod.pattern=dU,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 lK=E("$ZodNull",(X,J)=>{S0.init(X,J),X._zod.pattern=iU,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 dK=E("$ZodUnknown",(X,J)=>{S0.init(X,J),X._zod.parse=($)=>$}),iK=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 HK(X,J,$){if(X.issues.length)J.issues.push(...U9($,X.issues));J.value[$]=X.value}var nK=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)=>HK(B,$,z)));else HK(W,$,z)}if(Q.length)return Promise.all(Q).then(()=>$);return $}});function qX(X,J,$,Y){if(X.issues.length)J.issues.push(...U9($,X.issues));if(X.value===void 0){if($ in Y)J.value[$]=void 0}else J.value[$]=X.value}function sK(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 $=MY(X.shape);return{...X,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set($)}}function aK(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)=>qX(j,$,H,J)));else qX(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 $=P4(()=>sK(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=_1,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)=>qX(K,z,U,W)));else qX(q,z,U,W)}if(!G)return B.length?Promise.all(B).then(()=>z):z;return aK(B,W,z,Z,$.value,X)}}),oK=E("$ZodObjectJIT",(X,J)=>{wR.init(X,J);let $=X._zod.parse,Y=P4(()=>sK(J)),G=(j)=>{let q=new SY(["shape","payload","ctx"]),K=Y.value,N=(C)=>{let L=WX(C);return`shape[${L}]._zod.run({ value: input[${L}], 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 L=F[C],P=WX(C);q.write(`const ${L} = ${N(C)};`),q.write(`
169
+ `))}}var LK={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=LK;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=f9(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,N=U._zod.check(z);if(N instanceof Promise&&W?.async===!1)throw new V9;if(H||N instanceof Promise)H=(H??Promise.resolve()).then(async()=>{if(await N,z.issues.length===j)return;if(!B)B=f9(z,j)});else{if(z.issues.length===j)continue;if(!B)B=f9(z,j)}}if(H)return H.then(()=>{return z});return z},Q=(z,Z,W)=>{if(f9(z))return z.aborted=!0,z;let B=G(Z,Y,W);if(B instanceof Promise){if(W.async===!1)throw new V9;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 V9;return W.then((B)=>G(B,Y,Z))}return G(W,Y,Z)}}X["~standard"]={validate:(G)=>{try{let Q=DU(X,G);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return FU(X,G).then((z)=>z.success?{value:z.data}:{issues:z.error?.issues})}},vendor:"zod",version:1}}),DX=E("$ZodString",(X,J)=>{S0.init(X,J),X._zod.pattern=[...X?._zod.bag?.patterns??[]].pop()??oU(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)=>{l3.init(X,J),DX.init(X,J)}),RK=E("$ZodGUID",(X,J)=>{J.pattern??(J.pattern=vU),k0.init(X,J)}),CK=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=SY(Y))}else J.pattern??(J.pattern=SY());k0.init(X,J)}),EK=E("$ZodEmail",(X,J)=>{J.pattern??(J.pattern=yU),k0.init(X,J)}),SK=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:cU.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})}}}),IK=E("$ZodEmoji",(X,J)=>{J.pattern??(J.pattern=hU()),k0.init(X,J)}),bK=E("$ZodNanoID",(X,J)=>{J.pattern??(J.pattern=xU),k0.init(X,J)}),kK=E("$ZodCUID",(X,J)=>{J.pattern??(J.pattern=EU),k0.init(X,J)}),xK=E("$ZodCUID2",(X,J)=>{J.pattern??(J.pattern=SU),k0.init(X,J)}),wK=E("$ZodULID",(X,J)=>{J.pattern??(J.pattern=IU),k0.init(X,J)}),vK=E("$ZodXID",(X,J)=>{J.pattern??(J.pattern=bU),k0.init(X,J)}),yK=E("$ZodKSUID",(X,J)=>{J.pattern??(J.pattern=kU),k0.init(X,J)}),hK=E("$ZodISODateTime",(X,J)=>{J.pattern??(J.pattern=aU(J)),k0.init(X,J)}),fK=E("$ZodISODate",(X,J)=>{J.pattern??(J.pattern=iU),k0.init(X,J)}),gK=E("$ZodISOTime",(X,J)=>{J.pattern??(J.pattern=sU(J)),k0.init(X,J)}),mK=E("$ZodISODuration",(X,J)=>{J.pattern??(J.pattern=wU),k0.init(X,J)}),uK=E("$ZodIPv4",(X,J)=>{J.pattern??(J.pattern=fU),k0.init(X,J),X._zod.onattach.push(($)=>{let Y=$._zod.bag;Y.format="ipv4"})}),pK=E("$ZodIPv6",(X,J)=>{J.pattern??(J.pattern=gU),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})}}}),cK=E("$ZodCIDRv4",(X,J)=>{J.pattern??(J.pattern=mU),k0.init(X,J)}),lK=E("$ZodCIDRv6",(X,J)=>{J.pattern??(J.pattern=uU),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 dK(X){if(X==="")return!0;if(X.length%4!==0)return!1;try{return atob(X),!0}catch{return!1}}var iK=E("$ZodBase64",(X,J)=>{J.pattern??(J.pattern=pU),k0.init(X,J),X._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64"}),X._zod.check=($)=>{if(dK($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:X,continue:!J.abort})}});function mR(X){if(!IY.test(X))return!1;let J=X.replace(/[-_]/g,(Y)=>Y==="-"?"+":"/"),$=J.padEnd(Math.ceil(J.length/4)*4,"=");return dK($)}var nK=E("$ZodBase64URL",(X,J)=>{J.pattern??(J.pattern=IY),k0.init(X,J),X._zod.onattach.push(($)=>{$._zod.bag.contentEncoding="base64url"}),X._zod.check=($)=>{if(mR($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:X,continue:!J.abort})}}),sK=E("$ZodE164",(X,J)=>{J.pattern??(J.pattern=lU),k0.init(X,J)});function uR(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 aK=E("$ZodJWT",(X,J)=>{k0.init(X,J),X._zod.check=($)=>{if(uR($.value,J.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:X,continue:!J.abort})}});var vY=E("$ZodNumber",(X,J)=>{S0.init(X,J),X._zod.pattern=X._zod.bag.pattern??tU,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}:{}}),$}}),oK=E("$ZodNumber",(X,J)=>{QK.init(X,J),vY.init(X,J)}),rK=E("$ZodBoolean",(X,J)=>{S0.init(X,J),X._zod.pattern=eU,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 tK=E("$ZodNull",(X,J)=>{S0.init(X,J),X._zod.pattern=XK,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 eK=E("$ZodUnknown",(X,J)=>{S0.init(X,J),X._zod.parse=($)=>$}),Xj=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 DK(X,J,$){if(X.issues.length)J.issues.push(...K9($,X.issues));J.value[$]=X.value}var Jj=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)=>DK(B,$,z)));else DK(W,$,z)}if(Q.length)return Promise.all(Q).then(()=>$);return $}});function LX(X,J,$,Y){if(X.issues.length)J.issues.push(...K9($,X.issues));if(X.value===void 0){if($ in Y)J.value[$]=void 0}else J.value[$]=X.value}function $j(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 $=RY(X.shape);return{...X,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set($)}}function Yj(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)=>LX(j,$,H,J)));else LX(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 pR=E("$ZodObject",(X,J)=>{S0.init(X,J);let $=O4(()=>$j(J));q0(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=_1,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 N=H[U]._zod.run({value:W[U],issues:[]},Z);if(N instanceof Promise)B.push(N.then((K)=>LX(K,z,U,W)));else LX(N,z,U,W)}if(!G)return B.length?Promise.all(B).then(()=>z):z;return Yj(B,W,z,Z,$.value,X)}}),Gj=E("$ZodObjectJIT",(X,J)=>{pR.init(X,J);let $=X._zod.parse,Y=O4(()=>$j(J)),G=(j)=>{let N=new xY(["shape","payload","ctx"]),K=Y.value,q=(C)=>{let L=HX(C);return`shape[${L}]._zod.run({ value: input[${L}], issues: [] }, ctx)`};N.write("const input = payload.value;");let F=Object.create(null),O=0;for(let C of K.keys)F[C]=`key_${O++}`;N.write("const newResult = {};");for(let C of K.keys){let L=F[C],P=HX(C);N.write(`const ${L} = ${q(C)};`),N.write(`
170
170
  if (${L}.issues.length) {
171
171
  payload.issues = payload.issues.concat(${L}.issues.map(iss => ({
172
172
  ...iss,
@@ -183,40 +183,40 @@ Body dumps may contain prompt and session content. Turn this off after debugging
183
183
  newResult[${P}] = ${L}.value;
184
184
  }
185
185
 
186
- `)}q.write("payload.value = newResult;"),q.write("return payload;");let _=q.compile();return(C,L)=>_(j,C,L)},Q,z=_1,Z=!ZX.jitless,B=Z&&PY.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 aK([],K,j,q,U,X)}return $(j,q)}});function VK(X,J,$,Y){for(let Q of X)if(Q.issues.length===0)return J.value=Q.value,J;let G=X.filter((Q)=>!h9(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)=>q8(z,Y,c8())))}),J}var kY=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)=>f3(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 VK(Z,G,X,Q);return Promise.all(Z).then((W)=>{return VK(W,G,X,Q)})}}),rK=E("$ZodDiscriminatedUnion",(X,J)=>{kY.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=P4(()=>{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(!_1(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}}),tK=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 UK($,W,B)});return UK($,Q,z)}});function IY(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(y9(X)&&y9(J)){let $=Object.keys(J),Y=Object.keys(X).filter((Q)=>$.indexOf(Q)!==-1),G={...X,...J};for(let Q of Y){let z=IY(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=IY(G,Q);if(!z.valid)return{valid:!1,mergeErrorPath:[Y,...z.mergeErrorPath]};$.push(z.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function UK(X,J,$){if(J.issues.length)X.issues.push(...J.issues);if($.issues.length)X.issues.push(...$.issues);if(h9(X))return X;let Y=IY(J.value,$.value);if(!Y.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Y.mergeErrorPath)}`);return X.value=Y.data,X}var eK=E("$ZodRecord",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{let G=$.value;if(!y9(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(...U9(W,H.issues));$.value[W]=H.value}));else{if(B.issues.length)$.issues.push(...U9(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)=>q8(B,Y,c8())),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(...U9(z,B.issues));$.value[Z.value]=B.value}));else{if(W.issues.length)$.issues.push(...U9(z,W.issues));$.value[Z.value]=W.value}}}if(Q.length)return Promise.all(Q).then(()=>$);return $}});var Xj=E("$ZodEnum",(X,J)=>{S0.init(X,J);let $=y3(J.entries),Y=new Set($);X._zod.values=Y,X._zod.pattern=new RegExp(`^(${$.filter((G)=>OY.has(typeof G)).map((G)=>typeof G==="string"?V9(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}}),Jj=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"?V9($):$?V9($.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 $j=E("$ZodTransform",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{if(Y.direction==="backward")throw new w3(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 H9;return $.value=G,$}});function KK(X,J){if(X.issues.length&&J===void 0)return{issues:[],value:void 0};return X}var Yj=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(`^(${f3($.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)=>KK(Q,$.value));return KK(G,$.value)}if($.value===void 0)return $;return J.innerType._zod.run($,Y)}}),Gj=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(`^(${f3($.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)}}),Qj=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)=>jK(Q,J));return jK(G,J)}});function jK(X,J){if(X.value===void 0)X.value=J.defaultValue;return X}var zj=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)}}),Zj=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 Wj=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)=>q8(z,Y,c8()))},input:$.value}),$.issues=[];return $});if($.value=G.value,G.issues.length)$.value=J.catchValue({...$,error:{issues:G.issues.map((Q)=>q8(Q,Y,c8()))},input:$.value}),$.issues=[];return $}});var Bj=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)=>jX(z,J.in,Y));return jX(Q,J.in,Y)}let G=J.in._zod.run($,Y);if(G instanceof Promise)return G.then((Q)=>jX(Q,J.out,Y));return jX(G,J.out,Y)}});function jX(X,J,$){if(X.issues.length)return X.aborted=!0,X;return J._zod.run({value:X.value,issues:X.issues},$)}var Hj=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(NK);return NK(G)}});function NK(X){return X.value=Object.freeze(X.value),X}var Vj=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)}}),Uj=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)=>LK(Q,$,Y,X));LK(G,$,Y,X);return}});function LK(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(O4(G))}}var ep=Symbol("ZodOutput"),Xc=Symbol("ZodInput");class LX{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 vR(){return new LX}var A1=vR();function Kj(X,J){return new X({type:"string",...Y0(J)})}function jj(X,J){return new X({type:"string",format:"email",check:"string_format",abort:!1,...Y0(J)})}function xY(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 Nj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Y0(J)})}function Lj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Y0(J)})}function Dj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Y0(J)})}function Fj(X,J){return new X({type:"string",format:"url",check:"string_format",abort:!1,...Y0(J)})}function Pj(X,J){return new X({type:"string",format:"emoji",check:"string_format",abort:!1,...Y0(J)})}function Oj(X,J){return new X({type:"string",format:"nanoid",check:"string_format",abort:!1,...Y0(J)})}function Mj(X,J){return new X({type:"string",format:"cuid",check:"string_format",abort:!1,...Y0(J)})}function _j(X,J){return new X({type:"string",format:"cuid2",check:"string_format",abort:!1,...Y0(J)})}function Aj(X,J){return new X({type:"string",format:"ulid",check:"string_format",abort:!1,...Y0(J)})}function Tj(X,J){return new X({type:"string",format:"xid",check:"string_format",abort:!1,...Y0(J)})}function Rj(X,J){return new X({type:"string",format:"ksuid",check:"string_format",abort:!1,...Y0(J)})}function Cj(X,J){return new X({type:"string",format:"ipv4",check:"string_format",abort:!1,...Y0(J)})}function Ej(X,J){return new X({type:"string",format:"ipv6",check:"string_format",abort:!1,...Y0(J)})}function Sj(X,J){return new X({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Y0(J)})}function Ij(X,J){return new X({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Y0(J)})}function bj(X,J){return new X({type:"string",format:"base64",check:"string_format",abort:!1,...Y0(J)})}function kj(X,J){return new X({type:"string",format:"base64url",check:"string_format",abort:!1,...Y0(J)})}function xj(X,J){return new X({type:"string",format:"e164",check:"string_format",abort:!1,...Y0(J)})}function wj(X,J){return new X({type:"string",format:"jwt",check:"string_format",abort:!1,...Y0(J)})}function vj(X,J){return new X({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Y0(J)})}function yj(X,J){return new X({type:"string",format:"date",check:"string_format",...Y0(J)})}function hj(X,J){return new X({type:"string",format:"time",check:"string_format",precision:null,...Y0(J)})}function fj(X,J){return new X({type:"string",format:"duration",check:"string_format",...Y0(J)})}function gj(X,J){return new X({type:"number",checks:[],...Y0(J)})}function mj(X,J){return new X({type:"number",check:"number_format",abort:!1,format:"safeint",...Y0(J)})}function uj(X,J){return new X({type:"boolean",...Y0(J)})}function pj(X,J){return new X({type:"null",...Y0(J)})}function cj(X){return new X({type:"unknown"})}function lj(X,J){return new X({type:"never",...Y0(J)})}function DX(X,J){return new CY({check:"less_than",...Y0(J),value:X,inclusive:!1})}function c3(X,J){return new CY({check:"less_than",...Y0(J),value:X,inclusive:!0})}function FX(X,J){return new EY({check:"greater_than",...Y0(J),value:X,inclusive:!1})}function l3(X,J){return new EY({check:"greater_than",...Y0(J),value:X,inclusive:!0})}function PX(X,J){return new oU({check:"multiple_of",...Y0(J),value:X})}function OX(X,J){return new tU({check:"max_length",...Y0(J),maximum:X})}function M4(X,J){return new eU({check:"min_length",...Y0(J),minimum:X})}function MX(X,J){return new XK({check:"length_equals",...Y0(J),length:X})}function wY(X,J){return new JK({check:"string_format",format:"regex",...Y0(J),pattern:X})}function vY(X){return new $K({check:"string_format",format:"lowercase",...Y0(X)})}function yY(X){return new YK({check:"string_format",format:"uppercase",...Y0(X)})}function hY(X,J){return new GK({check:"string_format",format:"includes",...Y0(J),includes:X})}function fY(X,J){return new QK({check:"string_format",format:"starts_with",...Y0(J),prefix:X})}function gY(X,J){return new zK({check:"string_format",format:"ends_with",...Y0(J),suffix:X})}function T1(X){return new ZK({check:"overwrite",tx:X})}function mY(X){return T1((J)=>J.normalize(X))}function uY(){return T1((X)=>X.trim())}function pY(){return T1((X)=>X.toLowerCase())}function cY(){return T1((X)=>X.toUpperCase())}function dj(X,J,$){return new X({type:"array",element:J,...Y0($)})}function ij(X,J,$){let Y=Y0($);return Y.abort??(Y.abort=!0),new X({type:"custom",check:"custom",fn:J,...Y})}function nj(X,J,$){return new X({type:"custom",check:"custom",fn:J,...Y0($)})}function sj(X){let J=yR(($)=>{return $.addIssue=(Y)=>{if(typeof Y==="string")$.issues.push(O4(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(O4(G))}},X($.value,$)});return J}function yR(X,J){let $=new Z6({check:"custom",...Y0(J)});return $._zod.check=X,$}class lY{constructor(X){this.counter=0,this.metadataRegistry=X?.metadata??A1,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:N,format:F,patterns:O,contentEncoding:_}=X._zod.bag;if(typeof K==="number")q.minLength=K;if(typeof N==="number")q.maxLength=N;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((L)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:L.source}))]}break}case"number":{let q=j,{minimum:K,maximum:N,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 N==="number"){if(q.maximum=N,typeof _==="number"&&this.target!=="draft-4")if(_<=N)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:N}=X._zod.bag;if(typeof K==="number")q.minItems=K;if(typeof N==="number")q.maxItems=N;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 N=new Set(Object.keys(K)),F=new Set([...N].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((N,F)=>this.process(N,{...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]}),N=this.process(Y.right,{...H,path:[...H.path,"allOf",1]}),F=(_)=>("allOf"in _)&&Object.keys(_).length===1,O=[...F(K)?K.allOf:[K],...F(N)?N.allOf:[N]];q.allOf=O;break}case"tuple":{let q=j;q.type="array";let K=this.target==="draft-2020-12"?"prefixItems":"items",N=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",F=Y.items.map((L,P)=>this.process(L,{...H,path:[...H.path,K,P]})),O=Y.rest?this.process(Y.rest,{...H,path:[...H.path,N,...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=y3(Y.entries);if(K.every((N)=>typeof N==="number"))q.type="number";if(K.every((N)=>typeof N==="string"))q.type="string";q.enum=K;break}case"literal":{let q=j,K=[];for(let N of Y.values)if(N===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof N==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else K.push(Number(N));else K.push(N);if(K.length===0);else if(K.length===1){let N=K[0];if(q.type=N===null?"null":typeof N,this.target==="draft-4"||this.target==="openapi-3.0")q.enum=[N];else q.const=N}else{if(K.every((N)=>typeof N==="number"))q.type="number";if(K.every((N)=>typeof N==="string"))q.type="string";if(K.every((N)=>typeof N==="boolean"))q.type="string";if(K.every((N)=>N===null))q.type="null";q.enum=K}break}case"file":{let q=j,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:N,maximum:F,mime:O}=X._zod.bag;if(N!==void 0)K.minLength=N;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"&&a0(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,N=$.external.uri??((O)=>O);if(K)return{ref:N(K)};let F=B[1].defId??B[1].schema.id??`schema${this.counter++}`;return B[1].defId=F,{defId:F,ref:`${N("__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
+ `)}N.write("payload.value = newResult;"),N.write("return payload;");let _=N.compile();return(C,L)=>_(j,C,L)},Q,z=_1,Z=!BX.jitless,B=Z&&AY.value,H=J.catchall,U;X._zod.parse=(j,N)=>{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&&N?.async===!1&&N.jitless!==!0){if(!Q)Q=G(J.shape);if(j=Q(j,N),!H)return j;return Yj([],K,j,N,U,X)}return $(j,N)}});function FK(X,J,$,Y){for(let Q of X)if(Q.issues.length===0)return J.value=Q.value,J;let G=X.filter((Q)=>!f9(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)=>q8(z,Y,c8())))}),J}var yY=E("$ZodUnion",(X,J)=>{S0.init(X,J),q0(X._zod,"optin",()=>J.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),q0(X._zod,"optout",()=>J.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),q0(X._zod,"values",()=>{if(J.options.every((G)=>G._zod.values))return new Set(J.options.flatMap((G)=>Array.from(G._zod.values)));return}),q0(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)=>m3(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 FK(Z,G,X,Q);return Promise.all(Z).then((W)=>{return FK(W,G,X,Q)})}}),Qj=E("$ZodDiscriminatedUnion",(X,J)=>{yY.init(X,J);let $=X._zod.parse;q0(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=O4(()=>{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(!_1(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}}),zj=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 PK($,W,B)});return PK($,Q,z)}});function wY(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(h9(X)&&h9(J)){let $=Object.keys(J),Y=Object.keys(X).filter((Q)=>$.indexOf(Q)!==-1),G={...X,...J};for(let Q of Y){let z=wY(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=wY(G,Q);if(!z.valid)return{valid:!1,mergeErrorPath:[Y,...z.mergeErrorPath]};$.push(z.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function PK(X,J,$){if(J.issues.length)X.issues.push(...J.issues);if($.issues.length)X.issues.push(...$.issues);if(f9(X))return X;let Y=wY(J.value,$.value);if(!Y.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Y.mergeErrorPath)}`);return X.value=Y.data,X}var Zj=E("$ZodRecord",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{let G=$.value;if(!h9(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(...K9(W,H.issues));$.value[W]=H.value}));else{if(B.issues.length)$.issues.push(...K9(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)=>q8(B,Y,c8())),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(...K9(z,B.issues));$.value[Z.value]=B.value}));else{if(W.issues.length)$.issues.push(...K9(z,W.issues));$.value[Z.value]=W.value}}}if(Q.length)return Promise.all(Q).then(()=>$);return $}});var Wj=E("$ZodEnum",(X,J)=>{S0.init(X,J);let $=f3(J.entries),Y=new Set($);X._zod.values=Y,X._zod.pattern=new RegExp(`^(${$.filter((G)=>TY.has(typeof G)).map((G)=>typeof G==="string"?U9(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}}),Bj=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"?U9($):$?U9($.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 Hj=E("$ZodTransform",(X,J)=>{S0.init(X,J),X._zod.parse=($,Y)=>{if(Y.direction==="backward")throw new y3(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 V9;return $.value=G,$}});function OK(X,J){if(X.issues.length&&J===void 0)return{issues:[],value:void 0};return X}var Vj=E("$ZodOptional",(X,J)=>{S0.init(X,J),X._zod.optin="optional",X._zod.optout="optional",q0(X._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,void 0]):void 0}),q0(X._zod,"pattern",()=>{let $=J.innerType._zod.pattern;return $?new RegExp(`^(${m3($.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)=>OK(Q,$.value));return OK(G,$.value)}if($.value===void 0)return $;return J.innerType._zod.run($,Y)}}),Uj=E("$ZodNullable",(X,J)=>{S0.init(X,J),q0(X._zod,"optin",()=>J.innerType._zod.optin),q0(X._zod,"optout",()=>J.innerType._zod.optout),q0(X._zod,"pattern",()=>{let $=J.innerType._zod.pattern;return $?new RegExp(`^(${m3($.source)}|null)$`):void 0}),q0(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)}}),Kj=E("$ZodDefault",(X,J)=>{S0.init(X,J),X._zod.optin="optional",q0(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)=>MK(Q,J));return MK(G,J)}});function MK(X,J){if(X.value===void 0)X.value=J.defaultValue;return X}var jj=E("$ZodPrefault",(X,J)=>{S0.init(X,J),X._zod.optin="optional",q0(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)}}),Nj=E("$ZodNonOptional",(X,J)=>{S0.init(X,J),q0(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)=>_K(Q,X));return _K(G,X)}});function _K(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 qj=E("$ZodCatch",(X,J)=>{S0.init(X,J),q0(X._zod,"optin",()=>J.innerType._zod.optin),q0(X._zod,"optout",()=>J.innerType._zod.optout),q0(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)=>q8(z,Y,c8()))},input:$.value}),$.issues=[];return $});if($.value=G.value,G.issues.length)$.value=J.catchValue({...$,error:{issues:G.issues.map((Q)=>q8(Q,Y,c8()))},input:$.value}),$.issues=[];return $}});var Lj=E("$ZodPipe",(X,J)=>{S0.init(X,J),q0(X._zod,"values",()=>J.in._zod.values),q0(X._zod,"optin",()=>J.in._zod.optin),q0(X._zod,"optout",()=>J.out._zod.optout),q0(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)=>qX(z,J.in,Y));return qX(Q,J.in,Y)}let G=J.in._zod.run($,Y);if(G instanceof Promise)return G.then((Q)=>qX(Q,J.out,Y));return qX(G,J.out,Y)}});function qX(X,J,$){if(X.issues.length)return X.aborted=!0,X;return J._zod.run({value:X.value,issues:X.issues},$)}var Dj=E("$ZodReadonly",(X,J)=>{S0.init(X,J),q0(X._zod,"propValues",()=>J.innerType._zod.propValues),q0(X._zod,"values",()=>J.innerType._zod.values),q0(X._zod,"optin",()=>J.innerType._zod.optin),q0(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(AK);return AK(G)}});function AK(X){return X.value=Object.freeze(X.value),X}var Fj=E("$ZodLazy",(X,J)=>{S0.init(X,J),q0(X._zod,"innerType",()=>J.getter()),q0(X._zod,"pattern",()=>X._zod.innerType._zod.pattern),q0(X._zod,"propValues",()=>X._zod.innerType._zod.propValues),q0(X._zod,"optin",()=>X._zod.innerType._zod.optin??void 0),q0(X._zod,"optout",()=>X._zod.innerType._zod.optout??void 0),X._zod.parse=($,Y)=>{return X._zod.innerType._zod.run($,Y)}}),Pj=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)=>TK(Q,$,Y,X));TK(G,$,Y,X);return}});function TK(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(M4(G))}}var qc=Symbol("ZodOutput"),Lc=Symbol("ZodInput");class FX{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 cR(){return new FX}var A1=cR();function Oj(X,J){return new X({type:"string",...Y0(J)})}function Mj(X,J){return new X({type:"string",format:"email",check:"string_format",abort:!1,...Y0(J)})}function hY(X,J){return new X({type:"string",format:"guid",check:"string_format",abort:!1,...Y0(J)})}function _j(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,...Y0(J)})}function Aj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Y0(J)})}function Tj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Y0(J)})}function Rj(X,J){return new X({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Y0(J)})}function Cj(X,J){return new X({type:"string",format:"url",check:"string_format",abort:!1,...Y0(J)})}function Ej(X,J){return new X({type:"string",format:"emoji",check:"string_format",abort:!1,...Y0(J)})}function Sj(X,J){return new X({type:"string",format:"nanoid",check:"string_format",abort:!1,...Y0(J)})}function Ij(X,J){return new X({type:"string",format:"cuid",check:"string_format",abort:!1,...Y0(J)})}function bj(X,J){return new X({type:"string",format:"cuid2",check:"string_format",abort:!1,...Y0(J)})}function kj(X,J){return new X({type:"string",format:"ulid",check:"string_format",abort:!1,...Y0(J)})}function xj(X,J){return new X({type:"string",format:"xid",check:"string_format",abort:!1,...Y0(J)})}function wj(X,J){return new X({type:"string",format:"ksuid",check:"string_format",abort:!1,...Y0(J)})}function vj(X,J){return new X({type:"string",format:"ipv4",check:"string_format",abort:!1,...Y0(J)})}function yj(X,J){return new X({type:"string",format:"ipv6",check:"string_format",abort:!1,...Y0(J)})}function hj(X,J){return new X({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Y0(J)})}function fj(X,J){return new X({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Y0(J)})}function gj(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 uj(X,J){return new X({type:"string",format:"e164",check:"string_format",abort:!1,...Y0(J)})}function pj(X,J){return new X({type:"string",format:"jwt",check:"string_format",abort:!1,...Y0(J)})}function cj(X,J){return new X({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Y0(J)})}function lj(X,J){return new X({type:"string",format:"date",check:"string_format",...Y0(J)})}function dj(X,J){return new X({type:"string",format:"time",check:"string_format",precision:null,...Y0(J)})}function ij(X,J){return new X({type:"string",format:"duration",check:"string_format",...Y0(J)})}function nj(X,J){return new X({type:"number",checks:[],...Y0(J)})}function sj(X,J){return new X({type:"number",check:"number_format",abort:!1,format:"safeint",...Y0(J)})}function aj(X,J){return new X({type:"boolean",...Y0(J)})}function oj(X,J){return new X({type:"null",...Y0(J)})}function rj(X){return new X({type:"unknown"})}function tj(X,J){return new X({type:"never",...Y0(J)})}function PX(X,J){return new bY({check:"less_than",...Y0(J),value:X,inclusive:!1})}function d3(X,J){return new bY({check:"less_than",...Y0(J),value:X,inclusive:!0})}function OX(X,J){return new kY({check:"greater_than",...Y0(J),value:X,inclusive:!1})}function i3(X,J){return new kY({check:"greater_than",...Y0(J),value:X,inclusive:!0})}function MX(X,J){return new GK({check:"multiple_of",...Y0(J),value:X})}function _X(X,J){return new zK({check:"max_length",...Y0(J),maximum:X})}function _4(X,J){return new ZK({check:"min_length",...Y0(J),minimum:X})}function AX(X,J){return new WK({check:"length_equals",...Y0(J),length:X})}function fY(X,J){return new BK({check:"string_format",format:"regex",...Y0(J),pattern:X})}function gY(X){return new HK({check:"string_format",format:"lowercase",...Y0(X)})}function mY(X){return new VK({check:"string_format",format:"uppercase",...Y0(X)})}function uY(X,J){return new UK({check:"string_format",format:"includes",...Y0(J),includes:X})}function pY(X,J){return new KK({check:"string_format",format:"starts_with",...Y0(J),prefix:X})}function cY(X,J){return new jK({check:"string_format",format:"ends_with",...Y0(J),suffix:X})}function T1(X){return new NK({check:"overwrite",tx:X})}function lY(X){return T1((J)=>J.normalize(X))}function dY(){return T1((X)=>X.trim())}function iY(){return T1((X)=>X.toLowerCase())}function nY(){return T1((X)=>X.toUpperCase())}function ej(X,J,$){return new X({type:"array",element:J,...Y0($)})}function XN(X,J,$){let Y=Y0($);return Y.abort??(Y.abort=!0),new X({type:"custom",check:"custom",fn:J,...Y})}function JN(X,J,$){return new X({type:"custom",check:"custom",fn:J,...Y0($)})}function $N(X){let J=lR(($)=>{return $.addIssue=(Y)=>{if(typeof Y==="string")$.issues.push(M4(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(M4(G))}},X($.value,$)});return J}function lR(X,J){let $=new Z6({check:"custom",...Y0(J)});return $._zod.check=X,$}class sY{constructor(X){this.counter=0,this.metadataRegistry=X?.metadata??A1,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 N=j;N.type="string";let{minimum:K,maximum:q,format:F,patterns:O,contentEncoding:_}=X._zod.bag;if(typeof K==="number")N.minLength=K;if(typeof q==="number")N.maxLength=q;if(F){if(N.format=G[F]??F,N.format==="")delete N.format}if(_)N.contentEncoding=_;if(O&&O.size>0){let C=[...O];if(C.length===1)N.pattern=C[0].source;else if(C.length>1)z.schema.allOf=[...C.map((L)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:L.source}))]}break}case"number":{let N=j,{minimum:K,maximum:q,format:F,multipleOf:O,exclusiveMaximum:_,exclusiveMinimum:C}=X._zod.bag;if(typeof F==="string"&&F.includes("int"))N.type="integer";else N.type="number";if(typeof C==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.minimum=C,N.exclusiveMinimum=!0;else N.exclusiveMinimum=C;if(typeof K==="number"){if(N.minimum=K,typeof C==="number"&&this.target!=="draft-4")if(C>=K)delete N.minimum;else delete N.exclusiveMinimum}if(typeof _==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")N.maximum=_,N.exclusiveMaximum=!0;else N.exclusiveMaximum=_;if(typeof q==="number"){if(N.maximum=q,typeof _==="number"&&this.target!=="draft-4")if(_<=q)delete N.maximum;else delete N.exclusiveMaximum}if(typeof O==="number")N.multipleOf=O;break}case"boolean":{let N=j;N.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 N=j,{minimum:K,maximum:q}=X._zod.bag;if(typeof K==="number")N.minItems=K;if(typeof q==="number")N.maxItems=q;N.type="array",N.items=this.process(Y.element,{...H,path:[...H.path,"items"]});break}case"object":{let N=j;N.type="object",N.properties={};let K=Y.shape;for(let O in K)N.properties[O]=this.process(K[O],{...H,path:[...H.path,"properties",O]});let q=new Set(Object.keys(K)),F=new Set([...q].filter((O)=>{let _=Y.shape[O]._zod;if(this.io==="input")return _.optin===void 0;else return _.optout===void 0}));if(F.size>0)N.required=Array.from(F);if(Y.catchall?._zod.def.type==="never")N.additionalProperties=!1;else if(!Y.catchall){if(this.io==="output")N.additionalProperties=!1}else if(Y.catchall)N.additionalProperties=this.process(Y.catchall,{...H,path:[...H.path,"additionalProperties"]});break}case"union":{let N=j,K=Y.options.map((q,F)=>this.process(q,{...H,path:[...H.path,"anyOf",F]}));N.anyOf=K;break}case"intersection":{let N=j,K=this.process(Y.left,{...H,path:[...H.path,"allOf",0]}),q=this.process(Y.right,{...H,path:[...H.path,"allOf",1]}),F=(_)=>("allOf"in _)&&Object.keys(_).length===1,O=[...F(K)?K.allOf:[K],...F(q)?q.allOf:[q]];N.allOf=O;break}case"tuple":{let N=j;N.type="array";let K=this.target==="draft-2020-12"?"prefixItems":"items",q=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",F=Y.items.map((L,P)=>this.process(L,{...H,path:[...H.path,K,P]})),O=Y.rest?this.process(Y.rest,{...H,path:[...H.path,q,...this.target==="openapi-3.0"?[Y.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(N.prefixItems=F,O)N.items=O}else if(this.target==="openapi-3.0"){if(N.items={anyOf:F},O)N.items.anyOf.push(O);if(N.minItems=F.length,!O)N.maxItems=F.length}else if(N.items=F,O)N.additionalItems=O;let{minimum:_,maximum:C}=X._zod.bag;if(typeof _==="number")N.minItems=_;if(typeof C==="number")N.maxItems=C;break}case"record":{let N=j;if(N.type="object",this.target==="draft-7"||this.target==="draft-2020-12")N.propertyNames=this.process(Y.keyType,{...H,path:[...H.path,"propertyNames"]});N.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 N=j,K=f3(Y.entries);if(K.every((q)=>typeof q==="number"))N.type="number";if(K.every((q)=>typeof q==="string"))N.type="string";N.enum=K;break}case"literal":{let N=j,K=[];for(let q of Y.values)if(q===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof q==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else K.push(Number(q));else K.push(q);if(K.length===0);else if(K.length===1){let q=K[0];if(N.type=q===null?"null":typeof q,this.target==="draft-4"||this.target==="openapi-3.0")N.enum=[q];else N.const=q}else{if(K.every((q)=>typeof q==="number"))N.type="number";if(K.every((q)=>typeof q==="string"))N.type="string";if(K.every((q)=>typeof q==="boolean"))N.type="string";if(K.every((q)=>q===null))N.type="null";N.enum=K}break}case"file":{let N=j,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:q,maximum:F,mime:O}=X._zod.bag;if(q!==void 0)K.minLength=q;if(F!==void 0)K.maxLength=F;if(O)if(O.length===1)K.contentMediaType=O[0],Object.assign(N,K);else N.anyOf=O.map((_)=>{return{...K,contentMediaType:_}});else Object.assign(N,K);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let N=this.process(Y.innerType,H);if(this.target==="openapi-3.0")z.ref=Y.innerType,j.nullable=!0;else j.anyOf=[N,{type:"null"}];break}case"nonoptional":{this.process(Y.innerType,H),z.ref=Y.innerType;break}case"success":{let N=j;N.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 N;try{N=Y.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}j.default=N;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let N=j,K=X._zod.pattern;if(!K)throw Error("Pattern not found in template literal");N.type="string",N.pattern=K.source;break}case"pipe":{let N=this.io==="input"?Y.in._zod.def.type==="transform"?Y.out:Y.in:Y.out;this.process(N,H),z.ref=N;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 N=X._zod.innerType;this.process(N,H),z.ref=N;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"&&a0(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,q=$.external.uri??((O)=>O);if(K)return{ref:q(K)};let F=B[1].defId??B[1].schema.id??`schema${this.counter++}`;return B[1].defId=F,{defId:F,ref:`${q("__shared")}#/${H}/${F}`}}if(B[1]===Y)return{ref:"#"};let j=`${"#"}/${H}/`,N=B[1].schema.id??`__schema${this.counter++}`;return{defId:N,ref:j+N}},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 N=H.schema;for(let K in N)delete N[K];N.$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>
187
187
 
188
- 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 N=this.seen.get(K).schema;if(N.$ref&&(H.target==="draft-7"||H.target==="draft-4"||H.target==="openapi-3.0"))j.allOf=j.allOf??[],j.allOf.push(N);else Object.assign(j,N),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 aj(X,J){if(X instanceof LX){let Y=new lY(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 lY(J);return $.process(X),$.emit(X,J)}function a0(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 a0(G.element,$);case"object":{for(let Q in G.shape)if(a0(G.shape[Q],$))return!0;return!1}case"union":{for(let Q of G.options)if(a0(Q,$))return!0;return!1}case"intersection":return a0(G.left,$)||a0(G.right,$);case"tuple":{for(let Q of G.items)if(a0(Q,$))return!0;if(G.rest&&a0(G.rest,$))return!0;return!1}case"record":return a0(G.keyType,$)||a0(G.valueType,$);case"map":return a0(G.keyType,$)||a0(G.valueType,$);case"set":return a0(G.valueType,$);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return a0(G.innerType,$);case"lazy":return a0(G.getter(),$);case"default":return a0(G.innerType,$);case"prefault":return a0(G.innerType,$);case"custom":return!1;case"transform":return!0;case"pipe":return a0(G.in,$)||a0(G.out,$);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${G.type}`)}var pR=E("ZodISODateTime",(X,J)=>{SK.init(X,J),y0.init(X,J)});function oj(X){return vj(pR,X)}var cR=E("ZodISODate",(X,J)=>{IK.init(X,J),y0.init(X,J)});function rj(X){return yj(cR,X)}var lR=E("ZodISOTime",(X,J)=>{bK.init(X,J),y0.init(X,J)});function tj(X){return hj(lR,X)}var dR=E("ZodISODuration",(X,J)=>{kK.init(X,J),y0.init(X,J)});function ej(X){return fj(dR,X)}var Xq=(X,J)=>{HX.init(X,J),X.name="ZodError",Object.defineProperties(X,{format:{value:($)=>BU(X,$)},flatten:{value:($)=>WU(X,$)},addIssue:{value:($)=>{X.issues.push($),X.message=JSON.stringify(X.issues,F4,2)}},addIssues:{value:($)=>{X.issues.push(...$),X.message=JSON.stringify(X.issues,F4,2)}},isEmpty:{get(){return X.issues.length===0}}})},Ic=E("ZodError",Xq),l6=E("ZodError",Xq,{Parent:Error});var Jq=VX(l6),$q=UX(l6),Yq=m3(l6),AX=u3(l6),Gq=UU(l6),Qq=KU(l6),zq=jU(l6),Zq=qU(l6),Wq=NU(l6),Bq=LU(l6),Hq=DU(l6),Vq=FU(l6);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)=>j8(X,$,Y),X.brand=()=>X,X.register=($,Y)=>{return $.add(X,Y),X},X.parse=($,Y)=>Jq(X,$,Y,{callee:X.parse}),X.safeParse=($,Y)=>Yq(X,$,Y),X.parseAsync=async($,Y)=>$q(X,$,Y,{callee:X.parseAsync}),X.safeParseAsync=async($,Y)=>AX(X,$,Y),X.spa=X.safeParseAsync,X.encode=($,Y)=>Gq(X,$,Y),X.decode=($,Y)=>Qq(X,$,Y),X.encodeAsync=async($,Y)=>zq(X,$,Y),X.decodeAsync=async($,Y)=>Zq(X,$,Y),X.safeEncode=($,Y)=>Wq(X,$,Y),X.safeDecode=($,Y)=>Bq(X,$,Y),X.safeEncodeAsync=async($,Y)=>Hq(X,$,Y),X.safeDecodeAsync=async($,Y)=>Vq(X,$,Y),X.refine=($,Y)=>X.check(fC($,Y)),X.superRefine=($)=>X.check(gC($)),X.overwrite=($)=>X.check(T1($)),X.optional=()=>jq(X),X.nullable=()=>qq(X),X.nullish=()=>jq(qq(X)),X.nonoptional=($)=>bC(X,$),X.array=()=>nY(X),X.or=($)=>sY([X,$]),X.and=($)=>OC(X,$),X.transform=($)=>Nq(X,TC($)),X.default=($)=>EC(X,$),X.prefault=($)=>IC(X,$),X.catch=($)=>xC(X,$),X.pipe=($)=>Nq(X,$),X.readonly=()=>yC(X),X.describe=($)=>{let Y=X.clone();return A1.add(Y,{description:$}),Y},Object.defineProperty(X,"description",{get(){return A1.get(X)?.description},configurable:!0}),X.meta=(...$)=>{if($.length===0)return A1.get(X);let Y=X.clone();return A1.add(Y,$[0]),Y},X.isOptional=()=>X.safeParse(void 0).success,X.isNullable=()=>X.safeParse(null).success,X}),Lq=E("_ZodString",(X,J)=>{NX.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(wY(...Y)),X.includes=(...Y)=>X.check(hY(...Y)),X.startsWith=(...Y)=>X.check(fY(...Y)),X.endsWith=(...Y)=>X.check(gY(...Y)),X.min=(...Y)=>X.check(M4(...Y)),X.max=(...Y)=>X.check(OX(...Y)),X.length=(...Y)=>X.check(MX(...Y)),X.nonempty=(...Y)=>X.check(M4(1,...Y)),X.lowercase=(Y)=>X.check(vY(Y)),X.uppercase=(Y)=>X.check(yY(Y)),X.trim=()=>X.check(uY()),X.normalize=(...Y)=>X.check(mY(...Y)),X.toLowerCase=()=>X.check(pY()),X.toUpperCase=()=>X.check(cY())}),aR=E("ZodString",(X,J)=>{NX.init(X,J),Lq.init(X,J),X.email=($)=>X.check(jj(oR,$)),X.url=($)=>X.check(Fj(rR,$)),X.jwt=($)=>X.check(wj(UC,$)),X.emoji=($)=>X.check(Pj(tR,$)),X.guid=($)=>X.check(xY(Uq,$)),X.uuid=($)=>X.check(qj(TX,$)),X.uuidv4=($)=>X.check(Nj(TX,$)),X.uuidv6=($)=>X.check(Lj(TX,$)),X.uuidv7=($)=>X.check(Dj(TX,$)),X.nanoid=($)=>X.check(Oj(eR,$)),X.guid=($)=>X.check(xY(Uq,$)),X.cuid=($)=>X.check(Mj(XC,$)),X.cuid2=($)=>X.check(_j(JC,$)),X.ulid=($)=>X.check(Aj($C,$)),X.base64=($)=>X.check(bj(BC,$)),X.base64url=($)=>X.check(kj(HC,$)),X.xid=($)=>X.check(Tj(YC,$)),X.ksuid=($)=>X.check(Rj(GC,$)),X.ipv4=($)=>X.check(Cj(QC,$)),X.ipv6=($)=>X.check(Ej(zC,$)),X.cidrv4=($)=>X.check(Sj(ZC,$)),X.cidrv6=($)=>X.check(Ij(WC,$)),X.e164=($)=>X.check(xj(VC,$)),X.datetime=($)=>X.check(oj($)),X.date=($)=>X.check(rj($)),X.time=($)=>X.check(tj($)),X.duration=($)=>X.check(ej($))});function Dq(X){return Kj(aR,X)}var y0=E("ZodStringFormat",(X,J)=>{k0.init(X,J),Lq.init(X,J)}),oR=E("ZodEmail",(X,J)=>{PK.init(X,J),y0.init(X,J)});var Uq=E("ZodGUID",(X,J)=>{DK.init(X,J),y0.init(X,J)});var TX=E("ZodUUID",(X,J)=>{FK.init(X,J),y0.init(X,J)});var rR=E("ZodURL",(X,J)=>{OK.init(X,J),y0.init(X,J)});var tR=E("ZodEmoji",(X,J)=>{MK.init(X,J),y0.init(X,J)});var eR=E("ZodNanoID",(X,J)=>{_K.init(X,J),y0.init(X,J)});var XC=E("ZodCUID",(X,J)=>{AK.init(X,J),y0.init(X,J)});var JC=E("ZodCUID2",(X,J)=>{TK.init(X,J),y0.init(X,J)});var $C=E("ZodULID",(X,J)=>{RK.init(X,J),y0.init(X,J)});var YC=E("ZodXID",(X,J)=>{CK.init(X,J),y0.init(X,J)});var GC=E("ZodKSUID",(X,J)=>{EK.init(X,J),y0.init(X,J)});var QC=E("ZodIPv4",(X,J)=>{xK.init(X,J),y0.init(X,J)});var zC=E("ZodIPv6",(X,J)=>{wK.init(X,J),y0.init(X,J)});var ZC=E("ZodCIDRv4",(X,J)=>{vK.init(X,J),y0.init(X,J)});var WC=E("ZodCIDRv6",(X,J)=>{yK.init(X,J),y0.init(X,J)});var BC=E("ZodBase64",(X,J)=>{fK.init(X,J),y0.init(X,J)});var HC=E("ZodBase64URL",(X,J)=>{gK.init(X,J),y0.init(X,J)});var VC=E("ZodE164",(X,J)=>{mK.init(X,J),y0.init(X,J)});var UC=E("ZodJWT",(X,J)=>{uK.init(X,J),y0.init(X,J)});var Fq=E("ZodNumber",(X,J)=>{bY.init(X,J),h0.init(X,J),X.gt=(Y,G)=>X.check(FX(Y,G)),X.gte=(Y,G)=>X.check(l3(Y,G)),X.min=(Y,G)=>X.check(l3(Y,G)),X.lt=(Y,G)=>X.check(DX(Y,G)),X.lte=(Y,G)=>X.check(c3(Y,G)),X.max=(Y,G)=>X.check(c3(Y,G)),X.int=(Y)=>X.check(Kq(Y)),X.safe=(Y)=>X.check(Kq(Y)),X.positive=(Y)=>X.check(FX(0,Y)),X.nonnegative=(Y)=>X.check(l3(0,Y)),X.negative=(Y)=>X.check(DX(0,Y)),X.nonpositive=(Y)=>X.check(c3(0,Y)),X.multipleOf=(Y,G)=>X.check(PX(Y,G)),X.step=(Y,G)=>X.check(PX(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 Pq(X){return gj(Fq,X)}var KC=E("ZodNumberFormat",(X,J)=>{pK.init(X,J),Fq.init(X,J)});function Kq(X){return mj(KC,X)}var jC=E("ZodBoolean",(X,J)=>{cK.init(X,J),h0.init(X,J)});function Oq(X){return uj(jC,X)}var qC=E("ZodNull",(X,J)=>{lK.init(X,J),h0.init(X,J)});function Mq(X){return pj(qC,X)}var NC=E("ZodUnknown",(X,J)=>{dK.init(X,J),h0.init(X,J)});function d3(){return cj(NC)}var LC=E("ZodNever",(X,J)=>{iK.init(X,J),h0.init(X,J)});function iY(X){return lj(LC,X)}var DC=E("ZodArray",(X,J)=>{nK.init(X,J),h0.init(X,J),X.element=J.element,X.min=($,Y)=>X.check(M4($,Y)),X.nonempty=($)=>X.check(M4(1,$)),X.max=($,Y)=>X.check(OX($,Y)),X.length=($,Y)=>X.check(MX($,Y)),X.unwrap=()=>X.element});function nY(X,J){return dj(DC,X,J)}var _q=E("ZodObject",(X,J)=>{oK.init(X,J),h0.init(X,J),j0.defineLazy(X,"shape",()=>J.shape),X.keyof=()=>aY(Object.keys(X._zod.def.shape)),X.catchall=($)=>X.clone({...X._zod.def,catchall:$}),X.passthrough=()=>X.clone({...X._zod.def,catchall:d3()}),X.loose=()=>X.clone({...X._zod.def,catchall:d3()}),X.strict=()=>X.clone({...X._zod.def,catchall:iY()}),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(Iq,X,$[0]),X.required=(...$)=>j0.required(bq,X,$[0])});function Aq(X,J){let $={type:"object",get shape(){return j0.assignProp(this,"shape",X?j0.objectClone(X):{}),this.shape},...j0.normalizeParams(J)};return new _q($)}function Tq(X,J){return new _q({type:"object",get shape(){return j0.assignProp(this,"shape",j0.objectClone(X)),this.shape},catchall:d3(),...j0.normalizeParams(J)})}var Rq=E("ZodUnion",(X,J)=>{kY.init(X,J),h0.init(X,J),X.options=J.options});function sY(X,J){return new Rq({type:"union",options:X,...j0.normalizeParams(J)})}var FC=E("ZodDiscriminatedUnion",(X,J)=>{Rq.init(X,J),rK.init(X,J)});function Cq(X,J,$){return new FC({type:"union",options:J,discriminator:X,...j0.normalizeParams($)})}var PC=E("ZodIntersection",(X,J)=>{tK.init(X,J),h0.init(X,J)});function OC(X,J){return new PC({type:"intersection",left:X,right:J})}var MC=E("ZodRecord",(X,J)=>{eK.init(X,J),h0.init(X,J),X.keyType=J.keyType,X.valueType=J.valueType});function Eq(X,J,$){return new MC({type:"record",keyType:X,valueType:J,...j0.normalizeParams($)})}var dY=E("ZodEnum",(X,J)=>{Xj.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 dY({...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 dY({...J,checks:[],...j0.normalizeParams(G),entries:Q})}});function aY(X,J){let $=Array.isArray(X)?Object.fromEntries(X.map((Y)=>[Y,Y])):X;return new dY({type:"enum",entries:$,...j0.normalizeParams(J)})}var _C=E("ZodLiteral",(X,J)=>{Jj.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 Sq(X,J){return new _C({type:"literal",values:Array.isArray(X)?X:[X],...j0.normalizeParams(J)})}var AC=E("ZodTransform",(X,J)=>{$j.init(X,J),h0.init(X,J),X._zod.parse=($,Y)=>{if(Y.direction==="backward")throw new w3(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 TC(X){return new AC({type:"transform",transform:X})}var Iq=E("ZodOptional",(X,J)=>{Yj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function jq(X){return new Iq({type:"optional",innerType:X})}var RC=E("ZodNullable",(X,J)=>{Gj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function qq(X){return new RC({type:"nullable",innerType:X})}var CC=E("ZodDefault",(X,J)=>{Qj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType,X.removeDefault=X.unwrap});function EC(X,J){return new CC({type:"default",innerType:X,get defaultValue(){return typeof J==="function"?J():j0.shallowClone(J)}})}var SC=E("ZodPrefault",(X,J)=>{zj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function IC(X,J){return new SC({type:"prefault",innerType:X,get defaultValue(){return typeof J==="function"?J():j0.shallowClone(J)}})}var bq=E("ZodNonOptional",(X,J)=>{Zj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function bC(X,J){return new bq({type:"nonoptional",innerType:X,...j0.normalizeParams(J)})}var kC=E("ZodCatch",(X,J)=>{Wj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType,X.removeCatch=X.unwrap});function xC(X,J){return new kC({type:"catch",innerType:X,catchValue:typeof J==="function"?J:()=>J})}var wC=E("ZodPipe",(X,J)=>{Bj.init(X,J),h0.init(X,J),X.in=J.in,X.out=J.out});function Nq(X,J){return new wC({type:"pipe",in:X,out:J})}var vC=E("ZodReadonly",(X,J)=>{Hj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function yC(X){return new vC({type:"readonly",innerType:X})}var hC=E("ZodLazy",(X,J)=>{Vj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.getter()});function kq(X){return new hC({type:"lazy",getter:X})}var oY=E("ZodCustom",(X,J)=>{Uj.init(X,J),h0.init(X,J)});function xq(X,J){return ij(oY,X??(()=>!0),J)}function fC(X,J={}){return nj(oY,X,J)}function gC(X){return sj(X)}function wq(X,J={error:`Input not instance of ${X.name}`}){let $=new oY({type:"custom",check:"custom",fn:(Y)=>Y instanceof X,abort:!0,...j0.normalizeParams(J)});return $._zod.bag.Class=X,$}function lq(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 dq(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 iq(X,...J){let $=new Headers(dq(X)),Y=$.get("user-agent")||"";return $.set("user-agent",[Y,...J].filter(Boolean).join(" ")),Object.fromEntries($.entries())}var cC=[{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]}],Ol=[...cC,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];async function RX(X){try{await X.body?.cancel()}catch{}}var nq="AI_DownloadError",sq=`vercel.ai.error.${nq}`,lC=Symbol.for(sq),N6=class extends B9{constructor({url:X,statusCode:J,statusText:$,cause:Y,message:G=Y==null?`Failed to download ${X}: ${J} ${$}`:`Failed to download ${X}: ${Y}`}){super({name:nq,message:G,cause:Y});this[lC]=!0,this.url=X,this.statusCode=J,this.statusText=$}static isInstance(X){return B9.hasMarker(X,sq)}};function dC(X=globalThis){return X.window!=null}function eY(X,J){try{return new URL(X).origin===new URL(J).origin}catch{return!1}}function iC(X){let J;try{J=new URL(X)}catch{throw new N6({url:X,message:`Invalid URL: ${X}`})}if(J.protocol==="data:")return;if(J.protocol!=="http:"&&J.protocol!=="https:")throw new N6({url:X,message:`URL scheme must be http, https, or data, got ${J.protocol}`});let $=J.hostname.toLowerCase().replace(/\.+$/,"");if(!$)throw new N6({url:X,message:"URL must have a hostname"});if($==="localhost"||$.endsWith(".local")||$.endsWith(".localhost"))throw new N6({url:X,message:`URL with hostname ${$} is not allowed`});if($.startsWith("[")&&$.endsWith("]")){if(aq($.slice(1,-1)))throw new N6({url:X,message:`URL with IPv6 address ${$} is not allowed`});return}if(JG($)){if($G($))throw new N6({url:X,message:`URL with IP address ${$} is not allowed`})}}function nC({address:X,family:J,hostname:$}){if(J===4?!JG(X)||$G(X):J===6?aq(X):!0)throw new N6({url:$,message:`Hostname ${$} resolved to disallowed IP address ${X}`})}function JG(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 $G(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 sC(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||!JG(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 aq(X){let J=sC(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 $G(`${J[6]>>8&255}.${J[6]&255}.${J[7]>>8&255}.${J[7]&255}`);return!1}function aC(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)nC({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 oC;function rC(){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 tC(){if(!rC())return globalThis.fetch;return oC??=Promise.resolve().then(eC)}function eC(){let X=vq("node:module"),{lookup:J}=vq("node:dns"),{Agent:$,fetch:Y}=X.createRequire(oq())("undici"),G=new $({connect:{lookup:aC(J)}});return(Q,z)=>Y(Q,{...z,dispatcher:G})}function vq(X){let J=globalThis.process?.getBuiltinModule?.(X);if(J==null)throw Error(`Node.js built-in module ${X} is unavailable`);return J}function oq(){let X=Error.prepareStackTrace;try{Error.prepareStackTrace=(G,Q)=>Q;let J=Error("Capture current module path");Error.captureStackTrace(J,oq);let[$]=J.stack,Y=$?.getFileName();if(Y==null)throw Error("Unable to determine the current module path");return Y}finally{Error.prepareStackTrace=X}}var XE=["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 rq(X){let J=new Headers(X);for(let $ of XE)J.delete($);return J}var JE=10,$E=new Set([301,302,303,307,308]);async function YE(X){return X==null||X===globalThis.fetch?await tC():X}async function GE({url:X,headers:J,abortSignal:$,maxRedirects:Y=JE,fetch:G,trustedOrigin:Q}){let z=J===void 0?void 0:rq(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&&eY(W,Q);if(!H)iC(W);let U=H&&G!=null?G:H?globalThis.fetch:await YE(G),j=await U(W,Z("manual"));if(j.type==="opaqueredirect"){if(!dC())throw new N6({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($E.has(j.status)&&q){RX(j);let K=new URL(q,W).toString();if(z!==void 0&&!eY(K,W)){let N=z.get("user-agent");z=new Headers(N==null?void 0:{"user-agent":N})}W=K;continue}return j}throw new N6({url:X,message:`Too many redirects (max ${Y})`})}var QE=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 tq({headers:X,credentialedOrigin:J,untrustedFirstHopHeaders:$,...Y}){let G;if(X!==void 0){G=rq(X);let Q=J??Y.trustedOrigin;if(Q===void 0||!eY(Y.url,Q)){let z=new Set([...QE,...($??[]).map((Z)=>Z.toLowerCase())]);G=new Headers([...G].filter(([Z])=>z.has(Z)))}}return GE({...Y,headers:G})}var YG=2147483648;async function eq({response:X,url:J,maxBytes:$=YG}){let Y=X.headers.get("content-length");if(Y!=null){let H=parseInt(Y,10);if(!isNaN(H)&&H>$)throw await RX(X),new N6({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 N6({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 J6=({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 NY({argument:"separator",message:`The separator "${Y}" must not be part of the alphabet "${$}".`});return()=>`${X}${Y}${G()}`},XN=J6();function JN(X){return globalThis.Buffer?.isBuffer(X)??!1}function $N(X){if(X.type==="object"||Array.isArray(X.type)&&X.type.includes("object")){let{additionalProperties:$}=X;X.additionalProperties=$!=null&&typeof $!=="boolean"?f9($):!1;let{properties:Y}=X;if(Y!=null)for(let G of Object.keys(Y))Y[G]=f9(Y[G])}if(X.items!=null)X.items=Array.isArray(X.items)?X.items.map(f9):f9(X.items);if(X.anyOf!=null)X.anyOf=X.anyOf.map(f9);if(X.allOf!=null)X.allOf=X.allOf.map(f9);if(X.oneOf!=null)X.oneOf=X.oneOf.map(f9);let{definitions:J}=X;if(J!=null)for(let $ of Object.keys(J))J[$]=f9(J[$]);return X}function f9(X){if(typeof X==="boolean")return X;return $N(X)}var zE=Symbol("Let zodToJsonSchema decide on which parser to use"),yq={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"},ZE=(X)=>typeof X==="string"?{...yq,name:X}:{...yq,...X};function d6(){return{}}function WE(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 BE(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 HE(){return{type:"boolean"}}function YN(X,J){return A0(X.type._def,J)}var VE=(X,J)=>{return A0(X.innerType._def,J)};function GN(X,J,$){let Y=$??J.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((G)=>GN(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 UE(X)}}var UE=(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 KE(X,J){return{...A0(X.innerType._def,J),default:X.defaultValue()}}function jE(X,J){return J.effectStrategy==="input"?A0(X.schema._def,J):d6()}function qE(X){return{type:"string",enum:Array.from(X.values)}}var NE=(X)=>{if("type"in X&&X.type==="string")return!1;return"allOf"in X};function LE(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(NE(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 DE(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 rY=void 0,N8={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(rY===void 0)rY=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return rY},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 QN(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":L8($,"email",Y.message,J);break;case"format:idn-email":L8($,"idn-email",Y.message,J);break;case"pattern:zod":E6($,N8.email,Y.message,J)}break;case"url":L8($,"uri",Y.message,J);break;case"uuid":L8($,"uuid",Y.message,J);break;case"regex":E6($,Y.regex,Y.message,J);break;case"cuid":E6($,N8.cuid,Y.message,J);break;case"cuid2":E6($,N8.cuid2,Y.message,J);break;case"startsWith":E6($,RegExp(`^${tY(Y.value,J)}`),Y.message,J);break;case"endsWith":E6($,RegExp(`${tY(Y.value,J)}$`),Y.message,J);break;case"datetime":L8($,"date-time",Y.message,J);break;case"date":L8($,"date",Y.message,J);break;case"time":L8($,"time",Y.message,J);break;case"duration":L8($,"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":E6($,RegExp(tY(Y.value,J)),Y.message,J);break;case"ip":if(Y.version!=="v6")L8($,"ipv4",Y.message,J);if(Y.version!=="v4")L8($,"ipv6",Y.message,J);break;case"base64url":E6($,N8.base64url,Y.message,J);break;case"jwt":E6($,N8.jwt,Y.message,J);break;case"cidr":if(Y.version!=="v6")E6($,N8.ipv4Cidr,Y.message,J);if(Y.version!=="v4")E6($,N8.ipv6Cidr,Y.message,J);break;case"emoji":E6($,N8.emoji(),Y.message,J);break;case"ulid":E6($,N8.ulid,Y.message,J);break;case"base64":switch(J.base64Strategy){case"format:binary":L8($,"binary",Y.message,J);break;case"contentEncoding:base64":$.contentEncoding="base64";break;case"pattern:zod":E6($,N8.base64,Y.message,J)}break;case"nanoid":E6($,N8.nanoid,Y.message,J)}return $}function tY(X,J){return J.patternStrategy==="escape"?PE(X):X}var FE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function PE(X){let J="";for(let $=0;$<X.length;$++){if(!FE.has(X[$]))J+="\\";J+=X[$]}return J}function L8(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 E6(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:hq(J,Y),...$&&Y.errorMessages&&{errorMessage:{pattern:$}}})}else X.pattern=hq(J,Y)}function hq(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
+ 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,N={...j};if(U.ref===null)return;let K=U.ref;if(U.ref=null,K){z(K,H);let q=this.seen.get(K).schema;if(q.$ref&&(H.target==="draft-7"||H.target==="draft-4"||H.target==="openapi-3.0"))j.allOf=j.allOf??[],j.allOf.push(q);else Object.assign(j,q),Object.assign(j,N)}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 YN(X,J){if(X instanceof FX){let Y=new sY(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 sY(J);return $.process(X),$.emit(X,J)}function a0(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 a0(G.element,$);case"object":{for(let Q in G.shape)if(a0(G.shape[Q],$))return!0;return!1}case"union":{for(let Q of G.options)if(a0(Q,$))return!0;return!1}case"intersection":return a0(G.left,$)||a0(G.right,$);case"tuple":{for(let Q of G.items)if(a0(Q,$))return!0;if(G.rest&&a0(G.rest,$))return!0;return!1}case"record":return a0(G.keyType,$)||a0(G.valueType,$);case"map":return a0(G.keyType,$)||a0(G.valueType,$);case"set":return a0(G.valueType,$);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return a0(G.innerType,$);case"lazy":return a0(G.getter(),$);case"default":return a0(G.innerType,$);case"prefault":return a0(G.innerType,$);case"custom":return!1;case"transform":return!0;case"pipe":return a0(G.in,$)||a0(G.out,$);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${G.type}`)}var oR=E("ZodISODateTime",(X,J)=>{hK.init(X,J),y0.init(X,J)});function GN(X){return cj(oR,X)}var rR=E("ZodISODate",(X,J)=>{fK.init(X,J),y0.init(X,J)});function QN(X){return lj(rR,X)}var tR=E("ZodISOTime",(X,J)=>{gK.init(X,J),y0.init(X,J)});function zN(X){return dj(tR,X)}var eR=E("ZodISODuration",(X,J)=>{mK.init(X,J),y0.init(X,J)});function ZN(X){return ij(eR,X)}var WN=(X,J)=>{UX.init(X,J),X.name="ZodError",Object.defineProperties(X,{format:{value:($)=>LU(X,$)},flatten:{value:($)=>qU(X,$)},addIssue:{value:($)=>{X.issues.push($),X.message=JSON.stringify(X.issues,P4,2)}},addIssues:{value:($)=>{X.issues.push(...$),X.message=JSON.stringify(X.issues,P4,2)}},isEmpty:{get(){return X.issues.length===0}}})},nc=E("ZodError",WN),l6=E("ZodError",WN,{Parent:Error});var BN=KX(l6),HN=jX(l6),VN=p3(l6),RX=c3(l6),UN=PU(l6),KN=OU(l6),jN=MU(l6),NN=_U(l6),qN=AU(l6),LN=TU(l6),DN=RU(l6),FN=CU(l6);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)=>N8(X,$,Y),X.brand=()=>X,X.register=($,Y)=>{return $.add(X,Y),X},X.parse=($,Y)=>BN(X,$,Y,{callee:X.parse}),X.safeParse=($,Y)=>VN(X,$,Y),X.parseAsync=async($,Y)=>HN(X,$,Y,{callee:X.parseAsync}),X.safeParseAsync=async($,Y)=>RX(X,$,Y),X.spa=X.safeParseAsync,X.encode=($,Y)=>UN(X,$,Y),X.decode=($,Y)=>KN(X,$,Y),X.encodeAsync=async($,Y)=>jN(X,$,Y),X.decodeAsync=async($,Y)=>NN(X,$,Y),X.safeEncode=($,Y)=>qN(X,$,Y),X.safeDecode=($,Y)=>LN(X,$,Y),X.safeEncodeAsync=async($,Y)=>DN(X,$,Y),X.safeDecodeAsync=async($,Y)=>FN(X,$,Y),X.refine=($,Y)=>X.check(iC($,Y)),X.superRefine=($)=>X.check(nC($)),X.overwrite=($)=>X.check(T1($)),X.optional=()=>MN(X),X.nullable=()=>_N(X),X.nullish=()=>MN(_N(X)),X.nonoptional=($)=>gC(X,$),X.array=()=>rY(X),X.or=($)=>tY([X,$]),X.and=($)=>SC(X,$),X.transform=($)=>AN(X,xC($)),X.default=($)=>yC(X,$),X.prefault=($)=>fC(X,$),X.catch=($)=>uC(X,$),X.pipe=($)=>AN(X,$),X.readonly=()=>lC(X),X.describe=($)=>{let Y=X.clone();return A1.add(Y,{description:$}),Y},Object.defineProperty(X,"description",{get(){return A1.get(X)?.description},configurable:!0}),X.meta=(...$)=>{if($.length===0)return A1.get(X);let Y=X.clone();return A1.add(Y,$[0]),Y},X.isOptional=()=>X.safeParse(void 0).success,X.isNullable=()=>X.safeParse(null).success,X}),TN=E("_ZodString",(X,J)=>{DX.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(fY(...Y)),X.includes=(...Y)=>X.check(uY(...Y)),X.startsWith=(...Y)=>X.check(pY(...Y)),X.endsWith=(...Y)=>X.check(cY(...Y)),X.min=(...Y)=>X.check(_4(...Y)),X.max=(...Y)=>X.check(_X(...Y)),X.length=(...Y)=>X.check(AX(...Y)),X.nonempty=(...Y)=>X.check(_4(1,...Y)),X.lowercase=(Y)=>X.check(gY(Y)),X.uppercase=(Y)=>X.check(mY(Y)),X.trim=()=>X.check(dY()),X.normalize=(...Y)=>X.check(lY(...Y)),X.toLowerCase=()=>X.check(iY()),X.toUpperCase=()=>X.check(nY())}),YC=E("ZodString",(X,J)=>{DX.init(X,J),TN.init(X,J),X.email=($)=>X.check(Mj(GC,$)),X.url=($)=>X.check(Cj(QC,$)),X.jwt=($)=>X.check(pj(PC,$)),X.emoji=($)=>X.check(Ej(zC,$)),X.guid=($)=>X.check(hY(PN,$)),X.uuid=($)=>X.check(_j(CX,$)),X.uuidv4=($)=>X.check(Aj(CX,$)),X.uuidv6=($)=>X.check(Tj(CX,$)),X.uuidv7=($)=>X.check(Rj(CX,$)),X.nanoid=($)=>X.check(Sj(ZC,$)),X.guid=($)=>X.check(hY(PN,$)),X.cuid=($)=>X.check(Ij(WC,$)),X.cuid2=($)=>X.check(bj(BC,$)),X.ulid=($)=>X.check(kj(HC,$)),X.base64=($)=>X.check(gj(LC,$)),X.base64url=($)=>X.check(mj(DC,$)),X.xid=($)=>X.check(xj(VC,$)),X.ksuid=($)=>X.check(wj(UC,$)),X.ipv4=($)=>X.check(vj(KC,$)),X.ipv6=($)=>X.check(yj(jC,$)),X.cidrv4=($)=>X.check(hj(NC,$)),X.cidrv6=($)=>X.check(fj(qC,$)),X.e164=($)=>X.check(uj(FC,$)),X.datetime=($)=>X.check(GN($)),X.date=($)=>X.check(QN($)),X.time=($)=>X.check(zN($)),X.duration=($)=>X.check(ZN($))});function RN(X){return Oj(YC,X)}var y0=E("ZodStringFormat",(X,J)=>{k0.init(X,J),TN.init(X,J)}),GC=E("ZodEmail",(X,J)=>{EK.init(X,J),y0.init(X,J)});var PN=E("ZodGUID",(X,J)=>{RK.init(X,J),y0.init(X,J)});var CX=E("ZodUUID",(X,J)=>{CK.init(X,J),y0.init(X,J)});var QC=E("ZodURL",(X,J)=>{SK.init(X,J),y0.init(X,J)});var zC=E("ZodEmoji",(X,J)=>{IK.init(X,J),y0.init(X,J)});var ZC=E("ZodNanoID",(X,J)=>{bK.init(X,J),y0.init(X,J)});var WC=E("ZodCUID",(X,J)=>{kK.init(X,J),y0.init(X,J)});var BC=E("ZodCUID2",(X,J)=>{xK.init(X,J),y0.init(X,J)});var HC=E("ZodULID",(X,J)=>{wK.init(X,J),y0.init(X,J)});var VC=E("ZodXID",(X,J)=>{vK.init(X,J),y0.init(X,J)});var UC=E("ZodKSUID",(X,J)=>{yK.init(X,J),y0.init(X,J)});var KC=E("ZodIPv4",(X,J)=>{uK.init(X,J),y0.init(X,J)});var jC=E("ZodIPv6",(X,J)=>{pK.init(X,J),y0.init(X,J)});var NC=E("ZodCIDRv4",(X,J)=>{cK.init(X,J),y0.init(X,J)});var qC=E("ZodCIDRv6",(X,J)=>{lK.init(X,J),y0.init(X,J)});var LC=E("ZodBase64",(X,J)=>{iK.init(X,J),y0.init(X,J)});var DC=E("ZodBase64URL",(X,J)=>{nK.init(X,J),y0.init(X,J)});var FC=E("ZodE164",(X,J)=>{sK.init(X,J),y0.init(X,J)});var PC=E("ZodJWT",(X,J)=>{aK.init(X,J),y0.init(X,J)});var CN=E("ZodNumber",(X,J)=>{vY.init(X,J),h0.init(X,J),X.gt=(Y,G)=>X.check(OX(Y,G)),X.gte=(Y,G)=>X.check(i3(Y,G)),X.min=(Y,G)=>X.check(i3(Y,G)),X.lt=(Y,G)=>X.check(PX(Y,G)),X.lte=(Y,G)=>X.check(d3(Y,G)),X.max=(Y,G)=>X.check(d3(Y,G)),X.int=(Y)=>X.check(ON(Y)),X.safe=(Y)=>X.check(ON(Y)),X.positive=(Y)=>X.check(OX(0,Y)),X.nonnegative=(Y)=>X.check(i3(0,Y)),X.negative=(Y)=>X.check(PX(0,Y)),X.nonpositive=(Y)=>X.check(d3(0,Y)),X.multipleOf=(Y,G)=>X.check(MX(Y,G)),X.step=(Y,G)=>X.check(MX(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 EN(X){return nj(CN,X)}var OC=E("ZodNumberFormat",(X,J)=>{oK.init(X,J),CN.init(X,J)});function ON(X){return sj(OC,X)}var MC=E("ZodBoolean",(X,J)=>{rK.init(X,J),h0.init(X,J)});function SN(X){return aj(MC,X)}var _C=E("ZodNull",(X,J)=>{tK.init(X,J),h0.init(X,J)});function IN(X){return oj(_C,X)}var AC=E("ZodUnknown",(X,J)=>{eK.init(X,J),h0.init(X,J)});function n3(){return rj(AC)}var TC=E("ZodNever",(X,J)=>{Xj.init(X,J),h0.init(X,J)});function oY(X){return tj(TC,X)}var RC=E("ZodArray",(X,J)=>{Jj.init(X,J),h0.init(X,J),X.element=J.element,X.min=($,Y)=>X.check(_4($,Y)),X.nonempty=($)=>X.check(_4(1,$)),X.max=($,Y)=>X.check(_X($,Y)),X.length=($,Y)=>X.check(AX($,Y)),X.unwrap=()=>X.element});function rY(X,J){return ej(RC,X,J)}var bN=E("ZodObject",(X,J)=>{Gj.init(X,J),h0.init(X,J),j0.defineLazy(X,"shape",()=>J.shape),X.keyof=()=>eY(Object.keys(X._zod.def.shape)),X.catchall=($)=>X.clone({...X._zod.def,catchall:$}),X.passthrough=()=>X.clone({...X._zod.def,catchall:n3()}),X.loose=()=>X.clone({...X._zod.def,catchall:n3()}),X.strict=()=>X.clone({...X._zod.def,catchall:oY()}),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(fN,X,$[0]),X.required=(...$)=>j0.required(gN,X,$[0])});function kN(X,J){let $={type:"object",get shape(){return j0.assignProp(this,"shape",X?j0.objectClone(X):{}),this.shape},...j0.normalizeParams(J)};return new bN($)}function xN(X,J){return new bN({type:"object",get shape(){return j0.assignProp(this,"shape",j0.objectClone(X)),this.shape},catchall:n3(),...j0.normalizeParams(J)})}var wN=E("ZodUnion",(X,J)=>{yY.init(X,J),h0.init(X,J),X.options=J.options});function tY(X,J){return new wN({type:"union",options:X,...j0.normalizeParams(J)})}var CC=E("ZodDiscriminatedUnion",(X,J)=>{wN.init(X,J),Qj.init(X,J)});function vN(X,J,$){return new CC({type:"union",options:J,discriminator:X,...j0.normalizeParams($)})}var EC=E("ZodIntersection",(X,J)=>{zj.init(X,J),h0.init(X,J)});function SC(X,J){return new EC({type:"intersection",left:X,right:J})}var IC=E("ZodRecord",(X,J)=>{Zj.init(X,J),h0.init(X,J),X.keyType=J.keyType,X.valueType=J.valueType});function yN(X,J,$){return new IC({type:"record",keyType:X,valueType:J,...j0.normalizeParams($)})}var aY=E("ZodEnum",(X,J)=>{Wj.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 aY({...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 aY({...J,checks:[],...j0.normalizeParams(G),entries:Q})}});function eY(X,J){let $=Array.isArray(X)?Object.fromEntries(X.map((Y)=>[Y,Y])):X;return new aY({type:"enum",entries:$,...j0.normalizeParams(J)})}var bC=E("ZodLiteral",(X,J)=>{Bj.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 hN(X,J){return new bC({type:"literal",values:Array.isArray(X)?X:[X],...j0.normalizeParams(J)})}var kC=E("ZodTransform",(X,J)=>{Hj.init(X,J),h0.init(X,J),X._zod.parse=($,Y)=>{if(Y.direction==="backward")throw new y3(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 xC(X){return new kC({type:"transform",transform:X})}var fN=E("ZodOptional",(X,J)=>{Vj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function MN(X){return new fN({type:"optional",innerType:X})}var wC=E("ZodNullable",(X,J)=>{Uj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function _N(X){return new wC({type:"nullable",innerType:X})}var vC=E("ZodDefault",(X,J)=>{Kj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType,X.removeDefault=X.unwrap});function yC(X,J){return new vC({type:"default",innerType:X,get defaultValue(){return typeof J==="function"?J():j0.shallowClone(J)}})}var hC=E("ZodPrefault",(X,J)=>{jj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function fC(X,J){return new hC({type:"prefault",innerType:X,get defaultValue(){return typeof J==="function"?J():j0.shallowClone(J)}})}var gN=E("ZodNonOptional",(X,J)=>{Nj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function gC(X,J){return new gN({type:"nonoptional",innerType:X,...j0.normalizeParams(J)})}var mC=E("ZodCatch",(X,J)=>{qj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType,X.removeCatch=X.unwrap});function uC(X,J){return new mC({type:"catch",innerType:X,catchValue:typeof J==="function"?J:()=>J})}var pC=E("ZodPipe",(X,J)=>{Lj.init(X,J),h0.init(X,J),X.in=J.in,X.out=J.out});function AN(X,J){return new pC({type:"pipe",in:X,out:J})}var cC=E("ZodReadonly",(X,J)=>{Dj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.innerType});function lC(X){return new cC({type:"readonly",innerType:X})}var dC=E("ZodLazy",(X,J)=>{Fj.init(X,J),h0.init(X,J),X.unwrap=()=>X._zod.def.getter()});function mN(X){return new dC({type:"lazy",getter:X})}var XG=E("ZodCustom",(X,J)=>{Pj.init(X,J),h0.init(X,J)});function uN(X,J){return XN(XG,X??(()=>!0),J)}function iC(X,J={}){return JN(XG,X,J)}function nC(X){return $N(X)}function pN(X,J={error:`Input not instance of ${X.name}`}){let $=new XG({type:"custom",check:"custom",fn:(Y)=>Y instanceof X,abort:!0,...j0.normalizeParams(J)});return $._zod.bag.Class=X,$}function tN(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 eN(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 Xq(X,...J){let $=new Headers(eN(X)),Y=$.get("user-agent")||"";return $.set("user-agent",[Y,...J].filter(Boolean).join(" ")),Object.fromEntries($.entries())}var rC=[{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]}],fl=[...rC,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];async function EX(X){try{await X.body?.cancel()}catch{}}var Jq="AI_DownloadError",$q=`vercel.ai.error.${Jq}`,tC=Symbol.for($q),q6=class extends H9{constructor({url:X,statusCode:J,statusText:$,cause:Y,message:G=Y==null?`Failed to download ${X}: ${J} ${$}`:`Failed to download ${X}: ${Y}`}){super({name:Jq,message:G,cause:Y});this[tC]=!0,this.url=X,this.statusCode=J,this.statusText=$}static isInstance(X){return H9.hasMarker(X,$q)}};function eC(X=globalThis){return X.window!=null}function YG(X,J){try{return new URL(X).origin===new URL(J).origin}catch{return!1}}function XE(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(Yq($.slice(1,-1)))throw new q6({url:X,message:`URL with IPv6 address ${$} is not allowed`});return}if(QG($)){if(zG($))throw new q6({url:X,message:`URL with IP address ${$} is not allowed`})}}function JE({address:X,family:J,hostname:$}){if(J===4?!QG(X)||zG(X):J===6?Yq(X):!0)throw new q6({url:$,message:`Hostname ${$} resolved to disallowed IP address ${X}`})}function QG(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 zG(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 $E(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||!QG(H))return null;let[U,j,N,K]=H.split(".").map(Number);Z.push(U<<8|j,N<<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 Yq(X){let J=$E(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 zG(`${J[6]>>8&255}.${J[6]&255}.${J[7]>>8&255}.${J[7]&255}`);return!1}function YE(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)JE({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 GE;function QE(){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 zE(){if(!QE())return globalThis.fetch;return GE??=Promise.resolve().then(ZE)}function ZE(){let X=cN("node:module"),{lookup:J}=cN("node:dns"),{Agent:$,fetch:Y}=X.createRequire(Gq())("undici"),G=new $({connect:{lookup:YE(J)}});return(Q,z)=>Y(Q,{...z,dispatcher:G})}function cN(X){let J=globalThis.process?.getBuiltinModule?.(X);if(J==null)throw Error(`Node.js built-in module ${X} is unavailable`);return J}function Gq(){let X=Error.prepareStackTrace;try{Error.prepareStackTrace=(G,Q)=>Q;let J=Error("Capture current module path");Error.captureStackTrace(J,Gq);let[$]=J.stack,Y=$?.getFileName();if(Y==null)throw Error("Unable to determine the current module path");return Y}finally{Error.prepareStackTrace=X}}var WE=["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 Qq(X){let J=new Headers(X);for(let $ of WE)J.delete($);return J}var BE=10,HE=new Set([301,302,303,307,308]);async function VE(X){return X==null||X===globalThis.fetch?await zE():X}async function UE({url:X,headers:J,abortSignal:$,maxRedirects:Y=BE,fetch:G,trustedOrigin:Q}){let z=J===void 0?void 0:Qq(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&&YG(W,Q);if(!H)XE(W);let U=H&&G!=null?G:H?globalThis.fetch:await VE(G),j=await U(W,Z("manual"));if(j.type==="opaqueredirect"){if(!eC())throw new q6({url:X,message:`Redirect from ${W} could not be validated and was blocked`});return await U(W,Z("follow"))}let N=j.headers?.get("location");if(HE.has(j.status)&&N){EX(j);let K=new URL(N,W).toString();if(z!==void 0&&!YG(K,W)){let q=z.get("user-agent");z=new Headers(q==null?void 0:{"user-agent":q})}W=K;continue}return j}throw new q6({url:X,message:`Too many redirects (max ${Y})`})}var KE=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 zq({headers:X,credentialedOrigin:J,untrustedFirstHopHeaders:$,...Y}){let G;if(X!==void 0){G=Qq(X);let Q=J??Y.trustedOrigin;if(Q===void 0||!YG(Y.url,Q)){let z=new Set([...KE,...($??[]).map((Z)=>Z.toLowerCase())]);G=new Headers([...G].filter(([Z])=>z.has(Z)))}}return UE({...Y,headers:G})}var ZG=2147483648;async function Zq({response:X,url:J,maxBytes:$=ZG}){let Y=X.headers.get("content-length");if(Y!=null){let H=parseInt(Y,10);if(!isNaN(H)&&H>$)throw await EX(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 J6=({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 PY({argument:"separator",message:`The separator "${Y}" must not be part of the alphabet "${$}".`});return()=>`${X}${Y}${G()}`},Wq=J6();function Bq(X){return globalThis.Buffer?.isBuffer(X)??!1}function Hq(X){if(X.type==="object"||Array.isArray(X.type)&&X.type.includes("object")){let{additionalProperties:$}=X;X.additionalProperties=$!=null&&typeof $!=="boolean"?g9($):!1;let{properties:Y}=X;if(Y!=null)for(let G of Object.keys(Y))Y[G]=g9(Y[G])}if(X.items!=null)X.items=Array.isArray(X.items)?X.items.map(g9):g9(X.items);if(X.anyOf!=null)X.anyOf=X.anyOf.map(g9);if(X.allOf!=null)X.allOf=X.allOf.map(g9);if(X.oneOf!=null)X.oneOf=X.oneOf.map(g9);let{definitions:J}=X;if(J!=null)for(let $ of Object.keys(J))J[$]=g9(J[$]);return X}function g9(X){if(typeof X==="boolean")return X;return Hq(X)}var jE=Symbol("Let zodToJsonSchema decide on which parser to use"),lN={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"},NE=(X)=>typeof X==="string"?{...lN,name:X}:{...lN,...X};function d6(){return{}}function qE(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 LE(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 DE(){return{type:"boolean"}}function Vq(X,J){return A0(X.type._def,J)}var FE=(X,J)=>{return A0(X.innerType._def,J)};function Uq(X,J,$){let Y=$??J.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((G)=>Uq(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 PE(X)}}var PE=(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 OE(X,J){return{...A0(X.innerType._def,J),default:X.defaultValue()}}function ME(X,J){return J.effectStrategy==="input"?A0(X.schema._def,J):d6()}function _E(X){return{type:"string",enum:Array.from(X.values)}}var AE=(X)=>{if("type"in X&&X.type==="string")return!1;return"allOf"in X};function TE(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(AE(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 RE(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 JG=void 0,L8={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(JG===void 0)JG=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return JG},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 Kq(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":D8($,"email",Y.message,J);break;case"format:idn-email":D8($,"idn-email",Y.message,J);break;case"pattern:zod":S6($,L8.email,Y.message,J)}break;case"url":D8($,"uri",Y.message,J);break;case"uuid":D8($,"uuid",Y.message,J);break;case"regex":S6($,Y.regex,Y.message,J);break;case"cuid":S6($,L8.cuid,Y.message,J);break;case"cuid2":S6($,L8.cuid2,Y.message,J);break;case"startsWith":S6($,RegExp(`^${$G(Y.value,J)}`),Y.message,J);break;case"endsWith":S6($,RegExp(`${$G(Y.value,J)}$`),Y.message,J);break;case"datetime":D8($,"date-time",Y.message,J);break;case"date":D8($,"date",Y.message,J);break;case"time":D8($,"time",Y.message,J);break;case"duration":D8($,"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":S6($,RegExp($G(Y.value,J)),Y.message,J);break;case"ip":if(Y.version!=="v6")D8($,"ipv4",Y.message,J);if(Y.version!=="v4")D8($,"ipv6",Y.message,J);break;case"base64url":S6($,L8.base64url,Y.message,J);break;case"jwt":S6($,L8.jwt,Y.message,J);break;case"cidr":if(Y.version!=="v6")S6($,L8.ipv4Cidr,Y.message,J);if(Y.version!=="v4")S6($,L8.ipv6Cidr,Y.message,J);break;case"emoji":S6($,L8.emoji(),Y.message,J);break;case"ulid":S6($,L8.ulid,Y.message,J);break;case"base64":switch(J.base64Strategy){case"format:binary":D8($,"binary",Y.message,J);break;case"contentEncoding:base64":$.contentEncoding="base64";break;case"pattern:zod":S6($,L8.base64,Y.message,J)}break;case"nanoid":S6($,L8.nanoid,Y.message,J)}return $}function $G(X,J){return J.patternStrategy==="escape"?EE(X):X}var CE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function EE(X){let J="";for(let $=0;$<X.length;$++){if(!CE.has(X[$]))J+="\\";J+=X[$]}return J}function D8(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 S6(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:dN(J,Y),...$&&Y.errorMessages&&{errorMessage:{pattern:$}}})}else X.pattern=dN(J,Y)}function dN(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
189
189
  ]))`;continue}else if(Y[W]==="$"){G+=`($|(?=[\r
190
190
  ]))`;continue}}if($.s&&Y[W]==="."){G+=z?`${Y[W]}\r
191
191
  `:`[${Y[W]}\r
192
- ]`;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 zN(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}=QN(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}=YN(X.keyType._def,J);return{...$,propertyNames:G}}return $}function OE(X,J){if(J.mapStrategy==="record")return zN(X,J);return{type:"array",maxItems:125,items:{type:"array",items:[A0(X.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||d6(),A0(X.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||d6()],minItems:2,maxItems:2}}}function ME(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 _E(){return{not:d6()}}function AE(){return{type:"null"}}var XG={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function TE(X,J){let $=X.options instanceof Map?Array.from(X.options.values()):X.options;if($.every((Y)=>(Y._def.typeName in XG)&&(!Y._def.checks||!Y._def.checks.length))){let Y=$.reduce((G,Q)=>{let z=XG[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 RE(X,J)}var RE=(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 CE(X,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(X.innerType._def.typeName)&&(!X.innerType._def.checks||!X.innerType._def.checks.length))return{type:[XG[X.innerType._def.typeName],"null"]};let $=A0(X.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function EE(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 SE(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=bE(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=IE(X,J);if(Q!==void 0)$.additionalProperties=Q;return $}function IE(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 bE(X){try{return X.isOptional()}catch{return!0}}var kE=(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:d6()},$]}:d6()},xE=(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 vE(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 yE(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 hE(){return{not:d6()}}function fE(){return d6()}var gE=(X,J)=>{return A0(X.innerType._def,J)},mE=(X,J,$)=>{switch(J){case"ZodString":return QN(X,$);case"ZodNumber":return EE(X);case"ZodObject":return SE(X,$);case"ZodBigInt":return BE(X);case"ZodBoolean":return HE();case"ZodDate":return GN(X,$);case"ZodUndefined":return hE();case"ZodNull":return AE();case"ZodArray":return WE(X,$);case"ZodUnion":case"ZodDiscriminatedUnion":return TE(X,$);case"ZodIntersection":return LE(X,$);case"ZodTuple":return yE(X,$);case"ZodRecord":return zN(X,$);case"ZodLiteral":return DE(X);case"ZodEnum":return qE(X);case"ZodNativeEnum":return ME(X);case"ZodNullable":return CE(X,$);case"ZodOptional":return kE(X,$);case"ZodMap":return OE(X,$);case"ZodSet":return vE(X,$);case"ZodLazy":return()=>X.getter()._def;case"ZodPromise":return wE(X,$);case"ZodNaN":case"ZodNever":return _E();case"ZodEffects":return jE(X,$);case"ZodAny":return d6();case"ZodUnknown":return fE();case"ZodDefault":return KE(X,$);case"ZodBranded":return YN(X,$);case"ZodReadonly":return gE(X,$);case"ZodCatch":return VE(X,$);case"ZodPipeline":return xE(X,$);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Y)=>{return})(J)}},uE=(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!==zE)return Z}if(Y&&!$){let Z=pE(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=mE(X,X.typeName,J),z=typeof Q==="function"?A0(Q(),J):Q;if(z)cE(X,J,z);if(J.postProcess){let Z=J.postProcess(z,X,J);return G.jsonSchema=z,Z}return G.jsonSchema=z,z}var pE=(X,J)=>{switch(J.$refStrategy){case"root":return{$ref:X.path.join("/")};case"relative":return{$ref:uE(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`),d6();return J.$refStrategy==="seen"?d6():void 0}},cE=(X,J,$)=>{if(X.description)$.description=X.description;return $},lE=(X)=>{let J=ZE(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}]))}},dE=(X,J)=>{let $=lE(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)??d6()}),{}):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)??d6(),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},iE=Symbol.for("vercel.ai.schema");function GG(X){let J;return()=>{if(J==null)J=X();return J}}function CX(X,{validate:J}={}){return{[iE]:!0,_type:void 0,get jsonSchema(){if(typeof X==="function")X=X();return X},validate:J}}function nE(X,J){let $=J?.useReferences??!1;return CX(()=>dE(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 sE(X,J){let $=J?.useReferences??!1;return CX(()=>$N(aj(X,{target:"draft-7",io:"input",reused:$?"ref":"inline"})),{validate:async(Y)=>{let G=await AX(X,Y);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function aE(X){return"_zod"in X}function EX(X,J){if(aE(X))return sE(X,J);else return nE(X,J)}var oE="AI_SerializationError",Ml=`vercel.ai.error.${oE}`;var YS="AI_InvalidArgumentError",Yd=`vercel.ai.error.${YS}`;var GS="AI_InvalidStreamPartError",Gd=`vercel.ai.error.${GS}`;var QS="AI_InvalidToolApprovalError",Qd=`vercel.ai.error.${QS}`;var zS="AI_InvalidToolApprovalSignatureError",zd=`vercel.ai.error.${zS}`;var ZS="AI_InvalidToolInputError",Zd=`vercel.ai.error.${ZS}`;var WS="AI_ToolCallNotFoundForApprovalError",Wd=`vercel.ai.error.${WS}`;var BS="AI_MissingToolResultsError",Bd=`vercel.ai.error.${BS}`;var HS="AI_NoImageGeneratedError",Hd=`vercel.ai.error.${HS}`;var VS="AI_NoObjectGeneratedError",Vd=`vercel.ai.error.${VS}`;var US="AI_NoOutputGeneratedError",Ud=`vercel.ai.error.${US}`;var KS="AI_NoSpeechGeneratedError",Kd=`vercel.ai.error.${KS}`;var jS="AI_NoTranscriptGeneratedError",jd=`vercel.ai.error.${jS}`;var qS="AI_NoTranslationGeneratedError",qd=`vercel.ai.error.${qS}`;var NS="AI_NoVideoGeneratedError",Nd=`vercel.ai.error.${NS}`;var LS="AI_NoSuchToolError",Ld=`vercel.ai.error.${LS}`;var DS="AI_StreamProviderError",Dd=`vercel.ai.error.${DS}`;var FS="AI_ToolCallRepairError",Fd=`vercel.ai.error.${FS}`;var PS="AI_ToolChoiceViolationError",Pd=`vercel.ai.error.${PS}`;var OS="AI_UIMessageStreamError",Od=`vercel.ai.error.${OS}`;var MS="AI_InvalidDataContentError",Md=`vercel.ai.error.${MS}`;var _S="AI_InvalidMessageRoleError",_d=`vercel.ai.error.${_S}`;var AS="AI_MessageConversionError",Ad=`vercel.ai.error.${AS}`;var TS="AI_RetryError",Td=`vercel.ai.error.${TS}`;var RS="7.0.127",CS=async({url:X,maxBytes:J,abortSignal:$})=>{let Y=X.toString();try{let G=iq({},`ai-sdk/${RS}`,lq()),Q=await tq({url:Y,headers:G,abortSignal:$});if(!Q.ok)throw await RX(Q),new N6({url:Y,statusCode:Q.status,statusText:Q.statusText});return{data:await eq({response:Q,url:Y,maxBytes:J??YG}),mediaType:Q.headers.get("content-type")??void 0}}catch(G){if(N6.isInstance(G))throw G;throw new N6({url:Y,cause:G})}};var V={array:nY,boolean:Oq,custom:xq,discriminatedUnion:Cq,enum:aY,instanceof:wq,lazy:kq,literal:Sq,looseObject:Tq,never:iY,null:Mq,number:Pq,object:Aq,record:Eq,string:Dq,union:sY,unknown:d3},R1=V.lazy(()=>V.union([V.null(),V.string(),V.number(),V.boolean(),V.record(V.string(),R1.optional()),V.array(R1)])),g=V.record(V.string(),V.record(V.string(),R1.optional())),n3=V.union([V.string(),V.instanceof(Uint8Array),V.instanceof(ArrayBuffer),V.custom(JN,{message:"Must be a Buffer"})]),QG=V.record(V.string(),V.string()),ZN=V.object({type:V.literal("text"),text:V.string(),providerOptions:g.optional()}),ES=V.object({type:V.literal("image"),image:V.union([n3,V.instanceof(URL),QG]),mediaType:V.string().optional(),providerOptions:g.optional()}),WN=V.discriminatedUnion("type",[V.object({type:V.literal("data"),data:n3}),V.object({type:V.literal("url"),url:V.instanceof(URL)}),V.object({type:V.literal("reference"),reference:QG}),V.object({type:V.literal("text"),text:V.string()})]),SS=V.discriminatedUnion("type",[V.object({type:V.literal("data"),data:n3}),V.object({type:V.literal("url"),url:V.instanceof(URL)})]),BN=V.object({type:V.literal("file"),data:V.union([WN,n3,V.instanceof(URL),QG]),filename:V.string().optional(),mediaType:V.string(),providerOptions:g.optional()}),IS=V.object({type:V.literal("reasoning"),text:V.string(),providerOptions:g.optional()}),bS=V.object({type:V.literal("custom"),kind:V.string().transform((X)=>X),providerOptions:g.optional()}),kS=V.object({type:V.literal("reasoning-file"),data:V.union([SS,n3,V.instanceof(URL)]),mediaType:V.string(),providerOptions:g.optional()}),xS=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:R1,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:R1,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:WN,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()})]))})]),HN=V.object({type:V.literal("tool-result"),toolCallId:V.string(),toolName:V.string(),output:wS,providerOptions:g.optional()}),vS=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()}),yS=V.object({type:V.literal("tool-approval-response"),approvalId:V.string(),approved:V.boolean(),reason:V.string().optional()}),hS=V.object({role:V.literal("system"),content:V.string(),providerOptions:g.optional()}),fS=V.object({role:V.literal("user"),content:V.union([V.string(),V.array(V.union([ZN,ES,BN]))]),providerOptions:g.optional()}),gS=V.object({role:V.literal("assistant"),content:V.union([V.string(),V.array(V.union([ZN,bS,BN,IS,kS,xS,HN,vS]))]),providerOptions:g.optional()}),mS=V.object({role:V.literal("tool"),content:V.array(V.union([HN,yS])),providerOptions:g.optional()}),Rd=V.union([hS,fS,gS,mS]);var Cd=Symbol("ai-sdk-tool-call-input-schema-input");var Ed=J6({prefix:"aitxt",size:24}),Sd=J6({prefix:"call",size:24});var Id=class extends TransformStream{constructor(){super({transform(X,J){J.enqueue(`data: ${JSON.stringify(X)}
192
+ ]`;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 jq(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}=Kq(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}=Vq(X.keyType._def,J);return{...$,propertyNames:G}}return $}function SE(X,J){if(J.mapStrategy==="record")return jq(X,J);return{type:"array",maxItems:125,items:{type:"array",items:[A0(X.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||d6(),A0(X.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||d6()],minItems:2,maxItems:2}}}function IE(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 bE(){return{not:d6()}}function kE(){return{type:"null"}}var GG={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function xE(X,J){let $=X.options instanceof Map?Array.from(X.options.values()):X.options;if($.every((Y)=>(Y._def.typeName in GG)&&(!Y._def.checks||!Y._def.checks.length))){let Y=$.reduce((G,Q)=>{let z=GG[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 wE(X,J)}var wE=(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 vE(X,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(X.innerType._def.typeName)&&(!X.innerType._def.checks||!X.innerType._def.checks.length))return{type:[GG[X.innerType._def.typeName],"null"]};let $=A0(X.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function yE(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 hE(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=gE(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=fE(X,J);if(Q!==void 0)$.additionalProperties=Q;return $}function fE(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 gE(X){try{return X.isOptional()}catch{return!0}}var mE=(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:d6()},$]}:d6()},uE=(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 pE(X,J){return A0(X.type._def,J)}function cE(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 lE(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 dE(){return{not:d6()}}function iE(){return d6()}var nE=(X,J)=>{return A0(X.innerType._def,J)},sE=(X,J,$)=>{switch(J){case"ZodString":return Kq(X,$);case"ZodNumber":return yE(X);case"ZodObject":return hE(X,$);case"ZodBigInt":return LE(X);case"ZodBoolean":return DE();case"ZodDate":return Uq(X,$);case"ZodUndefined":return dE();case"ZodNull":return kE();case"ZodArray":return qE(X,$);case"ZodUnion":case"ZodDiscriminatedUnion":return xE(X,$);case"ZodIntersection":return TE(X,$);case"ZodTuple":return lE(X,$);case"ZodRecord":return jq(X,$);case"ZodLiteral":return RE(X);case"ZodEnum":return _E(X);case"ZodNativeEnum":return IE(X);case"ZodNullable":return vE(X,$);case"ZodOptional":return mE(X,$);case"ZodMap":return SE(X,$);case"ZodSet":return cE(X,$);case"ZodLazy":return()=>X.getter()._def;case"ZodPromise":return pE(X,$);case"ZodNaN":case"ZodNever":return bE();case"ZodEffects":return ME(X,$);case"ZodAny":return d6();case"ZodUnknown":return iE();case"ZodDefault":return OE(X,$);case"ZodBranded":return Vq(X,$);case"ZodReadonly":return nE(X,$);case"ZodCatch":return FE(X,$);case"ZodPipeline":return uE(X,$);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Y)=>{return})(J)}},aE=(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!==jE)return Z}if(Y&&!$){let Z=oE(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=sE(X,X.typeName,J),z=typeof Q==="function"?A0(Q(),J):Q;if(z)rE(X,J,z);if(J.postProcess){let Z=J.postProcess(z,X,J);return G.jsonSchema=z,Z}return G.jsonSchema=z,z}var oE=(X,J)=>{switch(J.$refStrategy){case"root":return{$ref:X.path.join("/")};case"relative":return{$ref:aE(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`),d6();return J.$refStrategy==="seen"?d6():void 0}},rE=(X,J,$)=>{if(X.description)$.description=X.description;return $},tE=(X)=>{let J=NE(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}]))}},eE=(X,J)=>{let $=tE(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)??d6()}),{}):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)??d6(),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},XS=Symbol.for("vercel.ai.schema");function WG(X){let J;return()=>{if(J==null)J=X();return J}}function SX(X,{validate:J}={}){return{[XS]:!0,_type:void 0,get jsonSchema(){if(typeof X==="function")X=X();return X},validate:J}}function JS(X,J){let $=J?.useReferences??!1;return SX(()=>eE(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 $S(X,J){let $=J?.useReferences??!1;return SX(()=>Hq(YN(X,{target:"draft-7",io:"input",reused:$?"ref":"inline"})),{validate:async(Y)=>{let G=await RX(X,Y);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function YS(X){return"_zod"in X}function IX(X,J){if(YS(X))return $S(X,J);else return JS(X,J)}var GS="AI_SerializationError",gl=`vercel.ai.error.${GS}`;var VS="AI_InvalidArgumentError",Pd=`vercel.ai.error.${VS}`;var US="AI_InvalidStreamPartError",Od=`vercel.ai.error.${US}`;var KS="AI_InvalidToolApprovalError",Md=`vercel.ai.error.${KS}`;var jS="AI_InvalidToolApprovalSignatureError",_d=`vercel.ai.error.${jS}`;var NS="AI_InvalidToolInputError",Ad=`vercel.ai.error.${NS}`;var qS="AI_ToolCallNotFoundForApprovalError",Td=`vercel.ai.error.${qS}`;var LS="AI_MissingToolResultsError",Rd=`vercel.ai.error.${LS}`;var DS="AI_NoImageGeneratedError",Cd=`vercel.ai.error.${DS}`;var FS="AI_NoObjectGeneratedError",Ed=`vercel.ai.error.${FS}`;var PS="AI_NoOutputGeneratedError",Sd=`vercel.ai.error.${PS}`;var OS="AI_NoSpeechGeneratedError",Id=`vercel.ai.error.${OS}`;var MS="AI_NoTranscriptGeneratedError",bd=`vercel.ai.error.${MS}`;var _S="AI_NoTranslationGeneratedError",kd=`vercel.ai.error.${_S}`;var AS="AI_NoVideoGeneratedError",xd=`vercel.ai.error.${AS}`;var TS="AI_NoSuchToolError",wd=`vercel.ai.error.${TS}`;var RS="AI_StreamProviderError",vd=`vercel.ai.error.${RS}`;var CS="AI_ToolCallRepairError",yd=`vercel.ai.error.${CS}`;var ES="AI_ToolChoiceViolationError",hd=`vercel.ai.error.${ES}`;var SS="AI_UIMessageStreamError",fd=`vercel.ai.error.${SS}`;var IS="AI_InvalidDataContentError",gd=`vercel.ai.error.${IS}`;var bS="AI_InvalidMessageRoleError",md=`vercel.ai.error.${bS}`;var kS="AI_MessageConversionError",ud=`vercel.ai.error.${kS}`;var xS="AI_RetryError",pd=`vercel.ai.error.${xS}`;var wS="7.0.127",vS=async({url:X,maxBytes:J,abortSignal:$})=>{let Y=X.toString();try{let G=Xq({},`ai-sdk/${wS}`,tN()),Q=await zq({url:Y,headers:G,abortSignal:$});if(!Q.ok)throw await EX(Q),new q6({url:Y,statusCode:Q.status,statusText:Q.statusText});return{data:await Zq({response:Q,url:Y,maxBytes:J??ZG}),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:rY,boolean:SN,custom:uN,discriminatedUnion:vN,enum:eY,instanceof:pN,lazy:mN,literal:hN,looseObject:xN,never:oY,null:IN,number:EN,object:kN,record:yN,string:RN,union:tY,unknown:n3},R1=V.lazy(()=>V.union([V.null(),V.string(),V.number(),V.boolean(),V.record(V.string(),R1.optional()),V.array(R1)])),g=V.record(V.string(),V.record(V.string(),R1.optional())),a3=V.union([V.string(),V.instanceof(Uint8Array),V.instanceof(ArrayBuffer),V.custom(Bq,{message:"Must be a Buffer"})]),BG=V.record(V.string(),V.string()),Nq=V.object({type:V.literal("text"),text:V.string(),providerOptions:g.optional()}),yS=V.object({type:V.literal("image"),image:V.union([a3,V.instanceof(URL),BG]),mediaType:V.string().optional(),providerOptions:g.optional()}),qq=V.discriminatedUnion("type",[V.object({type:V.literal("data"),data:a3}),V.object({type:V.literal("url"),url:V.instanceof(URL)}),V.object({type:V.literal("reference"),reference:BG}),V.object({type:V.literal("text"),text:V.string()})]),hS=V.discriminatedUnion("type",[V.object({type:V.literal("data"),data:a3}),V.object({type:V.literal("url"),url:V.instanceof(URL)})]),Lq=V.object({type:V.literal("file"),data:V.union([qq,a3,V.instanceof(URL),BG]),filename:V.string().optional(),mediaType:V.string(),providerOptions:g.optional()}),fS=V.object({type:V.literal("reasoning"),text:V.string(),providerOptions:g.optional()}),gS=V.object({type:V.literal("custom"),kind:V.string().transform((X)=>X),providerOptions:g.optional()}),mS=V.object({type:V.literal("reasoning-file"),data:V.union([hS,a3,V.instanceof(URL)]),mediaType:V.string(),providerOptions:g.optional()}),uS=V.object({type:V.literal("tool-call"),toolCallId:V.string(),toolName:V.string(),input:V.unknown(),providerOptions:g.optional(),providerExecuted:V.boolean().optional()}),pS=V.discriminatedUnion("type",[V.object({type:V.literal("text"),value:V.string(),providerOptions:g.optional()}),V.object({type:V.literal("json"),value:R1,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:R1,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:qq,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()})]))})]),Dq=V.object({type:V.literal("tool-result"),toolCallId:V.string(),toolName:V.string(),output:pS,providerOptions:g.optional()}),cS=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()}),lS=V.object({type:V.literal("tool-approval-response"),approvalId:V.string(),approved:V.boolean(),reason:V.string().optional()}),dS=V.object({role:V.literal("system"),content:V.string(),providerOptions:g.optional()}),iS=V.object({role:V.literal("user"),content:V.union([V.string(),V.array(V.union([Nq,yS,Lq]))]),providerOptions:g.optional()}),nS=V.object({role:V.literal("assistant"),content:V.union([V.string(),V.array(V.union([Nq,gS,Lq,fS,mS,uS,Dq,cS]))]),providerOptions:g.optional()}),sS=V.object({role:V.literal("tool"),content:V.array(V.union([Dq,lS])),providerOptions:g.optional()}),cd=V.union([dS,iS,nS,sS]);var ld=Symbol("ai-sdk-tool-call-input-schema-input");var dd=J6({prefix:"aitxt",size:24}),id=J6({prefix:"call",size:24});var nd=class extends TransformStream{constructor(){super({transform(X,J){J.enqueue(`data: ${JSON.stringify(X)}
193
193
 
194
194
  `)},flush(X){X.enqueue(`data: [DONE]
195
195
 
196
- `)}})}};var i3=V.record(V.string(),R1.optional()),bd=GG(()=>EX(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:i3.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:i3.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:i3.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:i3.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:i3.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 kd=Symbol("streamRetryAttemptBoundary");var xd=J6({prefix:"aitxt",size:24}),wd=J6({prefix:"call",size:24});var vd=J6({prefix:"aitxt",size:24}),yd=J6({prefix:"call",size:24});var hd=Symbol("streamRetryBoundary");var w6=V.record(V.string(),R1.optional()),uS=V.record(V.string(),V.string());var fd=GG(()=>{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 EX(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:uS.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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:w6.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 gd=J6({prefix:"call",size:24});var md=J6({prefix:"call",size:24});var ud=J6({prefix:"call",size:24});var pd=J6({prefix:"aiobj",size:24});function VN(X){return({url:J,abortSignal:$})=>CS({url:J,maxBytes:X?.maxBytes,abortSignal:$})}var cd=J6({prefix:"aiobj",size:24});var ld=J6({prefix:"call",size:24});var dd=VN();var id=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 pS="AI_NoSuchProviderError",nd=`vercel.ai.error.${pS}`;var sd=J6({prefix:"call",size:24});var ad=J6({prefix:"call",size:24}),od=VN();var rd=J6({prefix:"call",size:24});class v6 extends M1{name="ProviderResponseStreamError";constructor(X,J){super({message:X,url:"",requestBodyValues:void 0,cause:J?.cause,isRetryable:J?.retryable??!0})}}var L6={};DY(L6,{toWebSocketUrl:()=>zI,streamResponsesWebSocket:()=>VI,parseRateLimitSignal:()=>a3,normalizeHeaders:()=>ZI,markOversizedFrame:()=>MN,isUpgradeFailure:()=>WI,isOversizedFrame:()=>BI,isNonEmittingFrame:()=>AN,isAbortError:()=>HG,connectResponsesWebSocket:()=>HI,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>BG,PROTOCOL_HEADER:()=>FN,OpenAIWebSocket:()=>L6,OVERSIZED_FRAME_MESSAGE:()=>TN});function s3(X){let J=Number(X.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(J)?J:void 0}function SX(X,J,$=!1){let G=Buffer.from(X.slice(0,J)).toString("latin1").split(`\r
197
- `),Q=G[0]??"",z=s3(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 cS="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",UN=["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 zG{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+cS));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 UN)if(B[j]!==void 0)H.push(`${lS(j)}: ${B[j]}`);for(let[j,q]of Object.entries(J))if(!UN.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")H.push(`${j}: ${q}`);let U=`${H.join(`\r
196
+ `)}})}};var s3=V.record(V.string(),R1.optional()),sd=WG(()=>IX(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:s3.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:s3.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:s3.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:s3.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:s3.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 ad=Symbol("streamRetryAttemptBoundary");var od=J6({prefix:"aitxt",size:24}),rd=J6({prefix:"call",size:24});var td=J6({prefix:"aitxt",size:24}),ed=J6({prefix:"call",size:24});var Xi=Symbol("streamRetryBoundary");var v6=V.record(V.string(),R1.optional()),aS=V.record(V.string(),V.string());var Ji=WG(()=>{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 IX(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:aS.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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:v6.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 $i=J6({prefix:"call",size:24});var Yi=J6({prefix:"call",size:24});var Gi=J6({prefix:"call",size:24});var Qi=J6({prefix:"aiobj",size:24});function Fq(X){return({url:J,abortSignal:$})=>vS({url:J,maxBytes:X?.maxBytes,abortSignal:$})}var zi=J6({prefix:"aiobj",size:24});var Zi=J6({prefix:"call",size:24});var Wi=Fq();var Bi=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 oS="AI_NoSuchProviderError",Hi=`vercel.ai.error.${oS}`;var Vi=J6({prefix:"call",size:24});var Ui=J6({prefix:"call",size:24}),Ki=Fq();var ji=J6({prefix:"call",size:24});class y6 extends M1{name="ProviderResponseStreamError";constructor(X,J){super({message:X,url:"",requestBodyValues:void 0,cause:J?.cause,isRetryable:J?.retryable??!0})}}var L6={};MY(L6,{toWebSocketUrl:()=>jI,streamResponsesWebSocket:()=>FI,parseRateLimitSignal:()=>r3,normalizeHeaders:()=>NI,markOversizedFrame:()=>Iq,isUpgradeFailure:()=>qI,isOversizedFrame:()=>LI,isNonEmittingFrame:()=>kq,isAbortError:()=>jG,connectResponsesWebSocket:()=>DI,TERMINAL_AFTER_OUTPUT_MESSAGE:()=>KG,PROTOCOL_HEADER:()=>Cq,OpenAIWebSocket:()=>L6,OVERSIZED_FRAME_MESSAGE:()=>xq});function o3(X){let J=Number(X.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(J)?J:void 0}function bX(X,J,$=!1){let G=Buffer.from(X.slice(0,J)).toString("latin1").split(`\r
197
+ `),Q=G[0]??"",z=o3(Q);if(z===void 0||z===101)return;let Z=Object.fromEntries(G.slice(1).flatMap((N)=>{let K=N.indexOf(":");return K===-1?[]:[[N.slice(0,K).trim().toLowerCase(),N.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 N=JSON.parse(U);return s(N)?N: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 rS="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",Pq=["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 HG{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+rS));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[j,N]of Object.entries(J))B[j.toLowerCase()]=N;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 Pq)if(B[j]!==void 0)H.push(`${tS(j)}: ${B[j]}`);for(let[j,N]of Object.entries(J))if(!Pq.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")H.push(`${j}: ${N}`);let U=`${H.join(`\r
198
198
  `)}\r
199
199
  \r
200
- `;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 N=K instanceof Error?K.message:String(K);this.log("socket_error",{message:N}),this.emit("error",{message:N})},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=dS(this.rxBuffer,X),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),$=J.indexOf(`\r
200
+ `;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:(N)=>{this.socket=N,this.enqueueWrite(new TextEncoder().encode(U))},data:(N,K)=>this.onData(K),drain:()=>this.flushWrites(),error:(N,K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let q=K instanceof Error?K.message:String(K);this.log("socket_error",{message:q}),this.emit("error",{message:q})},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 N=j instanceof Error?j.message:String(j);this.log("connect_exception",{message:N}),this.emit("error",{message:N})}}onData(X){if(this.rxBuffer=eS(this.rxBuffer,X),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),$=J.indexOf(`\r
201
201
  \r
202
202
  `);if($===-1)return;let Y=J.slice(0,$),G=Y.split(`\r
203
- `)[0]??"",Q=Y.match(/sec-websocket-accept:\s*(\S+)/i),z=s3(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
+ `)[0]??"",Q=Y.match(/sec-websocket-accept:\s*(\S+)/i),z=o3(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
204
204
  \r
205
- `);if(J===-1)return!1;let $=SX(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=iS(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 F1({component:"raw-ws-bun",event:X,sessionID:this.sessionID,url:this.url,...J})}}function lS(X){return X}function dS(X,J){let $=new Uint8Array(X.length+J.length);return $.set(X,0),$.set(J,X.length),$}function iS(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 nS}from"node:net";import{connect as sS}from"node:tls";var aS="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",KN=["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 ZG{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+aS));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 KN)if(B[j]!==void 0)H.push(`${oS(j)}: ${B[j]}`);for(let[j,q]of Object.entries(J))if(!KN.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")H.push(`${j}: ${q}`);let U=`${H.join(`\r
205
+ `);if(J===-1)return!1;let $=bX(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=XI(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 F1({component:"raw-ws-bun",event:X,sessionID:this.sessionID,url:this.url,...J})}}function tS(X){return X}function eS(X,J){let $=new Uint8Array(X.length+J.length);return $.set(X,0),$.set(J,X.length),$}function XI(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 JI}from"node:net";import{connect as $I}from"node:tls";var YI="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",Oq=["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 VG{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+YI));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[j,N]of Object.entries(J))B[j.toLowerCase()]=N;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 Oq)if(B[j]!==void 0)H.push(`${GI(j)}: ${B[j]}`);for(let[j,N]of Object.entries(J))if(!Oq.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")H.push(`${j}: ${N}`);let U=`${H.join(`\r
206
206
  `)}\r
207
207
  \r
208
- `;try{this.log("connect_start",{host:Y,port:G,tls:$.protocol==="https:"});let j=()=>{this.socket?.write(U)},q=$.protocol==="https:"?sS({host:Y,port:G,servername:Y},j):nS({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 N=K instanceof Error?K.message:String(K);this.log("socket_error",{message:N}),this.emit("error",{message:N})}),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=rS(this.rxBuffer,X),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),$=J.indexOf(`\r
208
+ `;try{this.log("connect_start",{host:Y,port:G,tls:$.protocol==="https:"});let j=()=>{this.socket?.write(U)},N=$.protocol==="https:"?$I({host:Y,port:G,servername:Y},j):JI({host:Y,port:G},j);this.socket=N,N.on("data",(K)=>{this.onData(typeof K==="string"?Buffer.from(K,"binary"):K)}),N.on("error",(K)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let q=K instanceof Error?K.message:String(K);this.log("socket_error",{message:q}),this.emit("error",{message:q})}),N.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=QI(this.rxBuffer,X),!this.handshakeDone){let J=Buffer.from(this.rxBuffer).toString("latin1"),$=J.indexOf(`\r
209
209
  \r
210
210
  `);if($===-1)return;let Y=J.slice(0,$),G=Y.split(`\r
211
- `)[0]??"",Q=Y.match(/sec-websocket-accept:\s*(\S+)/i),z=s3(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
+ `)[0]??"",Q=Y.match(/sec-websocket-accept:\s*(\S+)/i),z=o3(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
212
212
  \r
213
- `);if(J===-1)return!1;let $=SX(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=tS(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 F1({component:"raw-ws-node",event:X,sessionID:this.sessionID,url:this.url,...J})}}function oS(X){return X}function rS(X,J){let $=new Uint8Array(X.length+J.length);return $.set(X,0),$.set(J,X.length),$}function tS(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 eS(){return typeof globalThis.Bun?.connect==="function"}var jN=eS()?zG:ZG;function IX(X){return process.env[X]??process.env[X.toLowerCase()]}function XI(X){let J=IX("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 JI(X){let J=new URL(X);if(XI(J))return;if(J.protocol==="http:")return IX("HTTP_PROXY");if(J.protocol==="https:")return IX("HTTPS_PROXY")??IX("HTTP_PROXY");return}var qN={getProxyForUrl:JI};var $I=Z0("quota"),g9=Z0("transport"),FN="responses_websockets=2026-02-06",NN=["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"],YI=new Set([k9,"x-opencode-title"]);function GI(X){let J=new Map;for(let Y of Object.keys(X))J.set(Y.toLowerCase(),Y);let $={};for(let Y of NN){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(!NN.includes(Y.toLowerCase()))$[Y]=G;return $}function QI(X){let J={};for(let[$,Y]of Object.entries(X)){if(YI.has($.toLowerCase()))continue;J[$]=Y}return J}function zI(X){return X.replace(/^http/,"ws")}function ZI(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 HG(X){return X instanceof DOMException&&X.name==="AbortError"}var PN=new WeakSet;function WI(X){return typeof X==="object"&&X!==null&&PN.has(X)}var ON=new WeakSet;function BI(X){return typeof X==="object"&&X!==null&&ON.has(X)}function MN(X){return ON.add(X),X}function LN(X,J){let $=Error(X,J===void 0?void 0:{cause:J});return PN.add($),$}function HI(X){return new Promise((J,$)=>{if(X.signal?.aborted){$(WG(X.signal));return}let Y={...X.headers,"openai-beta":X.headers["openai-beta"]??FN},G=Y[k9]??Y["session-id"];delete Y["content-length"],Y=GI(QI(Y));let Q=typeof Bun>"u"?void 0:qN.getProxyForUrl(X.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),z=!0,Z=X.rawWebSocket?new jN(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(),$(LN(e0(K),K))}function j(K){B(),$(LN(RN("WebSocket closed before open",K.code,K.reason)))}function q(){B(),Z.close(),$(WG(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 VI(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,N={sessionID:X.sessionID,codexSessionID:K},F,O=0,_,C=new Set,L={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
+ `);if(J===-1)return!1;let $=bX(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=zI(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 F1({component:"raw-ws-node",event:X,sessionID:this.sessionID,url:this.url,...J})}}function GI(X){return X}function QI(X,J){let $=new Uint8Array(X.length+J.length);return $.set(X,0),$.set(J,X.length),$}function zI(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 ZI(){return typeof globalThis.Bun?.connect==="function"}var Mq=ZI()?HG:VG;function kX(X){return process.env[X]??process.env[X.toLowerCase()]}function WI(X){let J=kX("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 BI(X){let J=new URL(X);if(WI(J))return;if(J.protocol==="http:")return kX("HTTP_PROXY");if(J.protocol==="https:")return kX("HTTPS_PROXY")??kX("HTTP_PROXY");return}var _q={getProxyForUrl:BI};var HI=Z0("quota"),m9=Z0("transport"),Cq="responses_websockets=2026-02-06",Aq=["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"],VI=new Set([x9,"x-opencode-title"]);function UI(X){let J=new Map;for(let Y of Object.keys(X))J.set(Y.toLowerCase(),Y);let $={};for(let Y of Aq){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(!Aq.includes(Y.toLowerCase()))$[Y]=G;return $}function KI(X){let J={};for(let[$,Y]of Object.entries(X)){if(VI.has($.toLowerCase()))continue;J[$]=Y}return J}function jI(X){return X.replace(/^http/,"ws")}function NI(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 jG(X){return X instanceof DOMException&&X.name==="AbortError"}var Eq=new WeakSet;function qI(X){return typeof X==="object"&&X!==null&&Eq.has(X)}var Sq=new WeakSet;function LI(X){return typeof X==="object"&&X!==null&&Sq.has(X)}function Iq(X){return Sq.add(X),X}function Tq(X,J){let $=Error(X,J===void 0?void 0:{cause:J});return Eq.add($),$}function DI(X){return new Promise((J,$)=>{if(X.signal?.aborted){$(UG(X.signal));return}let Y={...X.headers,"openai-beta":X.headers["openai-beta"]??Cq},G=Y[x9]??Y["session-id"];delete Y["content-length"],Y=UI(KI(Y));let Q=typeof Bun>"u"?void 0:_q.getProxyForUrl(X.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),z=!0,Z=X.rawWebSocket?new Mq(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",N)}function H(){B(),J(Z)}function U(K){B(),$(Tq(e0(K),K))}function j(K){B(),$(Tq(wq("WebSocket closed before open",K.code,K.reason)))}function N(){B(),Z.close(),$(UG(X.signal))}Z.addEventListener("open",H,{once:!0}),Z.addEventListener("error",U,{once:!0}),Z.addEventListener("close",j,{once:!0}),X.signal?.addEventListener("abort",N,{once:!0})})}function FI(X){let J=new TextEncoder,$=X.socket,Y,G=()=>{},Q=!1,z=0,Z=!1,W=!1,B,H=[],U=12,j=[],N=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,q={sessionID:X.sessionID,codexSessionID:K},F,O=0,_,C=new Set,L={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]
214
214
 
215
- `)),Y?.close()}function k(a){w(a,a)}function p(){if(!W)return"none";if(L.other)return"other";if(L.finished)return L.reasoningItemIds.size>0?"other":"finished-calls";return L.addedItemIds.size>0?"unfinished-calls":"none"}function i(){Y?.enqueue(J.encode(`data: ${JSON.stringify(FI)}
215
+ `)),Y?.close()}function k(a){w(a,a)}function p(){if(!W)return"none";if(L.other)return"other";if(L.finished)return L.reasoningItemIds.size>0?"other":"finished-calls";return L.addedItemIds.size>0?"unfinished-calls":"none"}function i(){Y?.enqueue(J.encode(`data: ${JSON.stringify(CI)}
216
216
 
217
- `)),T()}function X0(a){let u0={...N,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;g9.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=BG;g9.warn("stream failed after output; not retried",{reason:a.message,emittedOutput:!0,outputShape:t,...u0}),w(Error(o,{cause:a}),new v6(o,{cause:a}));return}let h=L.reasoningItemIds.size;g9.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}),k(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 v6(a)),X.idleTimeout)}async function G0(a){if(Q)return;if(typeof a.data!=="string"){X0(new v6("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"){$I.debug("codex.rate_limits frame received",{pid:process.pid}),J0("idle timeout waiting for websocket");let c=Rz(t);X.onQuota?.(c);return}let h=p(),o=h==="none"||h==="unfinished-calls"?a3(t):void 0;if(o&&t){Q=!0,P(),X.onRateLimitReached?.(o.window,o.resetAt),X.onTerminal?.(t),X.onFirstEvent?.(),Y?.error(new v6(`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 v6(c instanceof Error?c.message:String(c),{cause:c}));return}}let e=jI(t,u0);if(e&&t){if(!Z)X.onFirstEvent?.(e);Q=!0,P(),X.onTerminal?.(t);let c=new M1({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")g9.warn("protocol error after unfinished function calls only; surfaced as before output",{...N,status:e.status,reason:e.message,outputShape:D0,responseID:F,previousResponseID:q});Y?.error(c);return}if(g9.warn(D0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...N,status:e.status,reason:e.message,outputShape:D0,responseID:F,previousResponseID:q}),D0==="finished-calls"){i();return}Y?.error(Error(BG,{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")g9.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",{...N,outputShape:l0,responseID:F,previousResponseID:q});if(l0==="none"||l0==="unfinished-calls")X.onFirstEvent?.(),Y?.error(new v6(`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(UI(t,C),!Z)X.onFirstEvent?.();if(Y?.enqueue(J.encode(`${u0.split(/\r?\n/).map((c)=>`data: ${c}`).join(`
217
+ `)),T()}function X0(a){let u0={...q,openingFrameTypes:H,openingItemTypes:j,responseID:F,previousResponseID:N,hasContinuation:N!==void 0,framesSinceCreated:O,msSinceLastFrame:_===void 0?void 0:Date.now()-_},t=p();if(t==="finished-calls"){if(Q)return;m9.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=KG;m9.warn("stream failed after output; not retried",{reason:a.message,emittedOutput:!0,outputShape:t,...u0}),w(Error(o,{cause:a}),new y6(o,{cause:a}));return}let h=L.reasoningItemIds.size;m9.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}),k(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 y6(a)),X.idleTimeout)}async function G0(a){if(Q)return;if(typeof a.data!=="string"){X0(new y6("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"){HI.debug("codex.rate_limits frame received",{pid:process.pid}),J0("idle timeout waiting for websocket");let c=Iz(t);X.onQuota?.(c);return}let h=p(),o=h==="none"||h==="unfinished-calls"?r3(t):void 0;if(o&&t){Q=!0,P(),X.onRateLimitReached?.(o.window,o.resetAt),X.onTerminal?.(t),X.onFirstEvent?.(),Y?.error(new y6(`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 y6(c instanceof Error?c.message:String(c),{cause:c}));return}}let e=MI(t,u0);if(e&&t){if(!Z)X.onFirstEvent?.(e);Q=!0,P(),X.onTerminal?.(t);let c=new M1({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")m9.warn("protocol error after unfinished function calls only; surfaced as before output",{...q,status:e.status,reason:e.message,outputShape:D0,responseID:F,previousResponseID:N});Y?.error(c);return}if(m9.warn(D0==="finished-calls"?"protocol error after finished function calls only; ended as completed":"protocol error after output; not retried",{...q,status:e.status,reason:e.message,outputShape:D0,responseID:F,previousResponseID:N}),D0==="finished-calls"){i();return}Y?.error(Error(KG,{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")m9.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",{...q,outputShape:l0,responseID:F,previousResponseID:N});if(l0==="none"||l0==="unfinished-calls")X.onFirstEvent?.(),Y?.error(new y6(`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(PI(t,C),!Z)X.onFirstEvent?.();if(Y?.enqueue(J.encode(`${u0.split(/\r?\n/).map((c)=>`data: ${c}`).join(`
218
218
  `)}
219
219
 
220
- `)),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=LI(t),g9.debug("response created",{...N,responseID:F,previousResponseID:q,hasContinuation:q!==void 0});if(!AN(t.type))W=!0,DI(t,L);if(J0("idle timeout waiting for websocket"),t.type==="response.completed"||t.type==="response.done"){Q=!0,KI(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 v6(e0(a),{cause:a}))}function m(a){if(Q)return;let u0=a.code===1009,t=new v6(u0?TN:RN("WebSocket closed before response.completed",a.code,a.reason),{retryable:!u0});if(u0)g9.warn("websocket peer refused the request size",{...N,requestBytes:z,reason:a.reason.toString()});X0(u0?MN(t):t)}function c0(){let a=WG(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?.(qI(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;k(new v6(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 UI(X,J){if(X.type!=="response.output_item.done")return;if(!s(X.item))return;_N(X.item,J)}function KI(X,J){let $=X.response;if(!s($)||!Array.isArray($.output))return;for(let Y of $.output)if(s(Y))_N(Y,J)}function _N(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 jI(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 a3(X){if(typeof X==="string")try{return a3(JSON.parse(X))}catch{return}if(!s(X))return;let J=a3(X.cause);if(J)return J;let $=a3(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 qI(X){if(HG(X))return X;if(X instanceof Error)return X;return new DOMException(typeof X==="string"?X:"Aborted","AbortError")}function WG(X){let J=X?.reason;if(HG(J))return J;if(NI(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function NI(X){return X instanceof Error&&(X.name==="ProviderHeaderTimeoutError"||X.name==="ProviderResponseStreamError")}function LI(X){let J=X.response;if(!s(J))return;return typeof J.id==="string"?J.id:void 0}function DI(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(DN($)&&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(DN($)&&typeof $?.id==="string"&&J.reasoningItemIds.has($.id))return;break}J.other=!0}function DN(X){if(X?.type!=="reasoning")return!1;let J=($)=>$===void 0||$===null||Array.isArray($)&&$.length===0;return J(X.summary)&&J(X.content)}var FI={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function AN(X){return X==="response.created"||X==="response.in_progress"||X.startsWith("codex.")}var BG="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.",TN="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 RN(X,J,$){let Y=[`code ${J}`];if($.length>0)Y.push($.toString());return`${X} (${Y.join(": ")})`}var UG="x-opencode-title",bX="x-openai-auth-quota-account",VG=new Set([UG,k9,bX,"x-opencode-session"]),OI=15000,MI=300000,_I=3300000,CN="websocket_connection_limit_reached";function AI(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 PI("sha256").update(Y).digest("hex").slice(0,12)}function TI(X){let J=X?.httpFetch??globalThis.fetch,$=new Map,Y=X?.connectTimeout??OI,G=X?.idleTimeout??MI,Q=X?.maxConnectionAge??_I,z=X?.streamRetries??5,Z=X?.firstEventGraceMs??250,W=X?.rawWebSocket??!1,B=X?.onQuota,H=X?.onRateLimitReached,U=setInterval(()=>N(),Math.min(G,60000));if(typeof U==="object"&&"unref"in U&&typeof U.unref==="function")U.unref();function j(_,C,L,P){if(!C||!L)return L;KG(_,EN(C),void 0,P);let A=new Headers(L.headers),T=A.get("x-codex-turn-metadata");if(!T)return L;let k=yN(T,_.turnID,_.turnStartedAt);if(!k)return L;return A.set("x-codex-turn-metadata",k),{...L,headers:A}}async function q(_,C){let L=_ instanceof URL?_.toString():typeof _==="string"?_:_.url,P=L6.normalizeHeaders(C?.headers),A=uN(C),T=XX(A);if(C?.method!=="POST"||!new URL(L).pathname.endsWith("/responses"))return J(_,T);let k=(()=>{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(!k?.stream)return J(_,T);if(P[UG]==="true")return J(_,T);let p=P[k9]??P["x-session-affinity"]??P["session-id"],i=p;if(!p)return J(_,T);let X0=L6.normalizeHeaders(A?.headers),w=AI(X0),J0=`${p}:${w}:conversation`,G0=typeof P[bX]==="string"?P[bX]: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=EN(k),m0;if(m.fallback)return J(_,j(m,k,T,m0));if(m.busy)return J(_,j(m,k,T,m0));m.busy=!0,m.lastUsedAt=Date.now();try{m0=_4(m,c0);let r=L6.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 SI(m,X?.url??L,h,Y,Q,W,C?.signal),hI(m,c0,m0))await II(m,c0,G,{signal:C?.signal??void 0,sessionID:i,url:X?.url??L,headers:A?.headers,onRateLimitReached:L0});let o=()=>{},e=()=>{},c=new Promise((p0,D8)=>{o=p0,e=D8}),D0=yI(m,c0,m0),l0=o3(vN(m,D0,c0,m0)),i6=typeof l0.previous_response_id==="string";await q4({sessionID:i,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(l0),url:X?.url??L,method:A?.method,headers:A?.headers});let n0=L6.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,D8)=>{let A4=bN(p0);F1({component:"ws-pool",event:"main_completed",sessionID:i,responseID:IN(p0),usage:A4}),wN(m,c0,p0,D8,i6,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,K9(m)},onConnectionInvalid:(p0)=>{if(m.busy=!1,m.lastUsedAt=Date.now(),L6.isOversizedFrame(p0))m.fallback=!0;if(!m.fallback)K(m);m.continuation=void 0,K9(m),o(!1)},onAbort:(p0)=>{m.busy=!1,m.lastUsedAt=Date.now(),m.streamFailures=0,m.continuation=void 0,K9(m),e(p0)},onRetryableTerminal:async(p0)=>{let D8=SN(p0);if(!D8)return;throw m.fallback=!0,D8}}),F6=await RI(c,Z);if(F6!==!1){if(F6===!0||F6.status<200||F6.status>599)return n0;return new Response(F6.body,{status:F6.status,headers:{"content-type":"application/json",...F6.headers}})}let y6=()=>J(_,j(m,k,T,m0));if(!m.fallback)return CI(n0,y6);return y6()}catch(r){if(m.busy=!1,m.lastUsedAt=Date.now(),L6.isAbortError(r))throw m.streamFailures=0,m.continuation=void 0,K9(m),r;let a=L6.parseRateLimitSignal(r);if(a)L0?.(a.window,a.resetAt);if(L6.isUpgradeFailure(r)&&!W)m.fallback=!0;if(K(m),m.continuation=void 0,K9(m),m.fallback)return J(_,j(m,k,T,m0));return EI(new v6(r instanceof Error?r.message:String(r),{cause:r}))}}function K(_){if(_.streamFailures++,_.streamFailures>z)_.fallback=!0}function N(){let _=Date.now();for(let[C,L]of $){if(L.busy)continue;if(_-L.lastUsedAt<G)continue;K9(L),$.delete(C)}}function F(){clearInterval(U);for(let _ of $.values())K9(_);$.clear()}function O(_){let C=`${_}:`;for(let[L,P]of $){if(!L.startsWith(C))continue;K9(P),$.delete(L)}}return Object.assign(q,{close:F,remove:O})}function SN(X){if(X.type!=="error"||!s(X.error)||X.error.code!==CN)return;return Error(typeof X.error.message==="string"?X.error.message:CN)}async function RI(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 CI(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||!L6.isOversizedFrame(W)){Q.error(W);return}try{let B=await J();if(!B.ok){Q.error(new v6(`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 EI(X){return new Response(new ReadableStream({start(J){J.error(X)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function SI(X,J,$,Y,G,Q,z){if(X.socket?.readyState===WebSocket.OPEN&&X.connectedAt&&Date.now()-X.connectedAt<G)return X.socket;K9(X);let Z=await L6.connectResponsesWebSocket({url:L6.toWebSocketUrl(J),headers:$,timeout:Y,rawWebSocket:Q,signal:z??void 0});return X.connectedAt=Date.now(),Z}function K9(X){if(X.socket)X.socket.close(),X.socket=void 0;X.connectedAt=void 0,X.continuation=void 0}async function II(X,J,$,Y){if(!X.socket||!Array.isArray(J.input)||J.input.length===0)return;let G=kI(J);await q4({sessionID:Y.sessionID,transport:"websocket",phase:"prewarm",bodyText:()=>JSON.stringify(G),url:Y.url,method:"POST",headers:Y.headers});let Q=L6.streamResponsesWebSocket({socket:X.socket,body:G,sessionID:Y.sessionID,idleTimeout:$,signal:Y.signal,onRateLimitReached:Y.onRateLimitReached,onComplete:(z,Z)=>{F1({component:"ws-pool",event:"prewarm_completed",sessionID:Y.sessionID,responseID:IN(z),usage:bN(z)}),wN(X,G,z,Z,!1,{input:P1([]),signature:gN(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=SN(z);if(!Z)return;throw X.fallback=!0,Z}});await bI(Q)}function IN(X){let J=X.response;if(!s(J))return;return typeof J.id==="string"?J.id:void 0}function bN(X){let J=X.response;if(!s(J))return;return s(J.usage)?J.usage:void 0}async function bI(X){let J=X.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function kI(X){return o3({...X,generate:!1,input:[],previous_response_id:void 0,client_metadata:xI(X.client_metadata)})}function kN(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 xI(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":kN(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":kN($)}}catch{return X}}var xN=["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 EN(X){let J={...X};if(Array.isArray(X.input))J.input=X.input.map(vI);return J}function o3(X){let J={};for(let $ of xN)if($ in X)J[$]=X[$];for(let $ of Object.keys(X))if(!($ in J))J[$]=X[$];return J}function vI(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 wN(X,J,$,Y,G,Q=_4(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:k3(Q.input),finalizedCallIds:W}}function KG(X,J,$=J,Y=_4(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?x3(hN(Y,X.turnInput),Y.input):void 0,W=Z===void 0?G:Q.slice(Z);if(W.length>0&&W.some(fN)||!X.turnID)X.turnID=O1(),X.turnStartedAt=Date.now();X.turnInput=Q.slice(),Y.priorInputs.set(X.turnInput,Y.input),X.turnSignature=z,X.turnCanonical=k3(Y.input)}function vN(X,J,$=J,Y=_4(X,{...$,input:Array.isArray($.input)?$.input:J.input})){KG(X,J,$,Y);let G=J.client_metadata;if(!s(G)||typeof G["x-codex-turn-metadata"]!=="string")return J;let Q=yN(G["x-codex-turn-metadata"],X.turnID,X.turnStartedAt);if(!Q)return J;return{...J,client_metadata:{...G,"x-codex-turn-metadata":Q}}}function yN(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 _4(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=P1($,X.turnCanonical??X.continuation?.canonical);return Y.set($,G),{input:G,signature:gN(J),priorInputs:Y}}function hN(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}$??=P1(J),X.priorInputs.set(J,$)}return $}function yI(X,J,$=_4(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(!mN(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=fI(G,X.continuation.finalizedCallIds);if(Q.length===0)return J;return{...J,previous_response_id:X.continuation.responseID,input:Q}}function hI(X,J,$=_4(X,J)){let Y=Array.isArray(J.input)?J.input:void 0;if(!X.continuation)return!0;if(!Y)return!1;if(!mN(X.continuation,$))return!0;return Y.slice(X.continuation.input.length).some(fN)}function fN(X){if(!s(X))return!1;if(!(X.type==="message"||("role"in X)))return!1;return X.role==="user"||X.role==="developer"}function fI(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 gN(X){return D4(gI(Object.fromEntries(Object.entries(X).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function gI(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 mN(X,J){if(X.input.length>=J.input.texts.length)return!1;return x3(hN(J,X.input),J.input)!==void 0}function uN(X){if(!X?.headers)return X;if(X.headers instanceof Headers){let J=new Headers(X.headers);for(let $ of VG)J.delete($);return{...X,headers:J}}if(Array.isArray(X.headers))return{...X,headers:X.headers.filter((J)=>!VG.has(J[0].toLowerCase()))};return{...X,headers:Object.fromEntries(Object.entries(X.headers).filter(([J])=>!VG.has(J.toLowerCase())))}}var sI=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),aI=new Set(["gpt-5.6","gpt-6","gpt-6.1"]);function oI(X){if(sI.has(X))return!0;if(aI.has(X))return!1;let $=X.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return $?parseFloat($)>5.4:!1}function rI(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 tI="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.",eI=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"]),Xb="opencode-oauth-dummy-key",Jb="terminal_resize_reflow",DG="0.159.0",$b=`codex_exec/${DG} (Debian 12.0.0; aarch64) unknown (codex_exec; ${DG})`,Yb="seccomp",Pn=()=>g8,Gb=120000,Qb=90000,zb=4000,pN=50,cN=3,Zb=25,Wb=60000,Bb="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",FG=!1,vX;function On(){return vX}function Mn(){FG=!1,vX=void 0}var lN=Z0("models"),dN=!1,iN=!1;class OG 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 D6 extends Error{code;constructor(X,J){super(J);this.name="ResetTargetResolutionError",this.code=X}}function qG(X,J,$,Y){let G=($?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!X||!J||J-Y<=G}function Hb(X,J){let $=X==="main",Y=J.row,G=()=>new D6("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 D6("unknown_account",`Fallback account ${X} was not found.`)}if(!Y.enabled)throw new D6("disabled_account",`${$?"Main":"Fallback"} account ${X} is disabled.`);if(Y.type!=="oauth")throw new D6("non_oauth_account",`${$?"Main":"Fallback"} account ${X} is not an OAuth account.`);if(!J.token)throw G();let Q=V6(J.token);return{accountKey:X,label:$?"Main account":Y.label??X,accessToken:J.token,chatgptAccountId:Y.identity??(Q?U6(Q):void 0)}}function Vb(X){async function J(){let $=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath}),Y=z9($);if(!$||!Y||T0(Y))throw new D6("token_unavailable","Main OpenAI account has no usable access token.");let G=Y;if(qG(G.access,G.expires,$,X.now()))G=await(X.refreshPoolMainRow??X.refreshFallbackAccount)(G,$);if(!G.access)throw new D6("token_unavailable","Main OpenAI account has no usable access token.");let Q=V6(G.access);return{accountKey:"main",label:"Main account",accessToken:G.access,chatgptAccountId:G.accountId??(Q?U6(Q):void 0)}}return async($)=>{let Y=await X.poolAccess?.($);if(Y)return Hb($,Y);if($==="main"){let H=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath}),U=await X.getAuth();if(C6(U))return J();if(U.type!=="oauth")throw new D6("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(qG(U.access,U.expires,H,X.now()))try{U={type:"oauth",...await X.refreshMainWithLease()}}catch(N){if(N instanceof L1)return J();throw N}if(!U.access)throw new D6("token_unavailable","Main OpenAI account has no usable access token.");let j=V6(U.access),q=j?U6(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 D6("unknown_account",`Fallback account ${$} was not found.`);if(Q.enabled===!1)throw new D6("disabled_account",`Fallback account ${$} is disabled.`);if(!v0(Q))throw new D6("non_oauth_account",`Fallback account ${$} is not an OAuth account.`);let z=()=>new D6("token_unavailable",`Fallback account ${$} has no usable access token.`);if(T0(Q))throw z();let Z=Q;if(qG(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 D6("unknown_account",`Fallback account ${$} was not found.`);if(B.enabled===!1)throw new D6("disabled_account",`Fallback account ${$} is disabled.`);if(!v0(B))throw new D6("non_oauth_account",`Fallback account ${$} is not an OAuth account.`);return{accountKey:$,label:Z.label??$,accessToken:Z.access,chatgptAccountId:B.accountId}}}function Ub(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function NG(X){return X instanceof OG}function nN(){throw Error(Bb)}async function Kb(X,J={}){let $=M0(V0());if(h$($.configPath)){await K1(H4($),J.holdsMainRefreshLock?void 0:W9($),(Y)=>{if(J.canWrite&&!J.canWrite())throw Error(D1["vault-refused"]);X(Y)});return}await L7((Y)=>{return X(Y),Y},$,{canWrite:J.canWrite})}var UL=null;function _n(){return UL}function jb(X){return Math.floor(Math.random()*X)}var qb=!0;function Nb(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 Lb(X,J,$){let Y=X.get(J);if(Y)return Y;let G=O1(),Q={threadID:G,turnID:O1(),windowID:`${G}:0`};return X.set(J,Q),$?.(),Q}function KL(){return nI(w7(),"openai-auth-sessions.json")}function Db(){let X=new Map;try{let J=JSON.parse(cI(KL(),"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:O1(),windowID:`${Y.threadID}:0`})}}catch{}return X}function Fb(X){let J=KL(),$=`${J}.tmp-${process.pid}`;try{pI(w7(),{recursive:!0});let Y={version:1,sessions:Object.fromEntries([...X.entries()].map(([G,Q])=>[G,{threadID:Q.threadID}]))};iI($,`${JSON.stringify(Y,null,2)}
221
- `,"utf8"),lI($,J)}catch{}}function yX(X,J){return s(X)&&(X.type==="message"||("role"in X))&&X.role===J}function Pb(X,J,$){if(!X.input)return J.length>0;let Y=X.canonicalInput??P1(X.input);if(x3(Y,$)===void 0)return!0;return J.slice(X.input.length).some((Q)=>yX(Q,"user")||yX(Q,"developer"))}function Ob(X,J){let $=Array.isArray(J?.input)?J.input:void 0,Y=$?P1($,X.canonicalInput):void 0;if($&&Y&&(Pb(X,$,Y)||!X.turnID))X.turnID=O1(),X.turnStartedAt=Date.now();else if(!X.turnStartedAt)X.turnStartedAt=Date.now();if($&&Y)X.input=$.slice(),X.canonicalInput=k3(Y)}function Mb(X){let J=X.headers.get(hX);if(X.headers.delete(hX),!X.metadata)return{init:X.init};let $=Nb(X.init?.body);if(!X.websocket)Ob(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:Yb,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",Jb),X.headers.set("x-codex-turn-metadata",Y),X.headers.set("user-agent",$b),X.headers.set("version",DG),X.dumpSessionID)X.headers.set(k9,X.dumpSessionID);let G=$;if(!G)return{init:X.init};let Q=X.responsesLite&&typeof G.model==="string"&&eI.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(Eb);if(Rb(G,X.metadata,J),Q)Cb(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(o3(G))}}}function _b(X,J){return X.find(($)=>$.enabled!==!1&&v0($)&&($.id===J||$.accountId===J))}function sN(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 kX(X,J){if(!X)return X;if(typeof X.checkedAt==="number"&&Number.isFinite(X.checkedAt))return X;return{...X,checkedAt:J}}function jL(X,J,$=Date.now(),Y=J.mainAccountId){let G=X.getMain(),Q=G?.quota;return{main:{quota:Q?{...Q,checkedAt:G.checkedAt,primary:kX(Q.primary,G.checkedAt),secondary:kX(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:kX(W.primary,Z.checkedAt),secondary:kX(W.secondary,Z.checkedAt)}:null,killed:!1,enabled:!0,...W?.resetCreditsAvailable!==void 0?{resetCredits:W.resetCreditsAvailable}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:$}}function An(X,J,$,Y=Date.now()){return{...jL(X,J,Y),activeId:$}}function aN(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 LG(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 oN(X){return X.get("x-session-affinity")??X.get("x-opencode-session")??X.get("x-session-id")??X.get("session-id")??void 0}function PG(X){if(Array.isArray(X)){let $=X;for(let Y=0;Y<X.length;Y++){let G=PG(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=PG(X[$]);if(Y===X[$])continue;if(J===X)J={...X};J[$]=Y}return J}var Ab=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),hX="x-openai-auth-agent",Tb=new Set(["title","compaction","summary"]);function Rb(X,J,$){if($!==null&&Tb.has($))return;let Y=typeof X.model==="string"?X.model:"";if(!Ab.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)=>mI("sha256").update(D4(j)).digest("hex").slice(0,16);if(J.pinnedEffort===void 0||Z.some((j)=>!z||!yX(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)=>yX(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 Cb(X){let J=s(X.reasoning)?{...X.reasoning}:{};J.context="all_turns",X.reasoning=J,X.parallel_tool_calls=!1;let $=PG(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 Eb(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 Sb(X,J={}){let $=J.codexApiEndpoint??p6().codexApiEndpoint,Y=crypto.randomUUID(),G=Db(),Q=()=>Fb(G),z=!1,Z=!1,W=[],B=null,H=jH(X.client),U=new Map,j=new Map,q,K=!1,N,F=new Map,O,_,C=PV({host:"opencode",stateDir:J.vault?.stateDir??lW(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())),L=C.vault;await L.authority();let P=C.firstRoster,A=Promise.withResolvers(),T=Promise.race([P,A.promise]),k=J.vault?.firstRosterWaitMs??a$,p,i,{enabled:X0,...w}=J.poolMigration??{},J0=X0??qb;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?tH({paths:()=>M0(V0()),slot:H.slot,version:b9,...w,runDeps:{vaultServes:()=>L.serves(),...w.runDeps},paused:async()=>await L.authority()!=="local",migrate:async(h)=>{let o=await(w.migrate??c7)(h);return i?.load(),o},adopt:async(h)=>{if(!await E3(T,k))return{status:"retry",reason:"vault-roster-pending"};let o=await(w.adopt??l7)(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 p$(J.backgroundQuota),c0,m0=TH({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:L,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 lV(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=p8(o.id);if(F.delete(c),_?.cancel(`pin:${c}`),N){let D0=(await b0(M0(V0())))?.accounts;await QL(o.id,D0,N).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||WW(e),D0=c?null:await mV();if(!c&&D0&&!dN)dN=!0,lN.debug("restoring OAuth model costs from models.dev catalog");if(!c&&!D0&&!iN)iN=!0,lN.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"&&oI(l0.api.id)).map(([l0,i6])=>[l0,{...i6,cost:c?{input:0,output:0,cache:{read:0,write:0}}:D0?.[i6.api.id]??D0?.[l0]??i6.cost,limit:rI(i6.id)??i6.limit}]))}},auth:{provider:"openai",async loader(h){await L.authority(),c0=h,p??=LV({version:b9,logger:Z0("heartbeat")}),await p,G0?.start();let o=await h();if(o.type!=="oauth")return A.resolve(),{};let e=A3(o).kind==="tombstone";C.start();let c=X.directory?await tN(X.directory):void 0,D0=c?.dir??V0();async function l0(D,M={}){if(await L.authority()!=="local")return;return Kb(D,{...M,canWrite:()=>!L.enrolled()})}let i6=await L.authority()!=="local";if(!e&&!i6)await DW({type:"oauth",access:o.access??"",refresh:o.refresh??"",expires:o.expires??0},M0(V0()));let n0=await b0(M0(V0())).catch(async(D)=>{if(await L.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(!i6&&await p7(M0(V0()),o)){if(G0)G0.noticePlaceholderWithoutMain();else if(!K)K=!0,Z0("pool-migration").warn(V4,{reason:"placeholder-without-main"})}let F6,y6=n0;async function p0(){let D=V0(),M;try{M=dI(D)}catch{M=void 0}if(M&&F6?.path===D&&F6.mtimeMs===M.mtimeMs&&F6.size===M.size)return F6.storage;if(!M)F6=void 0;let R=b0(M0(D)).catch(async(I)=>{if(await L.authority()!=="local")return y6;throw I}).then((I)=>{if(M)F6={path:D,mtimeMs:M.mtimeMs,size:M.size,storage:I};return y6=I,I});return YX(R,$X,()=>y6)}function D8(){F6=void 0}if(n0&&o.access&&!e&&!i6){let D=Z8({id_token:"",access_token:o.access,refresh_token:o.refresh??""});if(D&&D!==n0.mainAccountId)await l0((M)=>{M.mainAccountId=D}),n0.mainAccountId=D,D8()}let A4=n0?.logging?.level;if(A4&&typeof A4==="string")t7(A4);let T4=Z0("transport"),X8=Z0("quota"),r3=Z0("refresh"),F8=Z0("accounts");T4.info("codex auth loader ready",{codexApiEndpoint:$,transport:p6().rawWebSocket?"raw-websocket":p6().webSockets?"websocket":"http"});let U0=new b8({storage:n0,configPath:V0(),fetchQuotaFn:void 0}),R4,C4=0;i?.dispose();let d0=new o$({paths:()=>M0(V0()),refreshProvider:async(D)=>{let M=await Y3({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 I8({accessToken:M.access,fetchImpl:fetch,now:Date.now,...D.identity?{accountId:D.identity}:{},accountKey:D.id,logger:X8}),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 S9(R,I,!0)},vaultIdentities:()=>L.identities(),vaultMode:()=>L.enrolled(),vaultAuthority:()=>L.authority(),vaultFirstRoster:P,vaultFirstRosterBackgroundWaitMs:k,log:Z0("pool")});if(i=d0,!i6)await d0.load();let n6=new rJ({paths:M0(V0()),refreshFn:async(D)=>{if(await L.authority()!=="local")throw Error(D1["vault-refused"]);return Y3({refreshToken:D.refreshToken,fetchImpl:D.fetchImpl,now:D.now})},quotaManager:U0,canWrite:()=>!L.enrolled(),onFallbackStorageChanged:D8,backgroundRefreshPaused:async()=>L.enrolled()||await d0.active()});if(n0&&n0.accounts.length>0)n6.startBackgroundRefresh();function fX(D){if(T0(D))return;return D.access||void 0}function t3(D={}){let{readSidebarState:M,respectBackoff:R,skipFresherThanMs:I}=D;return{getAuth:h,codexRefreshFn:Y3,refreshMainWithLease:kG,fallbackManager:n6,quotaManager:U0,loadAccounts:b0,writeSidebarState:P8,client:X.client,fetchImpl:fetch,now:Date.now,paths:M0(V0()),readSidebarState:M??(()=>XL(S6)),storageMainAccountId:n0?.mainAccountId,isOAuthAccountFn:v0,whamFn:I8,...R===void 0?{}:{respectBackoff:R},...I===void 0?{}:{skipFresherThanMs:I}}}async function MG(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 _G(D){return d0.accessFor(D,await b0(M0(V0())))}let AG=Z0("cachekeep"),e3=D7(n0),TG=e3?.enabled===!0,RG=e3?.subagents===!0,CG=e3?.sustain===!0,EG=lH(n0?{...n0,cachekeep:e3}:n0),X2;async function qL(D){await new Promise((M)=>setTimeout(M,D))}async function NL(D){let M;for(let R=1;R<=cN;R++){if(await L.authority()!=="local")throw Error(D1["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<cN)await qL(Zb*R)}}throw new OG(M)}async function J2(D){await l0((M)=>{M.refresh=M.refresh??{},D(M)},{holdsMainRefreshLock:!0}),D8()}async function gX(D){let M=Date.now()+zb;while(Date.now()<M){await new Promise((S)=>setTimeout(S,pN+jb(pN)));let R=await h();if(C6(R))throw new L1;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 r3.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 SG(D){if(C6(D))throw new L1;if(D.type!=="oauth")throw Error("not oauth");if(T0(D))throw new G1;if(!D.refresh)throw Error("Token refresh failed: missing refresh token");return D.refresh}async function mX(){if(!X2)X2=(async()=>{let D=await h(),M=SG(D);if(D.type!=="oauth")throw Error("not oauth");let R=z8(M),I=await b0(M0(V0())),S=I?.refresh?.mainLastRefreshError;if(S&&r0(S,M,Date.now()))throw Error(e8(S,Date.now()));if(I?.refresh?.mainRefreshLeaseUntil&&I.refresh.mainRefreshLeaseUntil>Date.now()&&I.refresh.mainRefreshLeaseTokenHash===R){let d=await gX(D);if(d)return d;throw Error("Codex OAuth refresh is already in progress")}let f=await g0({name:g8,ttlMs:Gb,path:V0(),renew:!0});if(!f){let d=await gX(D);if(d)return d;throw Error("Codex OAuth refresh is already in progress")}let b;try{let d=await h(),H0=SG(d);if(d.type!=="oauth")throw Error("not oauth");if(H0!==M){if(d.access&&(d.expires??0)>Date.now())return r3.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 W6=(await b0(M0(V0())))?.refresh?.mainLastRefreshError;if(W6&&r0(W6,H0,Date.now()))throw Error(e8(W6,Date.now()))}b={...d,refresh:H0}}catch(d){throw await f.release().catch(()=>{}),d}await rB(M0(V0()),b.refresh,b.access!==void 0?{slotAccess:b.access}:{}).catch(()=>!1);let v=z8(b.refresh),n=crypto.randomUUID(),z0=v;try{await J2((F0)=>{if(oB(V0(),b.refresh))throw new m7;F0.refresh=F0.refresh??{},F0.refresh.mainRefreshLeaseId=n,F0.refresh.mainRefreshLeaseUntil=Date.now()+Qb,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 L.authority()!=="local")throw Error(D1["vault-refused"]);let H0=await Y3({refreshToken:b.refresh,fetchImpl:fetch,now:Date.now});return await NL(H0),await J2((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 m7)){if(!NG(d))await J2((H0)=>{H0.refresh=H0.refresh??{},H0.refresh.mainLastRefreshError=p1({error:d,now:Date.now(),refreshToken:b.refresh,previous:H0.refresh.mainLastRefreshError})}).catch(()=>{});throw d}}finally{if(z0)await J2((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 gX(b);if(l)return l;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{X2=void 0});return X2}function IG(D){return qH({storage:D,now:Date.now,refreshAccount:(M,R)=>n6.refreshAccount(M,R,{asPoolMain:!0}),warn:(M,R)=>r3.warn(M,{pid:process.pid,...R})})}async function bG(){let D=await IG(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 kG(){try{return await mX()}catch(D){if(D instanceof L1)return bG();throw D}}let xG=globalThis,uX=xG.__openaiAuthCacheKeepManagers??new Map;xG.__openaiAuthCacheKeepManagers=uX,uX.get(D0)?.stop();let E4=nH({fetchImpl:fetch,vault:L,getMainToken:async()=>{if(await L.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await d0.active()){let M=await _G("main");if(!M)throw Error("main pool row has no usable token");return M.token}let D=await h();if(await L.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(C6(D))return(await bG()).access;if(D.type!=="oauth")throw Error("not oauth");if(!D.access||(D.expires??0)<Date.now())try{return(await kG()).access}catch(M){if(NG(M))throw M;if(D.access)return D.access;throw Error("main token refresh failed")}return D.access},refreshFallback:async(D)=>{if(await L.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await d0.active()){let b=await _G(D);if(!b)throw Error(`no access token for ${D}`);return{token:b.token}}let M=await p0(),R=M?_b(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 n6.refreshAccount(R,I),f=fX(S);if(!f)throw Error(`no access token for ${D}`);return{token:f}},codexResponsesUrl:$,activeAccount:async(D)=>iH(C1(await m9.read(),F),D),logger:AG,now:Date.now,getWindow:()=>EG,getSustain:()=>CG});uX.set(D0,E4),U.set(D0,E4);function E1(D,M,R,I,S=!1){try{LL(D,M,R,I,S)}catch(f){X8.warn("quota push failed",{pid:process.pid,accountId:R??"main",error:e0(f)})}}function LL(D,M,R,I,S){if(Object.keys(D).length===0&&!S)return;let f=Date.now(),b=D,v={quota:b,refreshAfter:f+300000,checkedAt:f},n;if(R&&R!=="main"){let l=M?V6(M):null,d=l?U6(l):void 0,H0=U0.peekFallbackForPolicy(R)?.quota,F0=sN(b,H0);v={...v,quota:F0},U0.setFallback(R,v,M,S,d)}else{if(n=I,!n&&M){let H0=V6(M);n=H0?U6(H0):void 0}if(n&&R4&&n!==R4){X8.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:n,currentMainIdentity:R4});return}let l=U0.peekMainForPolicy(n)?.quota,d=sN(b,l);v={...v,quota:d},U0.setMain(M,v,n,S)}X8.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");l8.enqueue("machine-state","quota",()=>{let l=y6;return P8(U0,l,z0?l?.mainAccountId:n)})}function DL(D,M,R){let I=x8(L.routes().find((S)=>S.id===D)?.quota)??(D==="main"?U0.peekMainForPolicy()?.quota:U0.peekFallbackForPolicy(D)?.quota);return tZ(I,M,Date.now(),Wb,R)}let $2=new Map,S4=new Map;function wG(){if(!L.enrolled())return;l8.enqueue("machine-state","quota",()=>P8(U0,y6))}let S1=J.experimentalWebSockets?j9.createWebSocketFetch({httpFetch:fetch,rawWebSocket:p6().rawWebSocket,onQuota:(D,M,R,I)=>{let S=R?$2.get(R):void 0;if(S){L.recordSnapshot(S.id,D,!0,S.receipt).then(wG);return}E1(D,M,R,!R||R==="main"?I:void 0,!0)},onRateLimitReached:(D,M,R)=>{if(!M)X8.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:D});let I=M?$2.get(M):void 0,S=I?.id??M??"main",f=DL(S,D,R);if(U0.markRateLimited(S,f),I)S4.set(S,Math.max(S4.get(S)??0,f));else d0.markRateLimited(S,f);X8.debug("mid-stream rate limit mark",{pid:process.pid,accountId:S,window:D})}}):void 0;if(S1)W.push(S1),z=!0;let S6=eN();N=S6;async function P8(D,M,R=M?.mainAccountId){if(L.enrolled()){await xX(VV(L.snapshot()?.rows??[],new Set(L.routes().map((S)=>S.id)),M,Date.now()),S6,{canWrite:()=>L.enrolled()});return}let I=await d0.current();if(I.active){await xX(UV(I.rows,M,Date.now(),(S)=>(S==="main"?D.getMain():D.getFallback(S))?.quota?.resetCreditsAvailable),S6,{canWrite:()=>!L.enrolled()});return}if(!M)return;await xX(jL(D,M,Date.now(),R),S6,{canWrite:()=>!L.enrolled()})}let m9=BL(S6);m9.read(),_?.stop();let l8=VL({logger:T4,onWritten:()=>m9.refreshInBackground()});if(_=l8,O!==S6)F.clear(),O=S6;function pX(D,M,R,I,S,f,b=!1){let v={canWrite:()=>L.enrolled()===b},n={activeId:R,route:I,updatedAt:Date.now()};if(!D){l8.enqueue("routing:legacy","routing",()=>GL(n,S6,v));return}if(l8.enqueue(`routing:${D}`,"routing",()=>wX({sessionId:D,...n},S,S6,v)),!M||M===D)return;if(I==="sticky-balanced"){let z0=f.stickyAssignments?.[p8(M)]?.accountId,l=S===void 0||z0==="main"||S.some((d)=>d.enabled!==!1&&d.id===z0);if(!z0||!l)return;l8.enqueue(`routing:${M}`,"routing",()=>wX({sessionId:M,activeId:z0,route:I,updatedAt:Date.now()},S,S6,v));return}l8.enqueue(`routing:${M}`,"routing",()=>wX({sessionId:M,...n},S,S6,v))}q?.stopBackgroundRefresh(),q=n6;let I4=M0(V0());if(B=UL={accountStoragePath:I4.configPath,accountStatePath:I4.statePath,packageVersion:b9,quotaManager:U0,loadAccounts:b0,beginAccountLogin:x2,store:()=>H4(I4),migration:async()=>{if(await i7(I4,H4(I4))!==void 0)return{migrated:!0};let D=await(w.fence??(()=>K4({currentVersion:b9})))();return{migrated:!1,blockers:D.open?[]:D.blockers.map((M)=>({pid:M.pid,version:M.version}))}},afterWrite:()=>d0.load(),vault:L,resolveResetTarget:Vb({getAuth:h,refreshMainWithLease:mX,refreshFallbackAccount:(D,M)=>n6.refreshAccount(D,M),refreshPoolMainRow:(D,M)=>n6.refreshAccount(D,M,{asPoolMain:!0}),poolAccess:async(D)=>d0.rowAccess(D,await b0(M0(V0()))),loadAccounts:b0,accountStoragePath:V0(),accountStatePath:S$(V0()),now:Date.now}),...Ub(),cacheKeepManager:E4,setCacheKeepEnabled:(D)=>{TG=D},setCacheKeepSubagents:(D)=>{RG=D},setCacheKeepSustain:(D)=>{CG=D},setCacheKeepWindow:(D)=>{EG=D},clearStickyRouting:async(D)=>{let M=p8(D),R=F.delete(M);return l8.cancel(`pin:${M}`),await WL(D,S6)||R},getStickyRouting:async(D)=>YL(C1(await m9.read(),F),D),refreshSidebar:async()=>{let D=await b0(M0(V0()));await P8(U0,D)},refreshAllQuota:async()=>{if(await L.authority(),L.enrolled()){let D=await L.pollStale(0);return await P8(U0,y6),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([MG(),L.pollStale(0)]);return await P8(U0,y6),[...D,...M.map((R)=>({account:R.id,ok:R.ok,...R.error!==void 0?{error:R.error}:{}}))]}return Y4(t3())},refreshResetTargetQuota:async(D)=>{if(await L.authority(),L.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 MG([D]);return R??{account:D,ok:!1,error:"targeted quota refresh returned no result"}}return(await Y4(t3({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 rN(iV,D.dir,()=>nV({dir:D.dir,secureDir:D.secureDir,sweepRoot:D.sweepRoot,drain:IH,apply:async(R)=>{let I=C5(R);if(!I)throw Error("not an /openai apply request");return yH(B,I)}}));j.set(D.dir,M)}catch{}}async function I1(D,M,R,I,S="main",f){if(!R.trim())throw T4.warn("refusing to send a request with no access token",{account:S,accountId:I}),Error(tI);if(!f&&await L.authority()!=="local")return Response.json({error:{message:D1["vault-refused"]}},{status:400});let b=aN(D,M);if(b.delete("x-api-key"),b.delete("api-key"),b.set("authorization",`Bearer ${R}`),I)b.set("ChatGPT-Account-Id",I);b.set(j9.QUOTA_ACCOUNT_HEADER,S);let v=oN(b),n=v?Lb(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=Mb({init:{...M,headers:b},headers:b,metadata:n,installationID:Y,websocket:Boolean(S1&&z0.pathname.endsWith("/responses")),responsesLite:J.responsesLite??!1,dumpSessionID:v}).init,F0=TG,W6=new Headers(H0?.headers),W0=cH({enabled:F0,includeSubagents:RG,headers:W6,body:H0?.body});if(F0)AG.trace("cachekeep headers",{pid:process.pid,hasParent:W6.has("x-parent-session-id"),sessionKey:W0?.sessionKey,captured:Boolean(W0),affinity:W6.get("x-session-affinity"),opencodeSession:W6.get("x-opencode-session"),sessionId:W6.get("session-id")});if(S1&&z0.pathname.endsWith("/responses")){if(T4.debug("WS transport",{pid:process.pid,pathname:z0.pathname,accountId:S}),W0)E4.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 j1(await S1(l,H0),R,"event-stream")}catch(i0){throw K8(i0,R)}let P0=`vault-stream:${uI()}`;$2.set(P0,{id:S,receipt:f});let O8=new Headers(H0?.headers);O8.set(j9.QUOTA_ACCOUNT_HEADER,P0);let P6=()=>$2.delete(P0);try{let i0=await S1(l,{...H0,headers:O8});if(!i0.body)return P6(),i0;let d8=i0.body.getReader();return await j1(new Response(new ReadableStream({async pull(i8){try{let n8=await d8.read();if(n8.done)P6(),i8.close();else i8.enqueue(n8.value)}catch(n8){P6(),i8.error(K8(n8,R))}},cancel(i8){return P6(),d8.cancel(i8)}}),{status:i0.status,statusText:i0.statusText,headers:i0.headers}),R,"event-stream")}catch(i0){throw P6(),K8(i0,R)}}let R0=j9.withoutInternalHeaders(H0);if(typeof R0?.body!=="string")try{return await j1(await fetch(l,R0),R,"event-stream")}catch(P0){throw K8(P0,R)}if(W0)E4.track({sessionKey:W0.sessionKey,bodyText:W0.bodyText,accountId:S,isSubagent:W0.isSubagent,meta:{replayHeaders:W0.replayHeaders,chatgptAccountId:I,routingSessionId:v}});T4.debug("HTTP transport",{pid:process.pid,pathname:z0.pathname,accountId:S});try{let P0=await fetch(l,R0);return await q4({sessionID:v,transport:"http",phase:"http",bodyText:R0.body,accountId:S,url:l.toString(),method:R0.method,headers:R0.headers,status:P0.status}),await j1(P0,R,"event-stream")}catch(P0){throw await q4({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)}),K8(P0,R)}}function b4(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 FL(D){return U0.peekMainForPolicy(D)?.quota}function vG(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 k4(D,M,R,I,S){let f=vG(D,M),b=vG(R),v=I===S&&R!=null&&(D===void 0||b!==void 0&&(f===void 0||b>f));return{quota:v?R:D,quotaCheckedAt:v?b:f,source:v?"file":"memory"}}function yG(D,M,R,I,S){let f=D?.quota,b=k4(f,D?.checkedAt,M,I,S),v=b.source,n=b.quota;if(!$L(n,R))return{exhausted:!1};let z0=JL(n,R);if(!z0)return{exhausted:!1};return{exhausted:!0,source:v,...z0}}function hG(D,M){X8.debug("admission skip: exhausted account",{accountId:D,source:M.source,resetsAt:M.resetsAt})}function fG(D,M="killswitch",R,I){let S=Date.now(),f=I?I.main:U0.getMain()?.quota,b=I?I.fallbacks:(D?.accounts??[]).filter((d)=>d.enabled!==!1&&v0(d)).map((d)=>({accountId:d.id,quota:U0.getFallback(d.id)?.quota})),v=LW(f,b,S,D);if(M==="quota-unknown")v=XV;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 cX(D){let M=D?.resetCreditsAvailable;return typeof M==="number"&&Number.isFinite(M)?M:void 0}async function PL(D){let M=Q9(D.storage),R=Date.now(),I=U0.peekMainForPolicy(D.mainAccountIdentity),S=k4(I?.quota,I?.checkedAt,D.sidebarState.main.quota,D.sidebarState.main.mainAccountId,D.mainAccountIdentity),f=M?Z1(I?.quota,D.storage,void 0,R):void 0,b=D.mainUnavailable?[]:[{accountId:"main",wireAccountId:D.mainAccountIdentity,access:D.primaryAccess,keepwarmAccountKey:"main",quota:S.quota,quotaCheckedAt:S.quotaCheckedAt,reservePercent:s6(D.storage),configuredOrder:0,resetCreditsApplicable:cX(S.quota),killswitchPasses:f}],v=await n6.getUsableFallbackAccounts(D.storage);if(!D.storage)return b;for(let n of v){let z0=fX(n);if(!z0)continue;let l=D.sidebarState.fallbacks.find((W6)=>W6.id===n.id),d=U0.peekFallbackForPolicy(n.id,n.accountId),H0=k4(d?.quota,d?.checkedAt,l?.quota,l?.accountId,n.accountId),F0=M?Z1(d?.quota,D.storage,n.id,R):void 0;b.push({accountId:n.id,wireAccountId:n.accountId,access:z0,keepwarmAccountKey:n.id,fallback:n,quota:H0.quota,quotaCheckedAt:H0.quotaCheckedAt,reservePercent:s6(D.storage,n.id),configuredOrder:b.length,resetCreditsApplicable:cX(H0.quota),killswitchPasses:F0})}return b}function gG(D,M,R,I,S){let f=Q9(S)?D.killswitchPasses:void 0;if(D.accountId==="main"){let z0=U0.peekMainForPolicy(D.wireAccountId),l=k4(z0?.quota,z0?.checkedAt,M.main.quota,M.main.mainAccountId,D.wireAccountId);return ZY({quota:l.quota,quotaCheckedAt:l.quotaCheckedAt,status:R,now:I,killswitchPasses:f})}let b=M.fallbacks.find((z0)=>z0.id===D.accountId),v=U0.peekFallbackForPolicy(D.accountId,D.wireAccountId),n=k4(v?.quota,v?.checkedAt,b?.quota,b?.accountId,D.wireAccountId);return ZY({quota:n.quota,quotaCheckedAt:n.quotaCheckedAt,status:R,now:I,killswitchPasses:f})}function OL(D){return D.accountId==="main"?"main":D.keepwarmAccountKey}function mG(D){return U0.isRateLimited(OL(D))}function lX(D){let M=D.candidates.filter((f)=>!mG(f)),R=new Map(M.map((f)=>[f.accountId,f])),I=new Set(D.excludeAccountIds),S=uG({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 b=M.filter((v)=>!I.has(v.accountId));if(b.length===0)return;return RV({candidates:b,pendingBytes:f,requestBytes:D.requestBytes,now:D.now,onEmptyWeightedSet:()=>{F8.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return S?R.get(S.accountId):void 0}function uG(D){let M=void 0,R=D.validPinnedAccountIds,I=zL(C1(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 b=D.select(f);if(!b)return;return M={accountId:b.accountId,source:b.source,pendingBytes:f.get(b.accountId)??0},b}}),S=I.assignment;if(!D.persist)return S;if(M&&S?.accountId===M.accountId)F8.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:p8(D.sessionId),accountId:M.accountId,source:M.source,requestBytes:D.requestBytes,pendingBytes:M.pendingBytes});if(S&&I.next!==void 0){let f=p8(D.sessionId),b=HL(F,f,S);l8.enqueue(`pin:${f}`,"sticky-pin",async()=>{await ZL({sessionId:D.sessionId,assignment:S,validPinnedAccountIds:R},S6),b.persistedAt=Date.now()})}return S}async function ML(D,M){let R=await n6.getUsableFallbackAccounts(D),I=[];if(!D)return{current:[],retained:[],skipped:[]};for(let l of R){let d=fX(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=Q9(D)?S.filter((l)=>Z1(U0.peekFallbackForPolicy(l.quotaAccountId,l.accountId)?.quota,D,l.quotaAccountId,Date.now())):S,b=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=b.get(l.quotaAccountId),H0=yG(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 pG(D,M){if(D.retained.length===0&&!M)return D.current;for(let{candidate:R,decision:I}of D.skipped)hG(R.quotaAccountId,I);return D.retained}function cG(D,M){try{let R=o9(D.headers);E1(R,M.access,M.quotaAccountId,void 0,d1(D.headers))}catch{}}async function _L(D,M,R,I){for(let S of I){let f;try{f=await I1(D,M,S.access,S.accountId,S.keepwarmAccountKey)}catch(b){if((b instanceof Error||b instanceof DOMException)&&b.name==="AbortError")throw b;if(M?.signal?.aborted)throw b;throw F8.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:S.quotaAccountId}),b}if(!B3(f.status,R))return n6.markUsed(S.fallback),{response:f,accessToken:S.access,quotaAccountId:S.quotaAccountId,activeId:S.keepwarmAccountKey};cG(f,S),f.body?.cancel().catch(()=>{})}return}async function AL(D,M,R,I,S){if(!b4(D,M))return{response:R};if(!S.length)return{response:R};let f=R,b;for(let v of S){let n;try{n=await I1(D,M,v.access,v.accountId,v.keepwarmAccountKey)}catch(z0){if((z0 instanceof Error||z0 instanceof DOMException)&&z0.name==="AbortError")throw z0;if(M?.signal?.aborted)throw z0;return F8.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:v.quotaAccountId}),{response:f,...b}}if(f.body?.cancel().catch(()=>{}),f=n,b={accessToken:v.access,accountId:v.quotaAccountId},!B3(n.status,I))return n6.markUsed(v.fallback),{response:n,...b};cG(n,v)}return{response:f,...b}}if(n0){let D=[];for(let M of n0.accounts)if(v0(M))D.push(M);U0.seedFallbacksFromAccounts(D)}if(!FG)if(FG=!0,P8(U0,n0).catch(()=>{}),P.then(()=>L.enrolled()?P8(U0,y6):void 0).catch(()=>{}),!L.enrolled()&&!await d0.active())vX=Y4(t3({respectBackoff:!0})).catch((D)=>X8.warn("boot quota seed failed",{pid:process.pid,error:e0(D)}));else vX=Promise.resolve();m.start(async()=>{if(await L.authority(),L.enrolled()){await P8(U0,y6);return}if(await d0.active()){let R=await uH(d0,await b0(M0(V0())),()=>u$(V0()));if(R.length>0)await P8(U0,y6);let I=R.filter((S)=>!S.ok);if(I.length>0)X8.warn("background pool quota poll completed with failures",{pid:process.pid,failures:I});return}let M=(await gH(t3({readSidebarState:async()=>(await m9.read()).state}))).filter((R)=>!R.ok);if(M.length>0)X8.warn("background quota refresh completed with failures",{pid:process.pid,failures:M})},(D)=>{X8.warn("background quota refresh failed",{pid:process.pid,error:D instanceof Error?D.message:String(D)})});async function dX(D,M,R,I,S,f){let b=R?.routing?.mode??"main-first",v=L.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 p7(M0(V0()),z0);if(f===C4)R4=n?.identity;let H0=await m9.get(),{response:F0,servedId:W6}=await HV({source:d0,...v?{vault:{routes:()=>L.routes(),awaitRoster:async()=>{await E3(P,s$)},noRouteCause:()=>iW(L),send:(W0,R0)=>L.send(W0,R0,{site:"model",...M?.signal?{signal:M.signal}:{}}),requestReading:(W0)=>L.requestReading(W0),rateLimitMarks:()=>{for(let[W0,R0]of S4)if(R0<=Date.now())S4.delete(W0);return S4}}}:{},storage:R,mode:b,sessionId:I,body:typeof M?.body==="string"?M.body:void 0,replayable:b4(D,M),now:Date.now,send:(W0,R0,P0)=>I1(D,M,R0,W0.identity,W0.id,P0),recordQuota:(W0,R0,P0,O8)=>{try{let P6=o9(W0.headers),i0=d1(W0.headers);if(!R0.row){if(O8)L.recordSnapshot(R0.id,P6,i0,O8).then(wG);return}E1(P6,P0,R0.id==="main"?void 0:R0.id,R0.id==="main"?R0.identity:void 0,i0)}catch{}},placePin:(W0)=>uG({...W0,sidebarSnapshot:H0}),blocked:(W0,R0,P0)=>{if(W0.reason==="no-credential"){if(d&&!$Y(P0))throw Error(V4);return new Response(D1[$Y(P0)?P0:l?"missing-main":P0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return fG(R,W0.reason,W0.resetAtMs,R0)},resetCredits:(W0)=>cX(W0==="main"?U0.peekMainForPolicy(n?.identity)?.quota:U0.peekFallbackForPolicy(W0)?.quota),isAbort:(W0)=>(W0 instanceof Error||W0 instanceof DOMException)&&W0.name==="AbortError"||Boolean(M?.signal?.aborted),log:F8});return pX(I,S,W6,b,v?L.routes().map((W0)=>({id:W0.id})):R?.accounts,C1(H0,F),v),F0}return Z=!0,{apiKey:Xb,async fetch(D,M){let R=await L.authority(),I=aN(D,M),S=oN(I),f=I.get("x-parent-session-id")?.trim()||void 0,b=await p0();if(R!=="local")return M=await LG(D,M),dX(D,M,b,S,f,++C4);let v=await h();if(await L.authority()!=="local")return M=await LG(D,M),dX(D,M,b,S,f,++C4);let n=++C4;if(v.type!=="oauth")return I.delete(hX),fetch(D,{...M,headers:I});M=await LG(D,M);let z0=(await d0.current()).active;if(C6(v)&&z0)return dX(D,M,b,S,f,n);if(z0)L.assertHostSlot(v);let l="",d=!1,H0,F0=C6(v);if(G0?.migrated()&&!F0&&v.refresh?.trim()&&A3(v).kind==="real")G0.noticeRealSlot(v.refresh);let W6=async(C0=b)=>{if(F0=!0,H0=await IG(C0),H0)l=H0.token;else l="",d=!0,F8.warn("main account in the pool has no usable token",{pid:process.pid})};if(F0)await W6();else if(T0(v))d=!0;else{if(!v.access||(v.expires??0)<Date.now()){r3.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(v.access),expiresInMs:v.expires?v.expires-Date.now():void 0});try{let C0=await mX();v.access=C0.access,v.refresh=C0.refresh,v.expires=C0.expires}catch(C0){if(NG(C0))throw C0;if(C0 instanceof L1)await W6(await b0(M0(V0())))}}if(!F0)l=v.access??""}let W0=F0?sJ(b):b,R0=v,P0=H0?.account.accountId??(F0?void 0:R0.accountId)??(l?U6(V6(l)??{}):void 0);if(n===C4)R4=P0;let O8=b?.routing?.mode??"main-first",P6=await m9.get(),i0=P6.state;if(O8==="sticky-balanced"&&S&&b4(D,M)&&typeof M?.body==="string"){let C0=Buffer.byteLength(M.body,"utf8"),$6=await PL({storage:W0,sidebarState:i0,primaryAccess:l,mainAccountIdentity:P0,mainUnavailable:d}),o0=lX({sessionId:S,requestBytes:C0,candidates:$6,sidebarSnapshot:P6,now:Date.now()});if(o0){let aG=mG(o0)?{action:"migrate",reason:"exhausted"}:gG(o0,i0,void 0,Date.now(),b);if(aG.action==="migrate"){let h6=lX({sessionId:S,requestBytes:C0,candidates:$6,sidebarSnapshot:P6,excludeAccountIds:[o0.accountId],now:Date.now()});if(h6)F8.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:p8(S),fromAccountId:o0.accountId,toAccountId:h6.accountId,reason:aG.reason}),o0=h6}let M8=await I1(D,M,o0.access,o0.wireAccountId,o0.keepwarmAccountKey),oG=(h6,u9)=>{try{let TL=o9(h6.headers);E1(TL,u9.access,u9.accountId==="main"?void 0:u9.accountId,u9.accountId==="main"?u9.wireAccountId:void 0,d1(h6.headers))}catch{}};oG(M8,o0);let rG=gG(o0,i0,M8.status,Date.now(),b);if((M8.status===401||M8.status===403||M8.status===429)&&rG.action==="migrate"){let h6=lX({sessionId:S,requestBytes:C0,candidates:$6,sidebarSnapshot:P6,excludeAccountIds:[o0.accountId],now:Date.now()});if(h6){F8.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:p8(S),fromAccountId:o0.accountId,toAccountId:h6.accountId,reason:rG.reason});let u9=M8;M8=await I1(D,M,h6.access,h6.wireAccountId,h6.keepwarmAccountKey),u9.body?.cancel().catch(()=>{}),o0=h6,oG(M8,o0)}}if(o0.fallback&&!B3(M8.status,b))n6.markUsed(o0.fallback);return pX(S,f,o0.accountId,O8,b?.accounts,C1(P6,F)),M8}}let d8=yG(U0.peekMainForPolicy(P0),i0.main.quota,Date.now(),i0.main.mainAccountId,P0),i8=Q9(b)&&!Z1(FL(P0),b,void 0,Date.now()),n8=U0.isRateLimited("main"),lG,iX=()=>{return lG??=ML(W0,i0),lG},s8,b1,dG=!1,Y2;if(O8==="fallback-first"&&b4(D,M)){dG=!0;let C0=await iX();Y2=pG(C0,!i8&&!n8&&!d8.exhausted);let $6=await _L(D,M,b,Y2);if($6)s8=$6.response,b1={accessToken:$6.accessToken,accountId:$6.quotaAccountId,activeId:$6.activeId}}if(!s8){let C0=d8.exhausted&&b4(D,M)&&(await iX()).retained.length>0;if(i8||n8||C0){let $6=i8?"killswitch":n8?"mid-stream-rate-limit":"quota-exhausted";if($6==="quota-exhausted"&&d8.exhausted)hG("main",d8);F8.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:$6}),s8=fG(b,$6,$6==="quota-exhausted"&&d8.exhausted?d8.resetAtMs:n8?U0.rateLimitedUntil("main"):void 0)}else s8=d?new Response(null,{status:401}):await I1(D,M,l,P0,"main")}let nX=Boolean(b1),x4=s8,iG=b1?.accessToken??l,nG=b1?.accountId,sG=b1?.activeId??"main";if(!b1&&!dG&&B3(s8.status,b)){F8.debug("reactive fallback triggered",{pid:process.pid,status:s8.status}),Y2??=pG(await iX(),!1);let C0=await AL(D,M,s8,b,Y2),$6=C0.response;if($6!==s8){if(nX=!0,x4=$6,iG=C0.accessToken??l,nG=C0.accountId,C0.accountId)sG=C0.accountId}}if(F0&&d&&!nX&&await p7(M0(V0()),await h()))throw Error(V4);try{let C0=o9(x4.headers);if(nX)E1(C0,iG,nG,void 0,d1(x4.headers));else E1(C0,l,void 0,P0,d1(x4.headers))}catch{}return pX(S,f,sG,O8,b?.accounts,C1(P6,F)),x4}}},methods:u0},"chat.headers":async(h,o)=>{if(h.model.providerID!=="openai")return;if(o.headers.originator="opencode",o.headers["User-Agent"]=`${b2(b9)} (${jG.platform()} ${jG.release()}; ${jG.arch()})`,o.headers["session-id"]=h.sessionID,Z)o.headers[hX]=h.agent;if(z&&h.agent==="title")o.headers[j9.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??{},[u6]:{template:u6,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!==u6)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."),nN();let o=await vH(B,h.sessionID);if(bH(h.sessionID))o7(o,h.sessionID);else await t(h.sessionID,hH(o.menu));nN()}}}var Ib=async(X)=>{let J=p6();return Sb(X,{codexApiEndpoint:J.codexApiEndpoint,experimentalWebSockets:J.webSockets,responsesLite:J.responsesLite})},Tn={id:"cortexkit-openai-auth",server:Ib};
222
- export{tX as c,CL as d,V6 as e,U6 as f,Z8 as g,x2 as h,o9 as i,d1 as j,Rz as k,X3 as l,T0 as m,Y3 as n,I8 as o,tZ as p,b0 as q,H3 as r,Q9 as s,s6 as t,Z1 as u,U8 as v,S9 as w,x8 as x,lW as y,Y$ as z,iW as A,S7 as B,G4 as C,K8 as D,vM as E,j1 as F,V0 as G,p6 as H,M0 as I,G_ as J,p7 as K,c7 as L,l7 as M,f8 as N,B4 as O,d7 as P,h$ as Q,V4 as R,K4 as S,b9 as T,s$ as U,a$ as V,E3 as W,o$ as X,tH as Y,c6 as Z,JV as _,YV as $,e$ as aa,QV as ba,zV as ca,gA as da,LV as ea,PV as fa,a3 as ga,AN as ha,sI as ia,aI as ja,oI as ka,rI as la,tI as ma,eI as na,DG as oa,$b as pa,Pn as qa,Gb as ra,Qb as sa,On as ta,Mn as ua,OG as va,D6 as wa,Vb as xa,Ub as ya,_n as za,qb as Aa,_b as Ba,sN as Ca,jL as Da,An as Ea,oN as Fa,Ab as Ga,Cb as Ha,Sb as Ia,Ib as Ja,Tn as Ka};
220
+ `)),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=TI(t),m9.debug("response created",{...q,responseID:F,previousResponseID:N,hasContinuation:N!==void 0});if(!kq(t.type))W=!0,RI(t,L);if(J0("idle timeout waiting for websocket"),t.type==="response.completed"||t.type==="response.done"){Q=!0,OI(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 y6(e0(a),{cause:a}))}function m(a){if(Q)return;let u0=a.code===1009,t=new y6(u0?xq:wq("WebSocket closed before response.completed",a.code,a.reason),{retryable:!u0});if(u0)m9.warn("websocket peer refused the request size",{...q,requestBytes:z,reason:a.reason.toString()});X0(u0?Iq(t):t)}function c0(){let a=UG(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?.(_I(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;k(new y6(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 PI(X,J){if(X.type!=="response.output_item.done")return;if(!s(X.item))return;bq(X.item,J)}function OI(X,J){let $=X.response;if(!s($)||!Array.isArray($.output))return;for(let Y of $.output)if(s(Y))bq(Y,J)}function bq(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 MI(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 r3(X){if(typeof X==="string")try{return r3(JSON.parse(X))}catch{return}if(!s(X))return;let J=r3(X.cause);if(J)return J;let $=r3(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 _I(X){if(jG(X))return X;if(X instanceof Error)return X;return new DOMException(typeof X==="string"?X:"Aborted","AbortError")}function UG(X){let J=X?.reason;if(jG(J))return J;if(AI(J))return J;return new DOMException(J instanceof Error?J.message:"Aborted","AbortError")}function AI(X){return X instanceof Error&&(X.name==="ProviderHeaderTimeoutError"||X.name==="ProviderResponseStreamError")}function TI(X){let J=X.response;if(!s(J))return;return typeof J.id==="string"?J.id:void 0}function RI(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(Rq($)&&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(Rq($)&&typeof $?.id==="string"&&J.reasoningItemIds.has($.id))return;break}J.other=!0}function Rq(X){if(X?.type!=="reasoning")return!1;let J=($)=>$===void 0||$===null||Array.isArray($)&&$.length===0;return J(X.summary)&&J(X.content)}var CI={type:"response.completed",response:{status:"completed",incomplete_details:null,usage:{input_tokens:0,output_tokens:0,total_tokens:0}}};function kq(X){return X==="response.created"||X==="response.in_progress"||X.startsWith("codex.")}var KG="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.",xq="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 wq(X,J,$){let Y=[`code ${J}`];if($.length>0)Y.push($.toString());return`${X} (${Y.join(": ")})`}var qG="x-opencode-title",xX="x-openai-auth-quota-account",NG=new Set([qG,x9,xX,"x-opencode-session"]),SI=15000,II=300000,bI=3300000,vq="websocket_connection_limit_reached";function kI(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 EI("sha256").update(Y).digest("hex").slice(0,12)}function xI(X){let J=X?.httpFetch??globalThis.fetch,$=new Map,Y=X?.connectTimeout??SI,G=X?.idleTimeout??II,Q=X?.maxConnectionAge??bI,z=X?.streamRetries??5,Z=X?.firstEventGraceMs??250,W=X?.rawWebSocket??!1,B=X?.onQuota,H=X?.onRateLimitReached,U=setInterval(()=>q(),Math.min(G,60000));if(typeof U==="object"&&"unref"in U&&typeof U.unref==="function")U.unref();function j(_,C,L,P){if(!C||!L)return L;LG(_,yq(C),void 0,P);let A=new Headers(L.headers),T=A.get("x-codex-turn-metadata");if(!T)return L;let k=lq(T,_.turnID,_.turnStartedAt);if(!k)return L;return A.set("x-codex-turn-metadata",k),{...L,headers:A}}async function N(_,C){let L=_ instanceof URL?_.toString():typeof _==="string"?_:_.url,P=L6.normalizeHeaders(C?.headers),A=aq(C),T=$X(A);if(C?.method!=="POST"||!new URL(L).pathname.endsWith("/responses"))return J(_,T);let k=(()=>{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(!k?.stream)return J(_,T);if(P[qG]==="true")return J(_,T);let p=P[x9]??P["x-session-affinity"]??P["session-id"],i=p;if(!p)return J(_,T);let X0=L6.normalizeHeaders(A?.headers),w=kI(X0),J0=`${p}:${w}:conversation`,G0=typeof P[xX]==="string"?P[xX]: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=yq(k),m0;if(m.fallback)return J(_,j(m,k,T,m0));if(m.busy)return J(_,j(m,k,T,m0));m.busy=!0,m.lastUsedAt=Date.now();try{m0=A4(m,c0);let r=L6.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?pI(r):r;if(m.socket=await hI(m,X?.url??L,h,Y,Q,W,C?.signal),dI(m,c0,m0))await fI(m,c0,G,{signal:C?.signal??void 0,sessionID:i,url:X?.url??L,headers:A?.headers,onRateLimitReached:L0});let o=()=>{},e=()=>{},c=new Promise((p0,F8)=>{o=p0,e=F8}),D0=lI(m,c0,m0),l0=t3(cq(m,D0,c0,m0)),i6=typeof l0.previous_response_id==="string";await q4({sessionID:i,transport:"websocket",phase:"main",bodyText:()=>JSON.stringify(l0),url:X?.url??L,method:A?.method,headers:A?.headers});let n0=L6.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,F8)=>{let T4=gq(p0);F1({component:"ws-pool",event:"main_completed",sessionID:i,responseID:fq(p0),usage:T4}),pq(m,c0,p0,F8,i6,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,j9(m)},onConnectionInvalid:(p0)=>{if(m.busy=!1,m.lastUsedAt=Date.now(),L6.isOversizedFrame(p0))m.fallback=!0;if(!m.fallback)K(m);m.continuation=void 0,j9(m),o(!1)},onAbort:(p0)=>{m.busy=!1,m.lastUsedAt=Date.now(),m.streamFailures=0,m.continuation=void 0,j9(m),e(p0)},onRetryableTerminal:async(p0)=>{let F8=hq(p0);if(!F8)return;throw m.fallback=!0,F8}}),F6=await wI(c,Z);if(F6!==!1){if(F6===!0||F6.status<200||F6.status>599)return n0;return new Response(F6.body,{status:F6.status,headers:{"content-type":"application/json",...F6.headers}})}let h6=()=>J(_,j(m,k,T,m0));if(!m.fallback)return vI(n0,h6);return h6()}catch(r){if(m.busy=!1,m.lastUsedAt=Date.now(),L6.isAbortError(r))throw m.streamFailures=0,m.continuation=void 0,j9(m),r;let a=L6.parseRateLimitSignal(r);if(a)L0?.(a.window,a.resetAt);if(L6.isUpgradeFailure(r)&&!W)m.fallback=!0;if(K(m),m.continuation=void 0,j9(m),m.fallback)return J(_,j(m,k,T,m0));return yI(new y6(r instanceof Error?r.message:String(r),{cause:r}))}}function K(_){if(_.streamFailures++,_.streamFailures>z)_.fallback=!0}function q(){let _=Date.now();for(let[C,L]of $){if(L.busy)continue;if(_-L.lastUsedAt<G)continue;j9(L),$.delete(C)}}function F(){clearInterval(U);for(let _ of $.values())j9(_);$.clear()}function O(_){let C=`${_}:`;for(let[L,P]of $){if(!L.startsWith(C))continue;j9(P),$.delete(L)}}return Object.assign(N,{close:F,remove:O})}function hq(X){if(X.type!=="error"||!s(X.error)||X.error.code!==vq)return;return Error(typeof X.error.message==="string"?X.error.message:vq)}async function wI(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 vI(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||!L6.isOversizedFrame(W)){Q.error(W);return}try{let B=await J();if(!B.ok){Q.error(new y6(`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 yI(X){return new Response(new ReadableStream({start(J){J.error(X)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function hI(X,J,$,Y,G,Q,z){if(X.socket?.readyState===WebSocket.OPEN&&X.connectedAt&&Date.now()-X.connectedAt<G)return X.socket;j9(X);let Z=await L6.connectResponsesWebSocket({url:L6.toWebSocketUrl(J),headers:$,timeout:Y,rawWebSocket:Q,signal:z??void 0});return X.connectedAt=Date.now(),Z}function j9(X){if(X.socket)X.socket.close(),X.socket=void 0;X.connectedAt=void 0,X.continuation=void 0}async function fI(X,J,$,Y){if(!X.socket||!Array.isArray(J.input)||J.input.length===0)return;let G=mI(J);await q4({sessionID:Y.sessionID,transport:"websocket",phase:"prewarm",bodyText:()=>JSON.stringify(G),url:Y.url,method:"POST",headers:Y.headers});let Q=L6.streamResponsesWebSocket({socket:X.socket,body:G,sessionID:Y.sessionID,idleTimeout:$,signal:Y.signal,onRateLimitReached:Y.onRateLimitReached,onComplete:(z,Z)=>{F1({component:"ws-pool",event:"prewarm_completed",sessionID:Y.sessionID,responseID:fq(z),usage:gq(z)}),pq(X,G,z,Z,!1,{input:P1([]),signature:nq(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=hq(z);if(!Z)return;throw X.fallback=!0,Z}});await gI(Q)}function fq(X){let J=X.response;if(!s(J))return;return typeof J.id==="string"?J.id:void 0}function gq(X){let J=X.response;if(!s(J))return;return s(J.usage)?J.usage:void 0}async function gI(X){let J=X.body?.getReader();if(!J)return;while(!0)if((await J.read()).done)return}function mI(X){return t3({...X,generate:!1,input:[],previous_response_id:void 0,client_metadata:uI(X.client_metadata)})}function mq(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 uI(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":mq(J),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return X}}function pI(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":mq($)}}catch{return X}}var uq=["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 yq(X){let J={...X};if(Array.isArray(X.input))J.input=X.input.map(cI);return J}function t3(X){let J={};for(let $ of uq)if($ in X)J[$]=X[$];for(let $ of Object.keys(X))if(!($ in J))J[$]=X[$];return J}function cI(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 pq(X,J,$,Y,G,Q=A4(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:w3(Q.input),finalizedCallIds:W}}function LG(X,J,$=J,Y=A4(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?v3(dq(Y,X.turnInput),Y.input):void 0,W=Z===void 0?G:Q.slice(Z);if(W.length>0&&W.some(iq)||!X.turnID)X.turnID=O1(),X.turnStartedAt=Date.now();X.turnInput=Q.slice(),Y.priorInputs.set(X.turnInput,Y.input),X.turnSignature=z,X.turnCanonical=w3(Y.input)}function cq(X,J,$=J,Y=A4(X,{...$,input:Array.isArray($.input)?$.input:J.input})){LG(X,J,$,Y);let G=J.client_metadata;if(!s(G)||typeof G["x-codex-turn-metadata"]!=="string")return J;let Q=lq(G["x-codex-turn-metadata"],X.turnID,X.turnStartedAt);if(!Q)return J;return{...J,client_metadata:{...G,"x-codex-turn-metadata":Q}}}function lq(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 A4(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=P1($,X.turnCanonical??X.continuation?.canonical);return Y.set($,G),{input:G,signature:nq(J),priorInputs:Y}}function dq(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}$??=P1(J),X.priorInputs.set(J,$)}return $}function lI(X,J,$=A4(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(!sq(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=iI(G,X.continuation.finalizedCallIds);if(Q.length===0)return J;return{...J,previous_response_id:X.continuation.responseID,input:Q}}function dI(X,J,$=A4(X,J)){let Y=Array.isArray(J.input)?J.input:void 0;if(!X.continuation)return!0;if(!Y)return!1;if(!sq(X.continuation,$))return!0;return Y.slice(X.continuation.input.length).some(iq)}function iq(X){if(!s(X))return!1;if(!(X.type==="message"||("role"in X)))return!1;return X.role==="user"||X.role==="developer"}function iI(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 nq(X){return F4(nI(Object.fromEntries(Object.entries(X).filter(([J])=>J!=="input"&&J!=="stream"&&J!=="background"&&J!=="previous_response_id"&&J!=="generate"))))}function nI(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 sq(X,J){if(X.input.length>=J.input.texts.length)return!1;return v3(dq(J,X.input),J.input)!==void 0}function aq(X){if(!X?.headers)return X;if(X.headers instanceof Headers){let J=new Headers(X.headers);for(let $ of NG)J.delete($);return{...X,headers:J}}if(Array.isArray(X.headers))return{...X,headers:X.headers.filter((J)=>!NG.has(J[0].toLowerCase()))};return{...X,headers:Object.fromEntries(Object.entries(X.headers).filter(([J])=>!NG.has(J.toLowerCase())))}}var $b=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),Yb=new Set(["gpt-5.6","gpt-6","gpt-6.1"]);function Gb(X){if($b.has(X))return!0;if(Yb.has(X))return!1;let $=X.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1];return $?parseFloat($)>5.4:!1}function Qb(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 zb="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.",Zb=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"]),Wb="opencode-oauth-dummy-key",Bb="terminal_resize_reflow",MG="0.159.0",Hb=`codex_exec/${MG} (Debian 12.0.0; aarch64) unknown (codex_exec; ${MG})`,Vb="seccomp",hn=()=>g8,Ub=120000,Kb=90000,jb=4000,oq=50,rq=3,Nb=25,qb=60000,Lb="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",_G=!1,hX;function fn(){return hX}function gn(){_G=!1,hX=void 0}var tq=Z0("models"),eq=!1,XL=!1;class TG 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 D6 extends Error{code;constructor(X,J){super(J);this.name="ResetTargetResolutionError",this.code=X}}function FG(X,J,$,Y){let G=($?.refresh?.refreshBeforeExpiryMinutes??240)*60000;return!X||!J||J-Y<=G}function Db(X,J){let $=X==="main",Y=J.row,G=()=>new D6("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 D6("unknown_account",`Fallback account ${X} was not found.`)}if(!Y.enabled)throw new D6("disabled_account",`${$?"Main":"Fallback"} account ${X} is disabled.`);if(Y.type!=="oauth")throw new D6("non_oauth_account",`${$?"Main":"Fallback"} account ${X} is not an OAuth account.`);if(!J.token)throw G();let Q=V6(J.token);return{accountKey:X,label:$?"Main account":Y.label??X,accessToken:J.token,chatgptAccountId:Y.identity??(Q?U6(Q):void 0)}}function Fb(X){async function J(){let $=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath}),Y=Z9($);if(!$||!Y||T0(Y))throw new D6("token_unavailable","Main OpenAI account has no usable access token.");let G=Y;if(FG(G.access,G.expires,$,X.now()))G=await(X.refreshPoolMainRow??X.refreshFallbackAccount)(G,$);if(!G.access)throw new D6("token_unavailable","Main OpenAI account has no usable access token.");let Q=V6(G.access);return{accountKey:"main",label:"Main account",accessToken:G.access,chatgptAccountId:G.accountId??(Q?U6(Q):void 0)}}return async($)=>{let Y=await X.poolAccess?.($);if(Y)return Db($,Y);if($==="main"){let H=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath}),U=await X.getAuth();if(C6(U))return J();if(U.type!=="oauth")throw new D6("non_oauth_account","Main OpenAI account is not authenticated with OAuth.");if(FG(U.access,U.expires,H,X.now()))try{U={type:"oauth",...await X.refreshMainWithLease()}}catch(q){if(q instanceof L1)return J();throw q}if(!U.access)throw new D6("token_unavailable","Main OpenAI account has no usable access token.");let j=V6(U.access),N=j?U6(j):void 0,K=await X.loadAccounts({configPath:X.accountStoragePath,statePath:X.accountStatePath});return{accountKey:$,label:"Main account",accessToken:U.access,chatgptAccountId:N??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 D6("unknown_account",`Fallback account ${$} was not found.`);if(Q.enabled===!1)throw new D6("disabled_account",`Fallback account ${$} is disabled.`);if(!v0(Q))throw new D6("non_oauth_account",`Fallback account ${$} is not an OAuth account.`);let z=()=>new D6("token_unavailable",`Fallback account ${$} has no usable access token.`);if(T0(Q))throw z();let Z=Q;if(FG(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 D6("unknown_account",`Fallback account ${$} was not found.`);if(B.enabled===!1)throw new D6("disabled_account",`Fallback account ${$} is disabled.`);if(!v0(B))throw new D6("non_oauth_account",`Fallback account ${$} is not an OAuth account.`);return{accountKey:$,label:Z.label??$,accessToken:Z.access,chatgptAccountId:B.accountId}}}function Pb(){return{fetchImpl:fetch,now:Date.now,randomUUID:()=>crypto.randomUUID()}}function PG(X){return X instanceof TG}function JL(){throw Error(Lb)}async function Ob(X,J={}){let $=M0(V0());if(u$($.configPath)){await K1(V4($),J.holdsMainRefreshLock?void 0:B9($),(Y)=>{if(J.canWrite&&!J.canWrite())throw Error(D1["vault-refused"]);X(Y)});return}await F7((Y)=>{return X(Y),Y},$,{canWrite:J.canWrite})}var PL=null;function mn(){return PL}function Mb(X){return Math.floor(Math.random()*X)}var _b=!0;function Ab(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 Tb(X,J,$){let Y=X.get(J);if(Y)return Y;let G=O1(),Q={threadID:G,turnID:O1(),windowID:`${G}:0`};return X.set(J,Q),$?.(),Q}function OL(){return Jb(y7(),"openai-auth-sessions.json")}function Rb(){let X=new Map;try{let J=JSON.parse(rI(OL(),"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:O1(),windowID:`${Y.threadID}:0`})}}catch{}return X}function Cb(X){let J=OL(),$=`${J}.tmp-${process.pid}`;try{oI(y7(),{recursive:!0});let Y={version:1,sessions:Object.fromEntries([...X.entries()].map(([G,Q])=>[G,{threadID:Q.threadID}]))};Xb($,`${JSON.stringify(Y,null,2)}
221
+ `,"utf8"),tI($,J)}catch{}}function fX(X,J){return s(X)&&(X.type==="message"||("role"in X))&&X.role===J}function Eb(X,J,$){if(!X.input)return J.length>0;let Y=X.canonicalInput??P1(X.input);if(v3(Y,$)===void 0)return!0;return J.slice(X.input.length).some((Q)=>fX(Q,"user")||fX(Q,"developer"))}function Sb(X,J){let $=Array.isArray(J?.input)?J.input:void 0,Y=$?P1($,X.canonicalInput):void 0;if($&&Y&&(Eb(X,$,Y)||!X.turnID))X.turnID=O1(),X.turnStartedAt=Date.now();else if(!X.turnStartedAt)X.turnStartedAt=Date.now();if($&&Y)X.input=$.slice(),X.canonicalInput=w3(Y)}function Ib(X){let J=X.headers.get(gX);if(X.headers.delete(gX),!X.metadata)return{init:X.init};let $=Ab(X.init?.body);if(!X.websocket)Sb(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:Vb,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",Bb),X.headers.set("x-codex-turn-metadata",Y),X.headers.set("user-agent",Hb),X.headers.set("version",MG),X.dumpSessionID)X.headers.set(x9,X.dumpSessionID);let G=$;if(!G)return{init:X.init};let Q=X.responsesLite&&typeof G.model==="string"&&Zb.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(yb);if(wb(G,X.metadata,J),Q)vb(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(t3(G))}}}function bb(X,J){return X.find(($)=>$.enabled!==!1&&v0($)&&($.id===J||$.accountId===J))}function $L(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 wX(X,J){if(!X)return X;if(typeof X.checkedAt==="number"&&Number.isFinite(X.checkedAt))return X;return{...X,checkedAt:J}}function ML(X,J,$=Date.now(),Y=J.mainAccountId){let G=X.getMain(),Q=G?.quota;return{main:{quota:Q?{...Q,checkedAt:G.checkedAt,primary:wX(Q.primary,G.checkedAt),secondary:wX(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:wX(W.primary,Z.checkedAt),secondary:wX(W.secondary,Z.checkedAt)}:null,killed:!1,enabled:!0,...W?.resetCreditsAvailable!==void 0?{resetCredits:W.resetCreditsAvailable}:{}}}),route:J.routing?.mode??"main-first",lastUpdated:$}}function un(X,J,$,Y=Date.now()){return{...ML(X,J,Y),activeId:$}}function YL(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 OG(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 GL(X){return X.get("x-session-affinity")??X.get("x-opencode-session")??X.get("x-session-id")??X.get("session-id")??void 0}function AG(X){if(Array.isArray(X)){let $=X;for(let Y=0;Y<X.length;Y++){let G=AG(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=AG(X[$]);if(Y===X[$])continue;if(J===X)J={...X};J[$]=Y}return J}var kb=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),gX="x-openai-auth-agent",xb=new Set(["title","compaction","summary"]);function wb(X,J,$){if($!==null&&xb.has($))return;let Y=typeof X.model==="string"?X.model:"";if(!kb.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)=>sI("sha256").update(F4(j)).digest("hex").slice(0,16);if(J.pinnedEffort===void 0||Z.some((j)=>!z||!fX(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)=>fX(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,N)=>N>0&&j.anchor<=(Z[N-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 N=Z[j];if(!N)continue;z.splice(N.anchor,0,{type:"configuration_update",reasoning:{effort:N.effort}})}}function vb(X){let J=s(X.reasoning)?{...X.reasoning}:{};J.context="all_turns",X.reasoning=J,X.parallel_tool_calls=!1;let $=AG(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 yb(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 hb(X,J={}){let $=J.codexApiEndpoint??c6().codexApiEndpoint,Y=crypto.randomUUID(),G=Rb(),Q=()=>Cb(G),z=!1,Z=!1,W=[],B=null,H=_H(X.client),U=new Map,j=new Map,N,K=!1,q,F=new Map,O,_,C=EV({host:"opencode",stateDir:J.vault?.stateDir??sW(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())),L=C.vault;await L.authority();let P=C.firstRoster,A=Promise.withResolvers(),T=Promise.race([P,A.promise]),k=J.vault?.firstRosterWaitMs??e$,p,i,{enabled:X0,...w}=J.poolMigration??{},J0=X0??_b;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?QV({paths:()=>M0(V0()),slot:H.slot,version:k9,...w,runDeps:{vaultServes:()=>L.serves(),...w.runDeps},paused:async()=>await L.authority()!=="local",migrate:async(h)=>{let o=await(w.migrate??d7)(h);return i?.load(),o},adopt:async(h)=>{if(!await I3(T,k))return{status:"retry",reason:"vault-roster-pending"};let o=await(w.adopt??i7)(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 i$(J.backgroundQuota),c0,m0=wH({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:L,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 tV(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(),N?.stopBackgroundRefresh(),N=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=p8(o.id);if(F.delete(c),_?.cancel(`pin:${c}`),q){let D0=(await b0(M0(V0())))?.accounts;await KL(o.id,D0,q).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||UW(e),D0=c?null:await sV();if(!c&&D0&&!eq)eq=!0,tq.debug("restoring OAuth model costs from models.dev catalog");if(!c&&!D0&&!XL)XL=!0,tq.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"&&Gb(l0.api.id)).map(([l0,i6])=>[l0,{...i6,cost:c?{input:0,output:0,cache:{read:0,write:0}}:D0?.[i6.api.id]??D0?.[l0]??i6.cost,limit:Qb(i6.id)??i6.limit}]))}},auth:{provider:"openai",async loader(h){await L.authority(),c0=h,p??=TV({version:k9,logger:Z0("heartbeat")}),await p,G0?.start();let o=await h();if(o.type!=="oauth")return A.resolve(),{};let e=C3(o).kind==="tombstone";C.start();let c=X.directory?await zL(X.directory):void 0,D0=c?.dir??V0();async function l0(D,M={}){if(await L.authority()!=="local")return;return Ob(D,{...M,canWrite:()=>!L.enrolled()})}let i6=await L.authority()!=="local";if(!e&&!i6)await MW({type:"oauth",access:o.access??"",refresh:o.refresh??"",expires:o.expires??0},M0(V0()));let n0=await b0(M0(V0())).catch(async(D)=>{if(await L.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(!i6&&await l7(M0(V0()),o)){if(G0)G0.noticePlaceholderWithoutMain();else if(!K)K=!0,Z0("pool-migration").warn(U4,{reason:"placeholder-without-main"})}let F6,h6=n0;async function p0(){let D=V0(),M;try{M=eI(D)}catch{M=void 0}if(M&&F6?.path===D&&F6.mtimeMs===M.mtimeMs&&F6.size===M.size)return F6.storage;if(!M)F6=void 0;let R=b0(M0(D)).catch(async(I)=>{if(await L.authority()!=="local")return h6;throw I}).then((I)=>{if(M)F6={path:D,mtimeMs:M.mtimeMs,size:M.size,storage:I};return h6=I,I});return GX(R,YX,()=>h6)}function F8(){F6=void 0}if(n0&&o.access&&!e&&!i6){let D=Z8({id_token:"",access_token:o.access,refresh_token:o.refresh??""});if(D&&D!==n0.mainAccountId)await l0((M)=>{M.mainAccountId=D}),n0.mainAccountId=D,F8()}let T4=n0?.logging?.level;if(T4&&typeof T4==="string")XX(T4);let R4=Z0("transport"),J8=Z0("quota"),e3=Z0("refresh"),P8=Z0("accounts");R4.info("codex auth loader ready",{codexApiEndpoint:$,transport:c6().rawWebSocket?"raw-websocket":c6().webSockets?"websocket":"http"});let U0=new k8({storage:n0,configPath:V0(),fetchQuotaFn:void 0}),C4,E4=0;i?.dispose();let d0=new XY({paths:()=>M0(V0()),refreshProvider:async(D)=>{let M=await Q3({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 b8({accessToken:M.access,fetchImpl:fetch,now:Date.now,...D.identity?{accountId:D.identity}:{},accountKey:D.id,logger:J8}),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 I9(R,I,!0)},vaultIdentities:()=>L.identities(),vaultMode:()=>L.enrolled(),vaultAuthority:()=>L.authority(),vaultFirstRoster:P,vaultFirstRosterBackgroundWaitMs:k,log:Z0("pool")});if(i=d0,!i6)await d0.load();let n6=new eJ({paths:M0(V0()),refreshFn:async(D)=>{if(await L.authority()!=="local")throw Error(D1["vault-refused"]);return Q3({refreshToken:D.refreshToken,fetchImpl:D.fetchImpl,now:D.now})},quotaManager:U0,canWrite:()=>!L.enrolled(),onFallbackStorageChanged:F8,backgroundRefreshPaused:async()=>L.enrolled()||await d0.active()});if(n0&&n0.accounts.length>0)n6.startBackgroundRefresh();function mX(D){if(T0(D))return;return D.access||void 0}function X2(D={}){let{readSidebarState:M,respectBackoff:R,skipFresherThanMs:I}=D;return{getAuth:h,codexRefreshFn:Q3,refreshMainWithLease:yG,fallbackManager:n6,quotaManager:U0,loadAccounts:b0,writeSidebarState:O8,client:X.client,fetchImpl:fetch,now:Date.now,paths:M0(V0()),readSidebarState:M??(()=>WL(I6)),storageMainAccountId:n0?.mainAccountId,isOAuthAccountFn:v0,whamFn:b8,...R===void 0?{}:{respectBackoff:R},...I===void 0?{}:{skipFresherThanMs:I}}}async function RG(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 CG(D){return d0.accessFor(D,await b0(M0(V0())))}let EG=Z0("cachekeep"),J2=P7(n0),SG=J2?.enabled===!0,IG=J2?.subagents===!0,bG=J2?.sustain===!0,kG=eH(n0?{...n0,cachekeep:J2}:n0),$2;async function _L(D){await new Promise((M)=>setTimeout(M,D))}async function AL(D){let M;for(let R=1;R<=rq;R++){if(await L.authority()!=="local")throw Error(D1["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<rq)await _L(Nb*R)}}throw new TG(M)}async function Y2(D){await l0((M)=>{M.refresh=M.refresh??{},D(M)},{holdsMainRefreshLock:!0}),F8()}async function uX(D){let M=Date.now()+jb;while(Date.now()<M){await new Promise((S)=>setTimeout(S,oq+Mb(oq)));let R=await h();if(C6(R))throw new L1;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 e3.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 xG(D){if(C6(D))throw new L1;if(D.type!=="oauth")throw Error("not oauth");if(T0(D))throw new G1;if(!D.refresh)throw Error("Token refresh failed: missing refresh token");return D.refresh}async function pX(){if(!$2)$2=(async()=>{let D=await h(),M=xG(D);if(D.type!=="oauth")throw Error("not oauth");let R=s6(M),I=await b0(M0(V0())),S=I?.refresh?.mainLastRefreshError;if(S&&r0(S,M,Date.now()))throw Error(X9(S,Date.now()));if(I?.refresh?.mainRefreshLeaseUntil&&I.refresh.mainRefreshLeaseUntil>Date.now()&&I.refresh.mainRefreshLeaseTokenHash===R){let d=await uX(D);if(d)return d;throw Error("Codex OAuth refresh is already in progress")}let f=await g0({name:g8,ttlMs:Ub,path:V0(),renew:!0});if(!f){let d=await uX(D);if(d)return d;throw Error("Codex OAuth refresh is already in progress")}let b;try{let d=await h(),H0=xG(d);if(d.type!=="oauth")throw Error("not oauth");if(H0!==M){if(d.access&&(d.expires??0)>Date.now())return e3.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 W6=(await b0(M0(V0())))?.refresh?.mainLastRefreshError;if(W6&&r0(W6,H0,Date.now()))throw Error(X9(W6,Date.now()))}b={...d,refresh:H0}}catch(d){throw await f.release().catch(()=>{}),d}await zH(M0(V0()),b.refresh,b.access!==void 0?{slotAccess:b.access}:{}).catch(()=>!1);let v=s6(b.refresh),n=crypto.randomUUID(),z0=v;try{await Y2((F0)=>{if(QH(V0(),b.refresh))throw new p7;F0.refresh=F0.refresh??{},F0.refresh.mainRefreshLeaseId=n,F0.refresh.mainRefreshLeaseUntil=Date.now()+Kb,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 L.authority()!=="local")throw Error(D1["vault-refused"]);let H0=await Q3({refreshToken:b.refresh,fetchImpl:fetch,now:Date.now});return await AL(H0),await Y2((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 p7)){if(!PG(d))await Y2((H0)=>{H0.refresh=H0.refresh??{},H0.refresh.mainLastRefreshError=p1({error:d,now:Date.now(),refreshToken:b.refresh,previous:H0.refresh.mainLastRefreshError})}).catch(()=>{});throw d}}finally{if(z0)await Y2((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 uX(b);if(l)return l;throw Error("Codex OAuth refresh is already in progress")})().finally(()=>{$2=void 0});return $2}function wG(D){return AH({storage:D,now:Date.now,refreshAccount:(M,R)=>n6.refreshAccount(M,R,{asPoolMain:!0}),warn:(M,R)=>e3.warn(M,{pid:process.pid,...R})})}async function vG(){let D=await wG(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 yG(){try{return await pX()}catch(D){if(D instanceof L1)return vG();throw D}}let hG=globalThis,cX=hG.__openaiAuthCacheKeepManagers??new Map;hG.__openaiAuthCacheKeepManagers=cX,cX.get(D0)?.stop();let S4=$V({fetchImpl:fetch,vault:L,getMainToken:async()=>{if(await L.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await d0.active()){let M=await CG("main");if(!M)throw Error("main pool row has no usable token");return M.token}let D=await h();if(await L.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(C6(D))return(await vG()).access;if(D.type!=="oauth")throw Error("not oauth");if(!D.access||(D.expires??0)<Date.now())try{return(await yG()).access}catch(M){if(PG(M))throw M;if(D.access)return D.access;throw Error("main token refresh failed")}return D.access},refreshFallback:async(D)=>{if(await L.authority()!=="local")throw Error("local accounts are not warmed while this host is connected to the vault");if(await d0.active()){let b=await CG(D);if(!b)throw Error(`no access token for ${D}`);return{token:b.token}}let M=await p0(),R=M?bb(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 n6.refreshAccount(R,I),f=mX(S);if(!f)throw Error(`no access token for ${D}`);return{token:f}},codexResponsesUrl:$,activeAccount:async(D)=>JV(C1(await u9.read(),F),D),logger:EG,now:Date.now,getWindow:()=>kG,getSustain:()=>bG});cX.set(D0,S4),U.set(D0,S4);function E1(D,M,R,I,S=!1){try{TL(D,M,R,I,S)}catch(f){J8.warn("quota push failed",{pid:process.pid,accountId:R??"main",error:e0(f)})}}function TL(D,M,R,I,S){if(Object.keys(D).length===0&&!S)return;let f=Date.now(),b=D,v={quota:b,refreshAfter:f+300000,checkedAt:f},n;if(R&&R!=="main"){let l=M?V6(M):null,d=l?U6(l):void 0,H0=U0.peekFallbackForPolicy(R)?.quota,F0=$L(b,H0);v={...v,quota:F0},U0.setFallback(R,v,M,S,d)}else{if(n=I,!n&&M){let H0=V6(M);n=H0?U6(H0):void 0}if(n&&C4&&n!==C4){J8.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:n,currentMainIdentity:C4});return}let l=U0.peekMainForPolicy(n)?.quota,d=$L(b,l);v={...v,quota:d},U0.setMain(M,v,n,S)}J8.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");l8.enqueue("machine-state","quota",()=>{let l=h6;return O8(U0,l,z0?l?.mainAccountId:n)})}function RL(D,M,R){let I=K8(L.routes().find((S)=>S.id===D)?.quota)??(D==="main"?U0.peekMainForPolicy()?.quota:U0.peekFallbackForPolicy(D)?.quota);return $W(I,M,Date.now(),qb,R)}let G2=new Map,I4=new Map;function fG(){if(!L.enrolled())return;l8.enqueue("machine-state","quota",()=>O8(U0,h6))}let S1=J.experimentalWebSockets?N9.createWebSocketFetch({httpFetch:fetch,rawWebSocket:c6().rawWebSocket,onQuota:(D,M,R,I)=>{let S=R?G2.get(R):void 0;if(S){L.recordSnapshot(S.id,D,!0,S.receipt).then(fG);return}E1(D,M,R,!R||R==="main"?I:void 0,!0)},onRateLimitReached:(D,M,R)=>{if(!M)J8.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:D});let I=M?G2.get(M):void 0,S=I?.id??M??"main",f=RL(S,D,R);if(U0.markRateLimited(S,f),I)I4.set(S,Math.max(I4.get(S)??0,f));else d0.markRateLimited(S,f);J8.debug("mid-stream rate limit mark",{pid:process.pid,accountId:S,window:D})}}):void 0;if(S1)W.push(S1),z=!0;let I6=ZL();q=I6;async function O8(D,M,R=M?.mainAccountId){if(L.enrolled()){await vX(FV(L.snapshot()?.rows??[],new Set(L.routes().map((S)=>S.id)),M,Date.now()),I6,{canWrite:()=>L.enrolled()});return}let I=await d0.current();if(I.active){await vX(PV(I.rows,M,Date.now(),(S)=>(S==="main"?D.getMain():D.getFallback(S))?.quota?.resetCreditsAvailable),I6,{canWrite:()=>!L.enrolled()});return}if(!M)return;await vX(ML(D,M,Date.now(),R),I6,{canWrite:()=>!L.enrolled()})}let u9=LL(I6);u9.read(),_?.stop();let l8=FL({logger:R4,onWritten:()=>u9.refreshInBackground()});if(_=l8,O!==I6)F.clear(),O=I6;function lX(D,M,R,I,S,f,b=!1){let v={canWrite:()=>L.enrolled()===b},n={activeId:R,route:I,updatedAt:Date.now()};if(!D){l8.enqueue("routing:legacy","routing",()=>UL(n,I6,v));return}if(l8.enqueue(`routing:${D}`,"routing",()=>yX({sessionId:D,...n},S,I6,v)),!M||M===D)return;if(I==="sticky-balanced"){let z0=f.stickyAssignments?.[p8(M)]?.accountId,l=S===void 0||z0==="main"||S.some((d)=>d.enabled!==!1&&d.id===z0);if(!z0||!l)return;l8.enqueue(`routing:${M}`,"routing",()=>yX({sessionId:M,activeId:z0,route:I,updatedAt:Date.now()},S,I6,v));return}l8.enqueue(`routing:${M}`,"routing",()=>yX({sessionId:M,...n},S,I6,v))}N?.stopBackgroundRefresh(),N=n6;let b4=M0(V0());if(B=PL={accountStoragePath:b4.configPath,accountStatePath:b4.statePath,packageVersion:k9,quotaManager:U0,loadAccounts:b0,beginAccountLogin:v2,store:()=>V4(b4),migration:async()=>{if(await s7(b4,V4(b4))!==void 0)return{migrated:!0};let D=await(w.fence??(()=>j4({currentVersion:k9})))();return{migrated:!1,blockers:D.open?[]:D.blockers.map((M)=>({pid:M.pid,version:M.version}))}},afterWrite:()=>d0.load(),vault:L,resolveResetTarget:Fb({getAuth:h,refreshMainWithLease:pX,refreshFallbackAccount:(D,M)=>n6.refreshAccount(D,M),refreshPoolMainRow:(D,M)=>n6.refreshAccount(D,M,{asPoolMain:!0}),poolAccess:async(D)=>d0.rowAccess(D,await b0(M0(V0()))),loadAccounts:b0,accountStoragePath:V0(),accountStatePath:x$(V0()),now:Date.now}),...Pb(),cacheKeepManager:S4,setCacheKeepEnabled:(D)=>{SG=D},setCacheKeepSubagents:(D)=>{IG=D},setCacheKeepSustain:(D)=>{bG=D},setCacheKeepWindow:(D)=>{kG=D},clearStickyRouting:async(D)=>{let M=p8(D),R=F.delete(M);return l8.cancel(`pin:${M}`),await qL(D,I6)||R},getStickyRouting:async(D)=>VL(C1(await u9.read(),F),D),refreshSidebar:async()=>{let D=await b0(M0(V0()));await O8(U0,D)},refreshAllQuota:async()=>{if(await L.authority(),L.enrolled()){let D=await L.pollStale(0);return await O8(U0,h6),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([RG(),L.pollStale(0)]);return await O8(U0,h6),[...D,...M.map((R)=>({account:R.id,ok:R.ok,...R.error!==void 0?{error:R.error}:{}}))]}return G4(X2())},refreshResetTargetQuota:async(D)=>{if(await L.authority(),L.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 RG([D]);return R??{account:D,ok:!1,error:"targeted quota refresh returned no result"}}return(await G4(X2({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 QL(XU,D.dir,()=>JU({dir:D.dir,secureDir:D.secureDir,sweepRoot:D.sweepRoot,drain:gH,apply:async(R)=>{let I=S5(R);if(!I)throw Error("not an /openai apply request");return dH(B,I)}}));j.set(D.dir,M)}catch{}}async function I1(D,M,R,I,S="main",f){if(!R.trim())throw R4.warn("refusing to send a request with no access token",{account:S,accountId:I}),Error(zb);if(!f&&await L.authority()!=="local")return Response.json({error:{message:D1["vault-refused"]}},{status:400});let b=YL(D,M);if(b.delete("x-api-key"),b.delete("api-key"),b.set("authorization",`Bearer ${R}`),I)b.set("ChatGPT-Account-Id",I);b.set(N9.QUOTA_ACCOUNT_HEADER,S);let v=GL(b),n=v?Tb(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=Ib({init:{...M,headers:b},headers:b,metadata:n,installationID:Y,websocket:Boolean(S1&&z0.pathname.endsWith("/responses")),responsesLite:J.responsesLite??!1,dumpSessionID:v}).init,F0=SG,W6=new Headers(H0?.headers),W0=tH({enabled:F0,includeSubagents:IG,headers:W6,body:H0?.body});if(F0)EG.trace("cachekeep headers",{pid:process.pid,hasParent:W6.has("x-parent-session-id"),sessionKey:W0?.sessionKey,captured:Boolean(W0),affinity:W6.get("x-session-affinity"),opencodeSession:W6.get("x-opencode-session"),sessionId:W6.get("session-id")});if(S1&&z0.pathname.endsWith("/responses")){if(R4.debug("WS transport",{pid:process.pid,pathname:z0.pathname,accountId:S}),W0)S4.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 j1(await S1(l,H0),R,"event-stream")}catch(i0){throw j8(i0,R)}let P0=`vault-stream:${aI()}`;G2.set(P0,{id:S,receipt:f});let M8=new Headers(H0?.headers);M8.set(N9.QUOTA_ACCOUNT_HEADER,P0);let P6=()=>G2.delete(P0);try{let i0=await S1(l,{...H0,headers:M8});if(!i0.body)return P6(),i0;let d8=i0.body.getReader();return await j1(new Response(new ReadableStream({async pull(i8){try{let n8=await d8.read();if(n8.done)P6(),i8.close();else i8.enqueue(n8.value)}catch(n8){P6(),i8.error(j8(n8,R))}},cancel(i8){return P6(),d8.cancel(i8)}}),{status:i0.status,statusText:i0.statusText,headers:i0.headers}),R,"event-stream")}catch(i0){throw P6(),j8(i0,R)}}let R0=N9.withoutInternalHeaders(H0);if(typeof R0?.body!=="string")try{return await j1(await fetch(l,R0),R,"event-stream")}catch(P0){throw j8(P0,R)}if(W0)S4.track({sessionKey:W0.sessionKey,bodyText:W0.bodyText,accountId:S,isSubagent:W0.isSubagent,meta:{replayHeaders:W0.replayHeaders,chatgptAccountId:I,routingSessionId:v}});R4.debug("HTTP transport",{pid:process.pid,pathname:z0.pathname,accountId:S});try{let P0=await fetch(l,R0);return await q4({sessionID:v,transport:"http",phase:"http",bodyText:R0.body,accountId:S,url:l.toString(),method:R0.method,headers:R0.headers,status:P0.status}),await j1(P0,R,"event-stream")}catch(P0){throw await q4({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)}),j8(P0,R)}}function k4(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 CL(D){return U0.peekMainForPolicy(D)?.quota}function gG(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 x4(D,M,R,I,S){let f=gG(D,M),b=gG(R),v=I===S&&R!=null&&(D===void 0||b!==void 0&&(f===void 0||b>f));return{quota:v?R:D,quotaCheckedAt:v?b:f,source:v?"file":"memory"}}function mG(D,M,R,I,S){let f=D?.quota,b=x4(f,D?.checkedAt,M,I,S),v=b.source,n=b.quota;if(!HL(n,R))return{exhausted:!1};let z0=BL(n,R);if(!z0)return{exhausted:!1};return{exhausted:!0,source:v,...z0}}function uG(D,M){J8.debug("admission skip: exhausted account",{accountId:D,source:M.source,resetsAt:M.resetsAt})}function pG(D,M="killswitch",R,I){let S=Date.now(),f=I?I.main:U0.getMain()?.quota,b=I?I.fallbacks:(D?.accounts??[]).filter((d)=>d.enabled!==!1&&v0(d)).map((d)=>({accountId:d.id,quota:U0.getFallback(d.id)?.quota})),v=OW(f,b,S,D);if(M==="quota-unknown")v=WV;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 dX(D){let M=D?.resetCreditsAvailable;return typeof M==="number"&&Number.isFinite(M)?M:void 0}async function EL(D){let M=z9(D.storage),R=Date.now(),I=U0.peekMainForPolicy(D.mainAccountIdentity),S=x4(I?.quota,I?.checkedAt,D.sidebarState.main.quota,D.sidebarState.main.mainAccountId,D.mainAccountIdentity),f=M?Z1(I?.quota,D.storage,void 0,R):void 0,b=D.mainUnavailable?[]:[{accountId:"main",wireAccountId:D.mainAccountIdentity,access:D.primaryAccess,keepwarmAccountKey:"main",quota:S.quota,quotaCheckedAt:S.quotaCheckedAt,reservePercent:a6(D.storage),configuredOrder:0,resetCreditsApplicable:dX(S.quota),killswitchPasses:f}],v=await n6.getUsableFallbackAccounts(D.storage);if(!D.storage)return b;for(let n of v){let z0=mX(n);if(!z0)continue;let l=D.sidebarState.fallbacks.find((W6)=>W6.id===n.id),d=U0.peekFallbackForPolicy(n.id,n.accountId),H0=x4(d?.quota,d?.checkedAt,l?.quota,l?.accountId,n.accountId),F0=M?Z1(d?.quota,D.storage,n.id,R):void 0;b.push({accountId:n.id,wireAccountId:n.accountId,access:z0,keepwarmAccountKey:n.id,fallback:n,quota:H0.quota,quotaCheckedAt:H0.quotaCheckedAt,reservePercent:a6(D.storage,n.id),configuredOrder:b.length,resetCreditsApplicable:dX(H0.quota),killswitchPasses:F0})}return b}function cG(D,M,R,I,S){let f=z9(S)?D.killswitchPasses:void 0;if(D.accountId==="main"){let z0=U0.peekMainForPolicy(D.wireAccountId),l=x4(z0?.quota,z0?.checkedAt,M.main.quota,M.main.mainAccountId,D.wireAccountId);return VY({quota:l.quota,quotaCheckedAt:l.quotaCheckedAt,status:R,now:I,killswitchPasses:f})}let b=M.fallbacks.find((z0)=>z0.id===D.accountId),v=U0.peekFallbackForPolicy(D.accountId,D.wireAccountId),n=x4(v?.quota,v?.checkedAt,b?.quota,b?.accountId,D.wireAccountId);return VY({quota:n.quota,quotaCheckedAt:n.quotaCheckedAt,status:R,now:I,killswitchPasses:f})}function SL(D){return D.accountId==="main"?"main":D.keepwarmAccountKey}function lG(D){return U0.isRateLimited(SL(D))}function iX(D){let M=D.candidates.filter((f)=>!lG(f)),R=new Map(M.map((f)=>[f.accountId,f])),I=new Set(D.excludeAccountIds),S=dG({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 b=M.filter((v)=>!I.has(v.accountId));if(b.length===0)return;return wV({candidates:b,pendingBytes:f,requestBytes:D.requestBytes,now:D.now,onEmptyWeightedSet:()=>{P8.debug("sticky routing: no fresh weighted candidates; using configured order")}})},persist:!0});return S?R.get(S.accountId):void 0}function dG(D){let M=void 0,R=D.validPinnedAccountIds,I=jL(C1(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 b=D.select(f);if(!b)return;return M={accountId:b.accountId,source:b.source,pendingBytes:f.get(b.accountId)??0},b}}),S=I.assignment;if(!D.persist)return S;if(M&&S?.accountId===M.accountId)P8.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:p8(D.sessionId),accountId:M.accountId,source:M.source,requestBytes:D.requestBytes,pendingBytes:M.pendingBytes});if(S&&I.next!==void 0){let f=p8(D.sessionId),b=DL(F,f,S);l8.enqueue(`pin:${f}`,"sticky-pin",async()=>{await NL({sessionId:D.sessionId,assignment:S,validPinnedAccountIds:R},I6),b.persistedAt=Date.now()})}return S}async function IL(D,M){let R=await n6.getUsableFallbackAccounts(D),I=[];if(!D)return{current:[],retained:[],skipped:[]};for(let l of R){let d=mX(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=z9(D)?S.filter((l)=>Z1(U0.peekFallbackForPolicy(l.quotaAccountId,l.accountId)?.quota,D,l.quotaAccountId,Date.now())):S,b=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=b.get(l.quotaAccountId),H0=mG(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 iG(D,M){if(D.retained.length===0&&!M)return D.current;for(let{candidate:R,decision:I}of D.skipped)uG(R.quotaAccountId,I);return D.retained}function nG(D,M){try{let R=o9(D.headers);E1(R,M.access,M.quotaAccountId,void 0,d1(D.headers))}catch{}}async function bL(D,M,R,I){for(let S of I){let f;try{f=await I1(D,M,S.access,S.accountId,S.keepwarmAccountKey)}catch(b){if((b instanceof Error||b instanceof DOMException)&&b.name==="AbortError")throw b;if(M?.signal?.aborted)throw b;throw P8.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:S.quotaAccountId}),b}if(!V3(f.status,R))return n6.markUsed(S.fallback),{response:f,accessToken:S.access,quotaAccountId:S.quotaAccountId,activeId:S.keepwarmAccountKey};nG(f,S),f.body?.cancel().catch(()=>{})}return}async function kL(D,M,R,I,S){if(!k4(D,M))return{response:R};if(!S.length)return{response:R};let f=R,b;for(let v of S){let n;try{n=await I1(D,M,v.access,v.accountId,v.keepwarmAccountKey)}catch(z0){if((z0 instanceof Error||z0 instanceof DOMException)&&z0.name==="AbortError")throw z0;if(M?.signal?.aborted)throw z0;return P8.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:v.quotaAccountId}),{response:f,...b}}if(f.body?.cancel().catch(()=>{}),f=n,b={accessToken:v.access,accountId:v.quotaAccountId},!V3(n.status,I))return n6.markUsed(v.fallback),{response:n,...b};nG(n,v)}return{response:f,...b}}if(n0){let D=[];for(let M of n0.accounts)if(v0(M))D.push(M);U0.seedFallbacksFromAccounts(D)}if(!_G)if(_G=!0,O8(U0,n0).catch(()=>{}),P.then(()=>L.enrolled()?O8(U0,h6):void 0).catch(()=>{}),!L.enrolled()&&!await d0.active())hX=G4(X2({respectBackoff:!0})).catch((D)=>J8.warn("boot quota seed failed",{pid:process.pid,error:e0(D)}));else hX=Promise.resolve();m.start(async()=>{if(await L.authority(),L.enrolled()){await O8(U0,h6);return}if(await d0.active()){let R=await oH(d0,await b0(M0(V0())),()=>d$(V0()));if(R.length>0)await O8(U0,h6);let I=R.filter((S)=>!S.ok);if(I.length>0)J8.warn("background pool quota poll completed with failures",{pid:process.pid,failures:I});return}let M=(await sH(X2({readSidebarState:async()=>(await u9.read()).state}))).filter((R)=>!R.ok);if(M.length>0)J8.warn("background quota refresh completed with failures",{pid:process.pid,failures:M})},(D)=>{J8.warn("background quota refresh failed",{pid:process.pid,error:D instanceof Error?D.message:String(D)})});async function nX(D,M,R,I,S,f){let b=R?.routing?.mode??"main-first",v=L.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 l7(M0(V0()),z0);if(f===E4)C4=n?.identity;let H0=await u9.get(),{response:F0,servedId:W6}=await DV({source:d0,...v?{vault:{routes:()=>L.routes(),awaitRoster:async()=>{await I3(P,t$)},noRouteCause:()=>oW(L),send:(W0,R0)=>L.send(W0,R0,{site:"model",...M?.signal?{signal:M.signal}:{}}),requestReading:(W0)=>L.requestReading(W0),rateLimitMarks:()=>{for(let[W0,R0]of I4)if(R0<=Date.now())I4.delete(W0);return I4}}}:{},storage:R,mode:b,sessionId:I,body:typeof M?.body==="string"?M.body:void 0,replayable:k4(D,M),now:Date.now,send:(W0,R0,P0)=>I1(D,M,R0,W0.identity,W0.id,P0),recordQuota:(W0,R0,P0,M8)=>{try{let P6=o9(W0.headers),i0=d1(W0.headers);if(!R0.row){if(M8)L.recordSnapshot(R0.id,P6,i0,M8).then(fG);return}E1(P6,P0,R0.id==="main"?void 0:R0.id,R0.id==="main"?R0.identity:void 0,i0)}catch{}},placePin:(W0)=>dG({...W0,sidebarSnapshot:H0}),blocked:(W0,R0,P0)=>{if(W0.reason==="no-credential"){if(d&&!zY(P0))throw Error(U4);return new Response(D1[zY(P0)?P0:l?"missing-main":P0??"unusable"],{status:401,headers:{"content-type":"text/plain; charset=utf-8"}})}return pG(R,W0.reason,W0.resetAtMs,R0)},resetCredits:(W0)=>dX(W0==="main"?U0.peekMainForPolicy(n?.identity)?.quota:U0.peekFallbackForPolicy(W0)?.quota),isAbort:(W0)=>(W0 instanceof Error||W0 instanceof DOMException)&&W0.name==="AbortError"||Boolean(M?.signal?.aborted),log:P8});return lX(I,S,W6,b,v?L.routes().map((W0)=>({id:W0.id})):R?.accounts,C1(H0,F),v),F0}return Z=!0,{apiKey:Wb,async fetch(D,M){let R=await L.authority(),I=YL(D,M),S=GL(I),f=I.get("x-parent-session-id")?.trim()||void 0,b=await p0();if(R!=="local")return M=await OG(D,M),nX(D,M,b,S,f,++E4);let v=await h();if(await L.authority()!=="local")return M=await OG(D,M),nX(D,M,b,S,f,++E4);let n=++E4;if(v.type!=="oauth")return I.delete(gX),fetch(D,{...M,headers:I});M=await OG(D,M);let z0=(await d0.current()).active;if(C6(v)&&z0)return nX(D,M,b,S,f,n);if(z0)L.assertHostSlot(v);let l="",d=!1,H0,F0=C6(v);if(G0?.migrated()&&!F0&&v.refresh?.trim()&&C3(v).kind==="real")G0.noticeRealSlot(v.refresh);let W6=async(C0=b)=>{if(F0=!0,H0=await wG(C0),H0)l=H0.token;else l="",d=!0,P8.warn("main account in the pool has no usable token",{pid:process.pid})};if(F0)await W6();else if(T0(v))d=!0;else{if(!v.access||(v.expires??0)<Date.now()){e3.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(v.access),expiresInMs:v.expires?v.expires-Date.now():void 0});try{let C0=await pX();v.access=C0.access,v.refresh=C0.refresh,v.expires=C0.expires}catch(C0){if(PG(C0))throw C0;if(C0 instanceof L1)await W6(await b0(M0(V0())))}}if(!F0)l=v.access??""}let W0=F0?oJ(b):b,R0=v,P0=H0?.account.accountId??(F0?void 0:R0.accountId)??(l?U6(V6(l)??{}):void 0);if(n===E4)C4=P0;let M8=b?.routing?.mode??"main-first",P6=await u9.get(),i0=P6.state;if(M8==="sticky-balanced"&&S&&k4(D,M)&&typeof M?.body==="string"){let C0=Buffer.byteLength(M.body,"utf8"),$6=await EL({storage:W0,sidebarState:i0,primaryAccess:l,mainAccountIdentity:P0,mainUnavailable:d}),o0=iX({sessionId:S,requestBytes:C0,candidates:$6,sidebarSnapshot:P6,now:Date.now()});if(o0){let eG=lG(o0)?{action:"migrate",reason:"exhausted"}:cG(o0,i0,void 0,Date.now(),b);if(eG.action==="migrate"){let f6=iX({sessionId:S,requestBytes:C0,candidates:$6,sidebarSnapshot:P6,excludeAccountIds:[o0.accountId],now:Date.now()});if(f6)P8.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:p8(S),fromAccountId:o0.accountId,toAccountId:f6.accountId,reason:eG.reason}),o0=f6}let _8=await I1(D,M,o0.access,o0.wireAccountId,o0.keepwarmAccountKey),XQ=(f6,p9)=>{try{let xL=o9(f6.headers);E1(xL,p9.access,p9.accountId==="main"?void 0:p9.accountId,p9.accountId==="main"?p9.wireAccountId:void 0,d1(f6.headers))}catch{}};XQ(_8,o0);let JQ=cG(o0,i0,_8.status,Date.now(),b);if((_8.status===401||_8.status===403||_8.status===429)&&JQ.action==="migrate"){let f6=iX({sessionId:S,requestBytes:C0,candidates:$6,sidebarSnapshot:P6,excludeAccountIds:[o0.accountId],now:Date.now()});if(f6){P8.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:p8(S),fromAccountId:o0.accountId,toAccountId:f6.accountId,reason:JQ.reason});let p9=_8;_8=await I1(D,M,f6.access,f6.wireAccountId,f6.keepwarmAccountKey),p9.body?.cancel().catch(()=>{}),o0=f6,XQ(_8,o0)}}if(o0.fallback&&!V3(_8.status,b))n6.markUsed(o0.fallback);return lX(S,f,o0.accountId,M8,b?.accounts,C1(P6,F)),_8}}let d8=mG(U0.peekMainForPolicy(P0),i0.main.quota,Date.now(),i0.main.mainAccountId,P0),i8=z9(b)&&!Z1(CL(P0),b,void 0,Date.now()),n8=U0.isRateLimited("main"),sG,sX=()=>{return sG??=IL(W0,i0),sG},s8,b1,aG=!1,Q2;if(M8==="fallback-first"&&k4(D,M)){aG=!0;let C0=await sX();Q2=iG(C0,!i8&&!n8&&!d8.exhausted);let $6=await bL(D,M,b,Q2);if($6)s8=$6.response,b1={accessToken:$6.accessToken,accountId:$6.quotaAccountId,activeId:$6.activeId}}if(!s8){let C0=d8.exhausted&&k4(D,M)&&(await sX()).retained.length>0;if(i8||n8||C0){let $6=i8?"killswitch":n8?"mid-stream-rate-limit":"quota-exhausted";if($6==="quota-exhausted"&&d8.exhausted)uG("main",d8);P8.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:$6}),s8=pG(b,$6,$6==="quota-exhausted"&&d8.exhausted?d8.resetAtMs:n8?U0.rateLimitedUntil("main"):void 0)}else s8=d?new Response(null,{status:401}):await I1(D,M,l,P0,"main")}let aX=Boolean(b1),w4=s8,oG=b1?.accessToken??l,rG=b1?.accountId,tG=b1?.activeId??"main";if(!b1&&!aG&&V3(s8.status,b)){P8.debug("reactive fallback triggered",{pid:process.pid,status:s8.status}),Q2??=iG(await sX(),!1);let C0=await kL(D,M,s8,b,Q2),$6=C0.response;if($6!==s8){if(aX=!0,w4=$6,oG=C0.accessToken??l,rG=C0.accountId,C0.accountId)tG=C0.accountId}}if(F0&&d&&!aX&&await l7(M0(V0()),await h()))throw Error(U4);try{let C0=o9(w4.headers);if(aX)E1(C0,oG,rG,void 0,d1(w4.headers));else E1(C0,l,void 0,P0,d1(w4.headers))}catch{}return lX(S,f,tG,M8,b?.accounts,C1(P6,F)),w4}}},methods:u0},"chat.headers":async(h,o)=>{if(h.model.providerID!=="openai")return;if(o.headers.originator="opencode",o.headers["User-Agent"]=`${x2(k9)} (${DG.platform()} ${DG.release()}; ${DG.arch()})`,o.headers["session-id"]=h.sessionID,Z)o.headers[gX]=h.agent;if(z&&h.agent==="title")o.headers[N9.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??{},[p6]:{template:p6,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!==p6)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."),JL();let o=await lH(B,h.sessionID);if(mH(h.sessionID))t7(o,h.sessionID);else await t(h.sessionID,iH(o.menu));JL()}}}var fb=async(X)=>{let J=c6();return hb(X,{codexApiEndpoint:J.codexApiEndpoint,experimentalWebSockets:J.webSockets,responsesLite:J.responsesLite})},pn={id:"cortexkit-openai-auth",server:fb};
222
+ export{V6 as c,U6 as d,Z8 as e,v2 as f,o9 as g,d1 as h,Iz as i,$3 as j,T0 as k,Q3 as l,b8 as m,$W as n,b0 as o,U3 as p,z9 as q,a6 as r,Z1 as s,U8 as t,I9 as u,K8 as v,sW as w,Q$ as x,oW as y,b7 as z,sf as A,Q4 as B,j8 as C,dM as D,j1 as E,V0 as F,c6 as G,M0 as H,j_ as I,l7 as J,d7 as K,i7 as L,f8 as M,H4 as N,n7 as O,u$ as P,U4 as Q,j4 as R,k9 as S,t$ as T,e$ as U,I3 as V,XY as W,QV as X,E6 as Y,BV as Z,HV as _,UV as $,YY as aa,jV as ba,NV as ca,nA as da,TV as ea,EV as fa,r3 as ga,kq as ha,$b as ia,Yb as ja,Gb as ka,Qb as la,zb as ma,Zb as na,MG as oa,Hb as pa,hn as qa,Ub as ra,Kb as sa,fn as ta,gn as ua,TG as va,D6 as wa,Fb as xa,Pb as ya,mn as za,_b as Aa,bb as Ba,$L as Ca,ML as Da,un as Ea,GL as Fa,kb as Ga,vb as Ha,hb as Ia,fb as Ja,pn as Ka};