@cortexkit/opencode-openai-auth 1.14.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2 -2
- package/dist/{index-nfbmjq6g.js → index-2f330s35.js} +2 -2
- package/dist/{index-4zpxwh8y.js → index-3mbw88h7.js} +2 -2
- package/dist/{index-q111b2h5.js → index-94b345dw.js} +1 -1
- package/dist/{index-yew3mp47.js → index-999nwa9p.js} +17 -17
- package/dist/{index-1abcvt9p.js → index-cxnrd85v.js} +1 -1
- package/dist/{index-xxmaf5ks.js → index-gkye2xh1.js} +2 -2
- package/dist/{index-f7t7cc9b.js → index-k5av4j8p.js} +2 -2
- package/dist/{index-wap9mf5f.js → index-pc4vrrex.js} +2 -2
- package/dist/{index-zcpher1w.js → index-snq7bwr6.js} +2 -2
- package/dist/{index-3c9pk6zn.js → index-wma2ggn9.js} +2 -2
- package/dist/{index-bc2d4vma.js → index-xk7f1aef.js} +1 -1
- package/dist/{index-a9tzfpxy.js → index-yygzbxjk.js} +1 -1
- package/dist/{index-4tpttpjw.js → index-z9cj13z7.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-6x4q5r2r.js → token-sgwxn4xg.js} +1 -1
- package/dist/token-util-8mrnmkge.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +1 -1
- package/dist/token-util-54mhq85x.js +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{$d as O7,$e as G7,Ad as s3,Bd as a3,Be as N4,Cd as i3,Ce as $7,De as F8,Ed as x7,Fd as y7,Fe as K8,Gd as O3,Ge as _4,Hd as S3,Id as I3,Ie as T4,Jd as k5,Je as u0,Kd as x5,Le as Q1,Md as w6,Nd as P9,Od as f2,Oe as N8,Pe as oZ,Rd as y5,Td as g5,Ud as f5,Ue as C4,Vd as E6,Wd as v5,Yd as h5,Zd as m5,Ze as z7,_d as R6,ae as w5,af as B7,be as u5,cf as D8,de as f7,df as P8,ee as I4,fe as v7,ff as A6,ge as J7,gf as K7,he as X7,if as fZ,le as I6,me as b6,pf as N7,qd as r0,rd as g7,sd as B1,td as c3,vd as m6,wd as I0,xd as gZ,yd as b0,ye as O4}from"./index-4zpxwh8y.js";import{Af as l4,Bf as t$,uf as r$,vf as P0,wf as o$,xf as y1,yf as K0}from"./index-zcpher1w.js";import{Lf as d7}from"./index-xxmaf5ks.js";import{$f as H$,Sf as g3,Wf as o,Xf as C7,Zf as V$,_f as b4,ag as x0}from"./index-wap9mf5f.js";import{dg as r4,kg as n$}from"./index-nfbmjq6g.js";class b extends Error{operation;rowId;phase;retryable;kind;committed;constructor($){super($.message??`${$.operation} failed (${$.kind}, ${$.phase})`,$.cause===void 0?void 0:{cause:$.cause});this.name="PoolOperationError",this.operation=$.operation,this.rowId=$.rowId,this.phase=$.phase,this.retryable=$.retryable,this.kind=$.kind,this.committed=$.committed}}class n2 extends Error{operation;constructor($){super(`${$} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=$}}var C2="identity-contradicted: ",L1="duplicate-identity";function s0($,Z,J){let X=$.rosterRow(Z);if(!X)return;X.enabled=!1;let z=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");$.setEntry(Z,{...z,disabledReason:G?z.disabledReason:J})}function r2($,Z){let J=$.rosterRow(Z);if(!J)return;J.enabled=!0;let X=$.entry(Z);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,$.setEntry(Z,z)}}function T2($,Z){let J=$.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===Z),X=[];for(let z of J.slice(1))s0($,z.id,"duplicate-identity"),X.push(z.id);return X}function J2($,Z,J){let X=$.rosterRow(Z);if(!X)return[];return X.accountId=J,T2($,J)}import{AsyncLocalStorage as x$}from"node:async_hooks";var p4=new x$,y$=new x$;function a($){if(p4.getStore()!==void 0)throw new n2($)}function g$(){if(p4.getStore()?.storeLocksReleased===!1||y$.getStore())throw new n2("updateLimitsNamespace")}function z0($){return y$.run(!0,$)}function G0($,Z,J=!1){return p4.run({operation:$,storeLocksReleased:J&&p4.getStore()?.storeLocksReleased!==!1},async()=>await Z())}async function f$($,Z,J,X,z){if(!Z)return;try{await G0($,()=>Z(J,X),!0)}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:J,error:G instanceof Error?G.message:String(G)})}}import{setTimeout as LJ}from"node:timers/promises";var _1=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function QJ($,Z,J){let X=(B)=>{try{let W=J.onLockEvent?.({type:B,name:$.name,path:$.path});if(W&&(typeof W==="object"||typeof W==="function")&&"then"in W&&typeof W.then==="function")Promise.resolve(W).catch(()=>{})}catch{}},z={...Z,...WJ($)},G=performance.now();for(;;){let B=await K0({name:$.name,path:$.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>X("contended"),...J.onRenewalTimer?{onRenewalTimer:(Y)=>J.onRenewalTimer?.({name:$.name,path:$.path},Y)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...J.onLockStep?{onStep:(Y)=>J.onLockStep?.({name:$.name,path:$.path},Y)}:{}});if(B){X("acquired");let Y={name:$.name,path:$.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),X("released")}};try{await Y.assertOwned()}catch(V){throw await Y.release(),V}return Y}let W=z.timeoutMs-(performance.now()-G);if(W<=0)throw new l4({target:$.path,name:$.name,timeoutMs:z.timeoutMs});let Q=Math.floor(Math.random()*(z.retryMs+1));await new Promise((Y)=>setTimeout(Y,Math.min(z.retryMs+Q,W)))}}function WJ($){let Z={};if($.ttlMs!==void 0)Z.ttlMs=$.ttlMs;if($.timeoutMs!==void 0)Z.timeoutMs=$.timeoutMs;if($.retryMs!==void 0)Z.retryMs=$.retryMs;if($.renew!==void 0)Z.renew=$.renew;if($.renewIntervalMs!==void 0)Z.renewIntervalMs=$.renewIntervalMs;return Z}class A0{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await QJ($,this.defaults,this.env);return this.held.push(Z),await this.assertAll(),Z}async assertAll(){for(let $ of this.held)await $.assertOwned()}async releaseTo($){while(this.held.length>$)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}function X2($,Z,J){if(J!==void 0)throw new b({operation:$,rowId:Z,kind:"row-staged",phase:$==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${Z} is reserved for roster publication`})}import{createHash as o2}from"node:crypto";var v="commonAuthPool",a0=1,N0="rows",d4="retiredEpochs",t2=1,O1=300000,g=v;function YJ($){let Z=JSON.parse(JSON.stringify($)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(S(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J(Z)}function z2($){return o2("sha256").update(YJ($)).digest("hex")}function v$($){if(!S($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function VJ($){if(!S($)||typeof $.reservation!=="string"||!$.reservation||typeof $.disabledReason!=="string")return;if(Object.keys($).some((Z)=>!["reservation","label","disabledReason","providerState"].includes(Z)))return;if("label"in $&&typeof $.label!=="string")return;if("providerState"in $&&(typeof $.providerState!=="string"||!/^[a-f0-9]{64}$/.test($.providerState)))return;return $}var n="commonAuthProviderState";function S($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var HJ=new Set(["__proto__","constructor","prototype"]);function L2($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(HJ.has($))return"id is a reserved object key";return}function S1($){let Z=typeof $==="string"?$.trim():"";if(!Z)return!1;try{let J=new URL(Z);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function h$($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function D0($){return o2("sha256").update(h$($)).digest("hex")}function E0($){return o2("sha256").update(`credential-stamp\x00${h$($)}`).digest("hex")}function f0($){let Z=$.type==="oauth"?["oauth",typeof $.access==="string"?$.access:null,$.refresh,typeof $.expires==="number"&&Number.isFinite($.expires)?$.expires:null]:["api",$.apiKey,$.baseURL.trim(),$.authHeader??"authorization-bearer"];return o2("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function A1($,Z,J,X={}){return{credentialEpoch:Z,digest:E0($),dispatch:f0($),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function _2($,Z){let J=$?.credentialBound?z0(()=>$.credentialBound?.(Z)):Z;return o2("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function e2($,Z,J,X){if(!Z||J===void 0)return;if(!S($)||!Object.hasOwn($,n))return;let z=t($[g]);if(!z||z.providerState===void 0||z.digest!==E0(Z)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function s($){return Number.isSafeInteger($)&&$>=1}function t($){if(!S($))return;let Z=$.credentialEpoch;if(!s(Z))return;if(typeof $.digest!=="string")return;if("dispatch"in $&&typeof $.dispatch!=="string")return;if("replace"in $&&$.replace!==!0)return;if("providerState"in $&&typeof $.providerState!=="string")return;let J="staged"in $?VJ($.staged):void 0;if("staged"in $&&!J)return;let X={...J?{staged:J}:{},...typeof $.dispatch==="string"?{dispatch:$.dispatch}:{},...$.replace===!0?{replace:!0}:{},...typeof $.providerState==="string"?{providerState:$.providerState}:{}};if(!("binding"in $))return"dispatch"in $||"replace"in $||"providerState"in $||"staged"in $?void 0:{credentialEpoch:Z,digest:$.digest};let z=$.binding;if(!S(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!S1(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...X,binding:{...typeof z.identity==="string"?{identity:z.identity}:{},...typeof z.baseURL==="string"?{baseURL:z.baseURL.trim()}:{},...z.authHeader==="authorization-bearer"||z.authHeader==="x-api-key"?{authHeader:z.authHeader}:{}}}}function UJ($,Z,J){if($.identity!==J)return!1;if($.baseURL!==void 0&&(Z.type!=="api"||Z.baseURL!==$.baseURL))return!1;if($.authHeader!==void 0&&(Z.type!=="api"||Z.authHeader!==$.authHeader))return!1;return!0}function qJ($,Z,J,X){if(!$)return"none";if(!S(X)||!Object.hasOwn(X,g))return"missing";let z=t(X[g]);if(!z)return"malformed";if(z.digest!==E0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!UJ(z.binding,$,J))return"mismatched";if(z.dispatch!==f0($))return"mismatched";return"bound"}function E1($){if(!$.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in $)return{status:"error",reason:"config file is not valid JSON"};let Z=$.value;if(!S(Z))return{status:"error",reason:"config root is not an object"};if("accounts"in Z&&!Array.isArray(Z.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(v in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let J=Z[v];if(!S(J))return{status:"error",reason:`${v} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${v}.schemaVersion is invalid`};if(X>a0)return{status:"error",reason:`${v}.schemaVersion ${X} is newer than ${a0}`};if(N0 in J&&!S(J[N0]))return{status:"error",reason:`${v}.${N0} is not an object`};return{status:"ready",exists:!0,config:Z}}function m$($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!S($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!S($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function O2($){return Array.isArray($.accounts)?$.accounts:[]}function w$($){let Z=$[v];if(!S(Z))return{};let J=Z[N0];return S(J)?J:{}}function jJ($){return S($.accounts)?$.accounts:{}}function FJ($){if(!S($))return"not an object";let Z=L2($.id);if(Z)return Z;if($.type==="api")return S1($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function KJ($,Z){if(!S($))return;let J=$.credentialEpoch;if(!s(J))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let X="quota"in $&&Z.decode?z0(()=>Z.decode?.($.quota)):$.quota;if("quota"in $&&!z0(()=>Z.validate(X)))return;if("staged"in $&&!v$($.staged))return;return{credentialEpoch:J,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:X}:{}}}function NJ($,Z){if(!S(Z))return;if($.type==="api"){let X=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if($.corrupt===!0)return;let J=Z.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.lastRefreshedAt==="number"?{lastRefreshedAt:Z.lastRefreshedAt}:{}}}function c4($,Z){return O2($).find((J)=>S(J)&&J.id===Z)}function u$($){if(!S($[v]))$[v]={};return $[v]}function R1($){let Z=u$($);if(!S(Z[N0]))Z[N0]={};return Z[N0]}function R0($,Z){let J=w$($),X=Object.hasOwn(J,Z)?J[Z]:void 0;return S(X)?X:void 0}function s4($,Z,J){Object.defineProperty(R1($),Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function p$($,Z){let J=$[v];if(!S(J))return;let X=J[d4];if(!S(X)||!Object.hasOwn(X,Z))return;let z=X[Z];return s(z)?z:void 0}function l$($,Z){let J=R0($,Z)?.credentialEpoch;return s(J)?J:void 0}function a4($,Z){return Math.max(p$($,Z)??0,l$($,Z)??0)+1}function d$($,Z){let J=[...Z];if(J.length===0)return;let X=u$($),z=S(X[d4])?X[d4]:{},G={},B=(W,Q)=>Object.defineProperty(G,W,{value:Q,enumerable:!0,writable:!0,configurable:!0});for(let[W,Q]of Object.entries(z))if(s(Q))B(W,Q);for(let W of J)B(W,Math.max(p$($,W)??0,l$($,W)??1));X[d4]=G}function i0($,Z,J,X){let z=w$($),G=jJ(Z),B=new Set,W=[];for(let Q of O2($)){let Y=FJ(Q),V=S(Q)&&typeof Q.id==="string"?Q.id:void 0,H=V===void 0?void 0:z[V],q=S(H)&&Object.hasOwn(H,"staged"),F=q?v$(H.staged):void 0;if(Y||!S(Q)||V===void 0||B.has(V)){if(V!==void 0&&!B.has(V))B.add(V);if(V!==void 0)W.push({id:V,type:S(Q)&&Q.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,V),candidate:!1,invalid:"roster",stamp:"none",...F?{staged:F}:{}});continue}B.add(V);let U=Q.type==="api"?"api":"oauth",j=Object.hasOwn(z,V),K=j?KJ(z[V],J):void 0,N=NJ(Q,G[V]),D=Q.enabled!==!1,O=K?K.credentialEpoch:j?void 0:1,M=typeof Q.accountId==="string"&&Q.accountId?Q.accountId:void 0,P={id:V,type:U,enabled:D,needsFirstReading:K?K.needsFirstReading:U==="oauth",hasEntry:j,candidate:!1,...typeof Q.label==="string"?{label:Q.label}:{},...typeof Q.addedAt==="number"?{addedAt:Q.addedAt}:{},...M!==void 0?{identity:M}:{},...N?{credential:N,fingerprint:D0(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...F?{staged:F}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...DJ(G[V],N,O,M,X),stamp:qJ(N,O,M,G[V])};if(j&&!K)P.invalid="entry";else P.candidate=D&&N!==void 0&&!q;W.push(P)}return W}function DJ($,Z,J,X,z){if(!S($)||!Object.hasOwn($,n))return{};let G=e2($,Z,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let B=$[n];if(!z||!z0(()=>z.validate(B)))return{providerStateDropped:"invalid"};if(_2(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function h($){return $.identity??$.id}function $4($,Z){if($===void 0||$>Z+O1)return Z;return Math.max(Z,$+1)}function I1($,Z){return $4($,Z)>Z+O1}function S2($){let{id:Z,credential:J,identity:X,label:z,addedAt:G}=$;return{id:Z,...z!==void 0?{label:z}:{},type:J.type,addedAt:G,...X!==void 0?{accountId:X}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}}}function c$($,Z){if($.type==="api")return{apiKey:$.apiKey};return{...$.access!==void 0?{access:$.access}:{},refresh:$.refresh,...$.expires!==void 0?{expires:$.expires}:{},...Z!==void 0?{lastRefreshedAt:Z}:{}}}function s$($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function a$($,Z={}){if(!S($))return"credential must be an object";if($.type==="oauth"){if(typeof $.refresh!=="string"||!$.refresh.trim())return"oauth credential needs a refresh token";return}if($.type==="api"){if(typeof $.apiKey!=="string"||!$.apiKey.trim())return"api credential needs an api key";if($.apiKey.trim()!==$.apiKey)return"api key must not carry surrounding whitespace";if(!(Z.baseURLOptional&&$.baseURL===void 0)&&!S1($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var i4="transition",i$="transitionMark";function PJ($){if(!S($))return;let Z=$[i4];if(!S(Z))return;if(typeof Z.mark!=="string"||Z.mark.length===0)return;if(Z.enabled===!0)return{mark:Z.mark,enabled:!0};if(Z.enabled===!1&&typeof Z.reason==="string")return{mark:Z.mark,enabled:!1,reason:Z.reason};return}function Z4($,Z,J){if(J.enabled)r2($,Z);else s0($,Z,J.reason??"");if(!$.rosterRow(Z))return;let X=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...X,[i$]:J.mark}),!J.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)T2($,z.identity)}function MJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function CJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function TJ($,Z,J,X={}){let z=S(Z.accounts)?Z.accounts:{},G=new Map;for(let B of i0($,Z,J)){if(B.invalid||B.staged||!B.credential)continue;let W=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!S(W))continue;let Q=t(W[g]);if(!Q?.binding)continue;if(Q.digest!==E0(B.credential))continue;let Y=B.credentialEpoch??1;if(Q.credentialEpoch>Y){if(!CJ(Q))continue;if(X.requireCredentialStamps){if(Q.dispatch===void 0)continue;if(Q.dispatch!==f0(MJ(B.credential,Q.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...Q,binding:Q.binding}})}else if(Q.credentialEpoch===Y&&Q.dispatch!==void 0&&Q.dispatch===f0(B.credential)&&Q.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:Q.binding.identity});else if(Q.credentialEpoch===Y&&Q.binding.identity===B.identity){if(X.requireCredentialStamps&&Q.dispatch!==f0(B.credential))continue;let V=PJ(W[g]);if(V&&R0($,B.id)?.[i$]!==V.mark)G.set(B.id,{kind:"transition",transition:V})}}return G}function b1($,Z,J,X){let G={...$.entry(Z)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(C2))delete G.disabledReason;$.setEntry(Z,G);let B=$.rosterRow(Z);if(!B)return;if(X.identity!==void 0)B.accountId=X.identity;else delete B.accountId;if(X.baseURL!==void 0)B.baseURL=X.baseURL;if(X.authHeader!==void 0)B.authHeader=X.authHeader}function k1($,Z,J,X={}){let z=TJ($,Z,J,X);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),B={rows:()=>i0(G,Z,J),rosterRow:(W)=>c4(G,W),entry:(W)=>R0(G,W),setEntry:(W,Q)=>s4(G,W,Q)};for(let[W,Q]of z)if(Q.kind==="replace")b1(B,W,Q.stamp.credentialEpoch,Q.stamp.binding);for(let[W,Q]of z)if(Q.kind==="identity")J2(B,W,Q.identity);else if(Q.kind==="transition")Z4(B,W,Q.transition);else if(Q.stamp.binding.identity!==void 0)T2(B,Q.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function x1($,Z,J,X={}){let{config:z,torn:G}=k1($,Z,J,X),B=i0(z,Z,J,X.providerState);for(let W of B){if(G.includes(W.id))W.torn=!0,W.candidate=!1;if(X.requireCredentialStamps&&W.stamp!=="bound")W.unbound=!0,W.candidate=!1}return B}async function n4($){try{return await n$($,r4)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function g1($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function e$($){return E1(g1(await n4($)))}async function i($){for(let Z=0;Z<3;Z++){let J=await n4($.configPath),X=await n4($.statePath),z=await n4($.configPath);if(J!==z){if(Z<2)await LJ(2+Math.floor(Math.random()*4));continue}let G=E1(g1(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=m$(g1(X));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:B.exists,config:G.config,state:B.state,rows:x1(G.config,B.state,$.codec,{requireCredentialStamps:$.requireCredentialStamps===!0,...$.providerState?{providerState:$.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function $0($,Z,J,X="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:$.reason});return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,retryable:!1,kind:$.status==="pending-migration"?"pending-migration":"load-error",message:$.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${$.file} file cannot be loaded: ${$.reason}`})}class $3{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,J,X,z){this.ctx=$,this.snapshot=Z,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return x1(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row($){return this.rows().find((Z)=>Z.id===$)}reservation($){if(this.rosterRow($)){let J=this.entry($);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let Z=this.stateAccount($)?.[g];return S(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){X2(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),c4(this.config,$)}dropRosterRows($){let Z=this.roster(),J=Z.filter((X)=>!(S(X)&&X.id===$));return this.config.accounts=J,Z.length-J.length}entries(){return R1(this.config)}entry($){return this.entries(),R0(this.config,$)}setEntry($,Z){s4(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=k1(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if(Z.length===0)return;this.config=$,await this.commitConfig({counted:!1})}stateAccount($){let Z=S(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn(Z,$)?Z[$]:void 0;return S(J)?J:void 0}dropStateAccount($){if(S(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!S(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,$,{value:Z,enumerable:!0,writable:!0,configurable:!0})}async commitConfig($={}){let Z=this.roster(),J=new Set;for(let Q of Z)if(S(Q)&&typeof Q.id==="string")J.add(Q.id);let X=new Set;for(let Q of O2(this.snapshot.config))if(S(Q)&&typeof Q.id==="string"&&!J.has(Q.id))X.add(Q.id);for(let Q of Object.keys(this.entries()))if(!J.has(Q))X.add(Q);d$(this.config,X);let z=this.entries(),G={};for(let[Q,Y]of Object.entries(z))if(J.has(Q))Object.defineProperty(G,Q,{value:Y,enumerable:!0,writable:!0,configurable:!0});let B=this.config[v],W={...this.config,version:t2,accounts:Z,[v]:{...B,schemaVersion:a0,[N0]:G}};await this.write(this.ctx.configPath,W,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let Q of X)this.ctx.removedIds.add(Q);this.config=W}),this.config=W}async commitState($,Z={}){let J={...this.state,version:t2,accounts:S(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,Z.durable??!1),this.state=J,$)this.progress.committed=$}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await y1(this.ctx.statePath)}catch($){throw new b({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:$})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await y1(this.ctx.configPath)}async write($,Z,J,X=!0,z=!1,G){await o$($,Z,{durable:z,beforeRename:async()=>{await this.ctx.onStep?.(`before-${J}-write`,this.info),await this.locks.assertAll()}},()=>{if(X)this.progress.writes++;G?.()}),await this.ctx.onStep?.(`after-${J}-write`,this.info)}}async function Z3($,Z){let J=new A0($.lockDefaults,$.lockEnv),X={writes:0};try{for(let W of $.storeLocks)await J.acquire(W);let z=await i($);if(z.status==="error")throw $0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[W,Q]of Object.entries(z.config))if(!Z.includes(W))G[W]=Q;G.version=t2,G[v]={schemaVersion:a0,[N0]:{}};let B={operation:"initialize",rowId:void 0};return await P0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",B),await J.assertAll()}}),X.writes++,await $.onStep?.("after-config-write",B),"initialized"}catch(z){throw n0(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function w($,Z,J,X,z,G={}){let B=Z.held.length;try{for(let Y of $.storeLocks)await Z.acquire(Y);let W=await i($);if(W.status!=="ready")throw $0(W,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let Q=new $3($,W,Z,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))Q.assertNotStaged(X.rowId);if(G.completeTorn??!0)await Q.completeTorn();return await z(Q)}finally{await Z.releaseTo(B)}}function n0($,Z,J,X){let z=Z==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if(Z==="publishRoster"&&X.publicationDecided)return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:z,kind:"publication-incomplete",retryable:!0,message:"The publication may already be decided. Replay the same plan or check publication(operationId).",cause:$});if(Z==="publishRoster"&&$ instanceof r$)return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof b){if($.phase===z&&$.rowId===J&&$.operation===Z&&$.committed===G)return $;return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:$.kind==="after-persist-hook"?$.phase:z,retryable:$.retryable,kind:$.kind,...$.committed??G?{committed:$.committed??G}:{},message:$.message,...$.cause!==void 0?{cause:$.cause}:{}})}let B={operation:Z,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof t$)return new b({...B,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${Z} lost a lease after its first write; the intermediate stays on disk`:`${Z} lost a lease before writing; nothing was written`});if($ instanceof l4)return new b({...B,retryable:!0,kind:"lock-contention",message:$.message});return new b({...B,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function l($,Z,J,X,z){let G=new A0($.lockDefaults,$.lockEnv),B={writes:0};try{return await z(G,B)}catch(W){let Q=n0(W,Z,J,B);if(Q.kind!=="after-persist-hook")await f$(Z,X,J,Q,$.logger);throw Q}finally{await G.releaseAll()}}function Z0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(h(Z))}`,path:$.ctx.statePath}}async function M0($,Z,J){let X=await i($.ctx);if(X.status!=="ready")throw $0(X,Z,J);let z=X.rows.find((Y)=>Y.id===J),G=R0(X.config,J),B=X.state.accounts,W=S(B)&&Object.hasOwn(B,J)?B[J]:void 0,Q=S(W)?W[g]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))X2(Z,J,G.staged);if(!z&&S(Q)&&Object.hasOwn(Q,"staged"))X2(Z,J,Q.staged);if(!z)throw B0(Z,J);return{result:X,row:z}}function B0($,Z){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function r($,Z){if(Z.unbound)throw _($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function _($,Z,J,X,z=!1){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function f1($,Z){if(!s(Z?.credentialEpoch))throw _("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function J4($,Z,J){if(!J)throw B0("pull",$);if(J.invalid)throw _("pull",$,"invalid-row",`row ${$} is invalid`);if(!J.credential)throw _("pull",$,"no-credential",`row ${$} holds no credential`);if(r("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==Z.credentialEpoch||J.identity!==Z.identity)throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${$} was issued for a credential the row no longer holds`})}function X4($,Z,J,X){let z=z0(()=>$.codec.merge(J,X));if(!z0(()=>$.codec.validate(z)))throw _("pull",Z,"invalid-quota","the quota codec rejected the merged map");return z}async function o4($,Z,J,X){let{ctx:z}=$,G=new A0(z.lockDefaults,z.lockEnv),B={writes:0};try{f1(Z,J),await w(z,G,B,{operation:"pull",rowId:Z},async(W)=>{W.assertNotStaged(Z);let Q=W.row(Z);J4(Z,J,Q);let Y=W.entry(Z);if(!Y)throw B0("pull",Z);let V=X4(z,Z,Y.quota,X);W.setEntry(Z,{...Y,quota:V,needsFirstReading:!1}),await W.commitConfig()},{completeTorn:!1})}catch(W){throw n0(W,"pull",Z,B)}finally{await G.releaseAll()}}async function J3($,Z,J={}){g$();let{ctx:X}=$;await l(X,"updateLimitsNamespace",void 0,void 0,async(z,G)=>{for(let H of X.storeLocks)await z.acquire(H);let B=await i(X);if(B.status!=="ready")throw $0(B,"updateLimitsNamespace",void 0);let W=B.rows.map(({id:H,credentialEpoch:q,identity:F})=>({id:H,credentialEpoch:q,identity:F})),Q=await G0("updateLimitsNamespace",()=>Z(structuredClone(B.config.commonAuthLimits),W)),Y={...B.config,commonAuthLimits:Q},V={operation:"updateLimitsNamespace",rowId:void 0};try{await P0(X.configPath,Y,{beforeRename:async()=>{await X.onStep?.("before-config-write",V),await z.assertAll(),J.beforePublish?.()}})}catch(H){if(H&&typeof H==="object"&&"published"in H&&H.published===!0)J.onPublished?.();throw H}G.writes++,J.onPublished?.(),await X.onStep?.("after-config-write",V)})}function v0($,Z,J,X,z="the provider state"){if(!$)throw _(Z,J,"invalid-input","the store was opened without a provider-state codec");let G;try{let B=JSON.stringify(X);G=B===void 0?void 0:JSON.parse(B)}catch{G=void 0}if(G===void 0)throw _(Z,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!z0(()=>$.validate(G)))throw _(Z,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function z4($,Z,J,X,z){if(X===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:v0($,Z,J,z0(()=>$.merge?.(structuredClone(X),structuredClone(z))),"the merged provider state")}}function X3($,Z,J,X,z){let G=$?.onReplace,B=G?z0(()=>G(Z.providerState===void 0?void 0:structuredClone(Z.providerState),{id:Z.id,credentialEpoch:J,...Z.identity!==void 0?{previousIdentity:Z.identity}:{},...X!==void 0?{identity:X}:{},...z!==void 0?{incoming:structuredClone(z)}:{}})):z;if(B===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:B};return{kind:"set",value:v0($,"replace",Z.id,B,"the provider state onReplace returned")}}function z3($,Z,J,X,z){if(Z.kind==="set")return _2($,Z.value);if(Z.kind==="clear")return;return e2(J,X?.credential,z,X?.identity)}async function G3($,Z,J,X,z={}){a("updateProviderState");let{ctx:G}=$,B="updateProviderState";return l(G,B,Z,z.onFailure,async(W,Q)=>{let Y=G.providerState;if(!Y)throw _(B,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw _(B,Z,"invalid-input","a mutator is required");let V=S(J)?J.credentialEpoch:void 0;if(!s(V))throw _(B,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:H}=await M0($,B,Z);await W.acquire(Z0($,H));for(let q of z.extraLocks??[])await W.acquire(q);return w(G,W,Q,{operation:B,rowId:Z},async(q)=>{let F=q.row(Z);if(!F)throw B0(B,Z);if(h(F)!==h(H))throw _(B,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(F.invalid)throw _(B,Z,"invalid-row",`row ${Z} failed validation`);if(!F.credential)throw _(B,Z,"no-credential",`row ${Z} holds no credential`);if(r(B,F),(F.credentialEpoch??1)!==V||F.identity!==J.identity)throw _(B,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let j=await v1(q,Y,B,F,X);if(j.kind!=="changed")return{id:Z,outcome:"unchanged",...j.kind==="unchanged"&&j.value!==void 0?{providerState:j.value}:{}};return q.setStateAccount(Z,j.account),await q.commitState(),j.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:j.value}})})}var B3=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function v1($,Z,J,X,z,G=!1){let{id:B,credential:W}=X;if(!W)throw _(J,B,"no-credential",`row ${B} holds no credential`);let Q=X.credentialEpoch??1,Y=$.stateAccount(B),V=Y?.[g],H=t(V);if(!S(V)||!H?.binding||H.digest!==E0(W)||H.credentialEpoch!==Q||H.binding.identity!==X.identity)throw _(J,B,"unbound-credential",`row ${B}'s credential carries no stamp of this store to bind a provider state to (stamp ${X.stamp}); rotate or replace it first`);let q=X.providerState===void 0?void 0:structuredClone(X.providerState),F=await G0(J,()=>z(q,X));if(G&&F===B3)return{kind:"declined"};let U=F===void 0?void 0:v0(Z,J,B,F,"the provider state the mutator returned"),j=Y!==void 0&&Object.hasOwn(Y,n);if(U===void 0?!j:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let K={...Y};if(U===void 0){delete K[n];let N={...V};delete N.providerState,K[g]=N}else{K[n]=U;let N=_2(Z,U);if(H.providerState!==N)K[g]={...V,providerState:N}}return{kind:"changed",...U!==void 0?{value:U}:{},account:K}}import{randomUUID as Q3}from"node:crypto";async function Z6($,Z,J){if(!J)return;let X=$.rows().map((G)=>{let{id:B,type:W,label:Q,enabled:Y,disabledReason:V,identity:H,credentialEpoch:q,stamp:F,staged:U,torn:j,invalid:K}=G;return{id:B,type:W,label:Q,enabled:Y,disabledReason:V,identity:H,credentialEpoch:q,stamp:F,staged:U,torn:j,invalid:K}}),z=await G0($.info.operation,()=>J({id:Z,row:X.find((G)=>G.id===Z),rows:X,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw _($.info.operation,Z,"row-protected",z)}var _J=["access","refresh","expires","lastRefreshedAt","apiKey"];function OJ($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function SJ($,Z,J){if(J.type!=="api")return J;let X=$.rosterRow(Z);if(!S(X)){if(J.baseURL===void 0)throw _($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=$.row(Z)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:OJ(X),B=J.baseURL?.trim()??G.baseURL,W=J.authHeader??G.authHeader;if(B!==G.baseURL||W!==G.authHeader)throw _($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:B,authHeader:W}}function W3($,Z,J,X){let z=$.rosterRow(Z),G=$.row(Z),B=X??(G?G.identity:S(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...B!==void 0?{identity:B}:{},...J.type==="api"?{baseURL:J.baseURL,authHeader:J.authHeader??"authorization-bearer"}:{}}}function t4($,Z,J,X,z={}){let G=SJ(Z,J,X),B=Z.stateAccount(J),W=z.providerState??{kind:"keep"},Q=Z.row(J)?.credentialEpoch??Z.entry(J)?.credentialEpoch,Y=typeof Q==="number"?Q:1,V=z3($.ctx.providerState,W,B,B&&Object.hasOwn(B,n)?Z.row(J):void 0,Y),H=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,q=G.type==="oauth"?z.stamp??$4(H,$.ctx.now()):void 0,F={...B??{}};for(let K of _J)delete F[K];if(z.clearErrors)delete F.lastRefreshError,delete F.lastQuotaRefreshError,delete F.quota;if(W.kind==="clear")delete F[n];else if(W.kind==="set")F[n]=W.value;let U=s$(G,q),j={...F,...c$(G,q),[g]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[i4]:z.transition}:{},...A1(U,Y,z.binding??W3(Z,J,U,z.identity),{replace:z.binding!==void 0,...V!==void 0?{providerState:V}:{}})}};return{stored:U,account:j}}async function e4($,Z,J){return $.setStateAccount(Z,J.account),await $.commitState(J.stored),J.stored}async function J6($,Z,J,X,z={}){return e4(Z,J,t4($,Z,J,X,z))}async function AJ($,Z,J){if(!Z.credential||Z.stamp!=="bound")return;let X=$.stateAccount(Z.id),z=e2(X,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...X??{},[g]:A1(Z.credential,Z.credentialEpoch??1,W3($,Z.id,Z.credential,J),z!==void 0?{providerState:z}:{})}),await $.commitState()}function m1($,Z,J){let X=$==="add"?L2(Z):void 0;if(X)throw _($,Z,"invalid-input",X);let z=a$(J,{baseURLOptional:$==="rotate"});if(z)throw _($,Z,"invalid-input",z)}function X6($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if(X&&X.type!==J.type)throw _($,Z,"type-mismatch",`row ${Z} holds a ${J.type} credential`);return J}function E2($,Z,J){if(J!==void 0&&!s(S(J)?J.credentialEpoch:void 0))throw _($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function z6($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw _($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function $6($,Z){return _($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function G4($,Z){return _($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function EJ($,Z,J,X){let{id:z,credential:G,identity:B}=J;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!A2(Z.state,z))return;let W=()=>{throw _("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Q=Z.stateAccount(z),Y=t(Q?.[g]);if(!Y?.binding||Y.dispatch===void 0||Y.replace)return W();if(G.type==="api"&&(Y.binding.baseURL===void 0||Y.binding.authHeader===void 0))return W();let V=G.type==="api"?{...G,baseURL:Y.binding.baseURL,authHeader:Y.binding.authHeader}:G,[H]=i0({accounts:[S2({id:z,credential:V,identity:Y.binding.identity,addedAt:0})],[v]:{rows:{[z]:{credentialEpoch:a4(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!H?.credential||H.invalid||H.stamp!=="bound")return W();if(B!==void 0&&B!==H.identity)return W();if(E0(G)!==Y.digest)return W();if(G.type==="api"){if(G.baseURL.trim()!==Y.binding.baseURL)return W();if((G.authHeader??"authorization-bearer")!==Y.binding.authHeader)return W()}else if(f0(G)!==Y.dispatch)return W();if(Y.providerState!==void 0&&H.providerState===void 0)return W();if(X!==void 0&&_2($.ctx.providerState,X)!==Y.providerState)return W();return H}function RJ($,Z,J,X){let{id:z,credential:G,identity:B,label:W}=J,Q=Z.rosterRow(z),Y=()=>{throw _("add",z,Q?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},V=Z.stateAccount(z),H=t(V?.[g]),q=H?.staged;if(!H?.binding||!q||H.replace||H.dispatch===void 0)return Y();if(Q&&(Q.type!==G.type||Q.label!==W||Q.accountId!==B))return Y();if(q.reservation!==J.stage?.reservation||q.label!==W||q.disabledReason!==J.disabled?.reason||H.binding.identity!==B)return Y();let F=X===void 0?void 0:z2(X),U=V?.[n],j=U===void 0?void 0:z2(U);if(q.providerState!==F||q.providerState!==j)return Y();if(E0(G)!==H.digest||f0(G)!==H.dispatch)return Y();let K=Q?Z.config:{accounts:[{...S2({id:z,credential:G.type==="api"?{...G,baseURL:H.binding.baseURL??"",authHeader:H.binding.authHeader}:G,identity:H.binding.identity,label:q.label,addedAt:0}),enabled:!1}],[v]:{rows:{[z]:{credentialEpoch:H.credentialEpoch,disabledReason:q.disabledReason,staged:{reservation:q.reservation}}}}},N=i0(K,Z.state,$.ctx.codec,$.ctx.providerState).find((D)=>D.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==q.label||N.identity!==H.binding.identity||N.disabledReason!==q.disabledReason||N.staged?.reservation!==q.reservation)return Y();if(Q)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:H.credentialEpoch};if(a4(Z.config,z)!==H.credentialEpoch)return Y();return Z.roster().push({...S2({id:z,credential:G,identity:B,label:W,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:H.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:q.disabledReason,staged:{reservation:q.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:H.credentialEpoch}))}async function Y3($,Z,J={}){a("add");let{ctx:X}=$,{id:z,credential:G,identity:B,label:W}=Z,Q=Z.stage!==void 0||Z.disabled!==void 0,Y=await l(X,"add",z,J.onFailure,async(V,H)=>{m1("add",z,G);let q=J.onExisting??"rotate";if(Z.stage!==void 0&&q==="rotate")throw _("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(q)||Z.stage!==void 0&&(W!==void 0&&typeof W!=="string"||B!==void 0&&(typeof B!=="string"||!B))||Z.disabled!==void 0&&(!S(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!S(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||q==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw _("add",z,"invalid-input","staging requires a reservation and a disabled reason");let F=Z.providerState===void 0?void 0:v0(X.providerState,"add",z,Z.providerState);if(await V.acquire(Z0($,{id:z,identity:B})),G.type==="oauth")await V.acquire(J.providerLock??$.providerLock);for(let U of J.extraLocks??[])await V.acquire(U);return w(X,V,H,{operation:"add",rowId:z},async(U)=>{await Z6(U,z,J.protect);let j=S(U.state.accounts)?U.state.accounts:{},K=Object.entries(j).find(([I,f])=>{if(I===z||U.rosterRow(I)||!S(f))return!1;let c=f[g];if(!S(c)||!Object.hasOwn(c,"staged"))return!1;return G.type==="oauth"?f.refresh===G.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===G.apiKey.trim()});if(K)throw _("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw _("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&q!=="rotate"&&(U.rosterRow(z)||A2(U.state,z)))return RJ($,U,Z,F);if(q==="rotate"){U.assertNotStaged(z);let I=U.rows().find((f)=>f.fingerprint===D0(G));if(I)U.assertNotStaged(I.id)}if(q==="refuse"){let I=U.rows().find((c0)=>c0.fingerprint===D0(G)||c0.id===z&&c0.credential),f=S(U.state.accounts)?U.state.accounts:{},c=Object.entries(f).find(([,c0])=>{if(!S(c0))return!1;if(G.type==="oauth")return c0.refresh===G.refresh;return typeof c0.apiKey==="string"&&c0.apiKey.trim()===G.apiKey.trim()})?.[0],k$=I?.id??c??z;if(I||c!==void 0||A2(U.state,z))throw _("add",k$,"credential-exists",`row ${k$} already holds this secret or id`)}if(q==="stage-duplicate"&&(U.rosterRow(z)||A2(U.state,z)))throw _("add",z,"id-exists",`row ${z} already exists`);let N=EJ($,U,Z,F),D=U.rows(),O=D0(G),M=q==="rotate"&&!N&&D.find((I)=>I.invalid===void 0&&I.fingerprint===O);if(M){if(U.assertNotStaged(M.id),r("add",M),B!==void 0&&M.identity!==void 0&&B!==M.identity)throw $6("add",M.id);let I=t4($,U,M.id,G,{...F!==void 0?{providerState:z4(X.providerState,"add",M.id,M.providerState,F)}:{}});await U.completeTorn(),U.assertNotStaged(M.id);let f=await e4(U,M.id,I);return{id:M.id,outcome:"rotated",credential:f,credentialEpoch:M.credentialEpoch??1}}let P=D.find((I)=>I.id===z);if(P){if(P.invalid)throw _("add",z,"invalid-row",`row ${z} is invalid`);if(P.credential)throw _("add",z,"id-exists",`row ${z} already holds a credential`);if(r("add",P),P.type!==G.type)throw _("add",z,"type-mismatch",`row ${z} is a ${P.type} row`);if(B!==void 0&&P.identity!==void 0&&B!==P.identity)throw $6("add",z);if(!P.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let I=t4($,U,z,G,{clearErrors:!0,...F!==void 0?{providerState:{kind:"set",value:F}}:{}});await U.completeTorn();let f=await e4(U,z,I);if(!P.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:f,credentialEpoch:P.credentialEpoch??1}}let L=a4(U.config,z);if(!s(L))throw _("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let C=N?.identity??B;U.roster().push(S2({id:z,credential:G,...C!==void 0?{identity:C}:{},...W!==void 0?{label:W}:{},addedAt:X.now()})),U.setEntry(z,{credentialEpoch:L,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let T="added";if(Z.disabled)s0(U,z,Z.disabled.reason),T="added-disabled";if(!Z.disabled&&C!==void 0&&G.type==="oauth"){if(D.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===C))s0(U,z,L1),T="added-disabled"}if(N?.credential)return await U.commitConfig(),{id:z,outcome:T,credential:N.credential,credentialEpoch:N.credentialEpoch??L};U.dropStateAccount(z);let A=t4($,U,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...W!==void 0?{label:W}:{},...F!==void 0?{providerState:z2(F)}:{}}}:{},...F!==void 0?{providerState:{kind:"set",value:F}}:{}});if(q==="rotate")await U.completeTorn();let x=await e4(U,z,A);return await U.commitConfig(),{id:z,outcome:T,credential:x,credentialEpoch:L}},{completeTorn:!1})});if(!Q&&G.type==="oauth"&&(Y.outcome==="added"||Y.outcome==="completed"))$.firePull(Y.id,"add");return Y}async function V3($,Z,J,X={},z={}){a("replace");let{ctx:G}=$,B=await l(G,"replace",Z,z.onFailure,async(W,Q)=>{m1("replace",Z,J),E2("replace",Z,z.attribution);let Y=X.providerState===void 0?void 0:v0(G.providerState,"replace",Z,X.providerState),{row:V}=await M0($,"replace",Z);if(await W.acquire(Z0($,V)),J.type==="oauth")await W.acquire(z.providerLock??$.providerLock);for(let H of z.extraLocks??[])await W.acquire(H);return w(G,W,Q,{operation:"replace",rowId:Z},async(H)=>{if(z.attribution!==void 0)z6("replace",Z,H.row(Z),z.attribution),await H.completeTorn();let q=X6("replace",Z,H.row(Z),J);if(h(q)!==h(V))throw G4("replace",Z);let F=H.entry(Z)?.credentialEpoch,U=(typeof F==="number"?F:1)+1;if(!s(U))throw _("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let j=X3(G.providerState,q,U,X.identity,Y),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(b1(H,Z,U,K),X.identity!==void 0)T2(H,X.identity);let N=await J6($,H,Z,J,{clearErrors:!0,binding:K,providerState:j});return await H.commitConfig(),{id:Z,credential:N,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")$.firePull(Z,"replace");return B}async function H3($,Z,J,X={},z={}){a("rotate");let{ctx:G}=$;return l(G,"rotate",Z,z.onFailure,async(B,W)=>{m1("rotate",Z,J),E2("rotate",Z,z.attribution);let Q=X.providerState===void 0?void 0:v0(G.providerState,"rotate",Z,X.providerState),{row:Y}=await M0($,"rotate",Z);if(await B.acquire(Z0($,Y)),X.identity!==void 0&&J.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await B.acquire(V);return w(G,B,W,{operation:"rotate",rowId:Z},async(V)=>{if(z.attribution!==void 0)z6("rotate",Z,V.row(Z),z.attribution),await V.completeTorn();let H=X6("rotate",Z,V.row(Z),J);if(h(H)!==h(Y))throw G4("rotate",Z);if(r("rotate",H),X.identity!==void 0&&H.identity!==void 0&&X.identity!==H.identity)throw $6("rotate",Z);let q=X.identity!==void 0&&H.identity===void 0?X.identity:void 0,F=await J6($,V,Z,J,{identity:q,...Q!==void 0?{providerState:z4(G.providerState,"rotate",Z,H.providerState,Q)}:{}}),U=!1;if(!H.hasEntry)V.setEntry(Z,{credentialEpoch:1,needsFirstReading:H.type==="oauth"}),U=!0;if(X.identity!==void 0&&H.identity!==X.identity)J2(V,Z,X.identity),U=!0;if(U)await V.commitConfig();return{id:Z,credential:F}},{completeTorn:z.attribution===void 0})})}async function U3($,Z,J,X,z){a(Z);let{ctx:G}=$,B=G.providerState,W=z.attribution,Q=z.providerState;return l(G,Z,J,z.onFailure,async(Y,V)=>{if(E2(Z,J,W),Q!==void 0){if(typeof Q!=="function")throw _(Z,J,"invalid-input","the provider-state mutator must be a function");if(W===void 0)throw _(Z,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw _(Z,J,"invalid-input","the store was opened without a provider-state codec")}let{row:H}=await M0($,Z,J);await Y.acquire(Z0($,H));for(let q of z.extraLocks??[])await Y.acquire(q);return w(G,Y,V,{operation:Z,rowId:J},async(q)=>{await Z6(q,J,z.protect),q.assertNotStaged(J);let F=q.row(J),U=X.enabled?X6("enable",J,F):F;if(!U||!q.rosterRow(J))throw B0(Z,J);if(h(U)!==h(H))throw G4(Z,J);if(W!==void 0)z6(Z,J,U,W);if(X.enabled&&U.disabledReason?.startsWith(C2))throw _("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let j=!X.enabled||!U.enabled||U.disabledReason!==void 0;if(X.enabled&&j&&U.type==="oauth"){let M=U.identity===void 0?void 0:q.rows().find((P)=>P.id!==J&&P.invalid===void 0&&P.type==="oauth"&&P.enabled&&P.identity===U.identity);if(M)throw _("enable",J,"duplicate-identity",`row ${M.id} is enabled with the same identity as row ${J}`)}if(Q===void 0||B===void 0){if(await q.completeTorn(),!j)return{id:J};if(X.enabled)r2(q,J);else s0(q,J,X.reason);return await q.commitConfig(),{id:J}}if(!U.credential)throw _(Z,J,"no-credential",`row ${J} holds no credential`);r(Z,U);let K=await v1(q,B,Z,U,Q,!0);if(K.kind==="declined")return{id:J,declined:!0};await q.completeTorn();let N={id:J,providerStateOutcome:K.kind==="unchanged"?"unchanged":K.value===void 0?"cleared":"updated",...K.value!==void 0?{providerState:K.value}:{}};if(K.kind==="unchanged"){if(j){if(X.enabled)r2(q,J);else s0(q,J,X.reason);await q.commitConfig()}return N}if(!j)return q.setStateAccount(J,K.account),await q.commitState(),N;let D=X.enabled?{mark:Q3(),enabled:!0}:{mark:Q3(),enabled:!1,reason:X.reason},O=K.account[g];return q.setStateAccount(J,{...K.account,[g]:{...O,[i4]:D}}),await q.commitState(),Z4(q,J,D),await q.commitConfig(),N},{completeTorn:!1})})}function q3($,Z,J,X={}){return U3($,"disable",Z,{enabled:!1,reason:J},X)}function j3($,Z,J={}){return U3($,"enable",Z,{enabled:!0},J)}async function F3($,Z,J={}){a("remove");let{ctx:X}=$;return l(X,"remove",Z,J.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw _("remove",Z,"invalid-input","id must be non-empty");let B=J.attribution;if(E2("remove",Z,B),J.staged!==void 0&&(!S(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw _("remove",Z,"invalid-input","a staged removal needs a reservation");let W=await i(X);if(W.status!=="ready")throw $0(W,"remove",Z);let Q=W.rows.find((V)=>V.id===Z);if(!Q&&!A2(W.state,Z))throw B0("remove",Z);let Y=h(Q??{id:Z});await z.acquire(Z0($,Q??{id:Z}));for(let V of J.extraLocks??[])await z.acquire(V);return w(X,z,G,{operation:"remove",rowId:Z},async(V)=>{let H=V.reservation(Z);if(H!==void 0){if(!S(H)||!J.staged||H.reservation!==J.staged.reservation)throw _("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(J.staged)throw _("remove",Z,"attribution",`row ${Z} is no longer reserved`);let q=V.row(Z),F=A2(V.state,Z);if(!q&&!F)throw B0("remove",Z);if(h(q??{id:Z})!==Y)throw G4("remove",Z);if(B!==void 0)if(q)G6(Z,q,B);else IJ($,V,Z,B);let U=J.protect;if(U){let j={row:q,config:V.snapshot.config,state:V.snapshot.state},K=await G0("remove",()=>U(Z,j));if(K!==void 0)throw _("remove",Z,"row-protected",K)}if(q){if(B===void 0)await V.completeTorn();V.dropRosterRows(Z),await V.commitConfig()}if(F)V.dropStateAccount(Z),await V.commitState();return{id:Z,outcome:q?"removed":"completed"}},{completeTorn:!1})})}function G6($,Z,J,X="remove"){if(z6(X,$,Z,J),Z.torn)throw _(X,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw _(X,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function IJ($,Z,J,X){let z=()=>_("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=Z.stateAccount(J),B=t(G?.[g]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let W;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();W={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")W={type:"oauth",refresh:G.refresh};else throw z();let[Q]=i0({accounts:[S2({id:J,credential:W,identity:B.binding.identity,addedAt:0})],[v]:{rows:{[J]:{credentialEpoch:B.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!Q?.credential||Q.invalid||Q.stamp!=="bound")throw z();if(B.credentialEpoch!==X.credentialEpoch||B.binding.identity!==X.identity)throw _("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function A2($,Z){let J=$.accounts;return S(J)&&Object.hasOwn(J,Z)}function h1($){return S($)&&typeof $.id==="string"?$.id:void 0}function bJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let J=new Set;for(let G of $){let B=h1(G);if(B!==void 0)J.add(B)}let X=new Set;for(let G of Z){if(typeof G!=="string")return"ids must be an array of roster ids";if(X.has(G))return`id ${G} appears more than once`;if(!J.has(G))return`id ${G} is not in the roster`;X.add(G)}let z=[...J].filter((G)=>!X.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function kJ($,Z){let J=new Map;for(let G of $){let B=h1(G);if(B===void 0)continue;let W=J.get(B);if(W)W.push(G);else J.set(B,[G])}let X=Z.flatMap((G)=>J.get(G)??[]),z=0;return $.map((G)=>h1(G)===void 0?G:X[z++])}async function K3($,Z,J={}){a("reorder");let{ctx:X}=$,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let W of J.extraLocks??[])await G.acquire(W);return w(X,G,B,{operation:"reorder",rowId:void 0},async(W)=>{let Q=W.roster(),Y=bJ(Q,Z);if(Y)throw new b({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Y});let V=[...Z],H=kJ(Q,V);if(H.every((q,F)=>q===Q[F]))return{ids:V,outcome:"unchanged"};return W.config.accounts=H,await W.commitConfig(),{ids:V,outcome:"reordered"}},{completeTorn:!1})})}async function N3($,Z,J,X,z={}){return a("recordIdentity"),l($.ctx,"recordIdentity",Z,z.onFailure,async(G,B)=>{if(typeof J!=="string"||J.length===0)throw _("recordIdentity",Z,"invalid-input","identity must be non-empty");let W=S(X)?X.credentialEpoch:void 0;if(!s(W))throw _("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Q}=await M0($,"recordIdentity",Z);await G.acquire(Z0($,Q)),await G.acquire(z.providerLock??$.providerLock);for(let Y of z.extraLocks??[])await G.acquire(Y);return w($.ctx,G,B,{operation:"recordIdentity",rowId:Z},async(Y)=>{let V=X6("recordIdentity",Z,Y.row(Z));if(h(V)!==h(Q))throw G4("recordIdentity",Z);if(r("recordIdentity",V),(V.credentialEpoch??1)!==W)throw _("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(V.identity!==void 0&&V.identity!==J)throw $6("recordIdentity",Z);if(V.identity===void 0)await AJ(Y,V,J);let H=J2(Y,Z,J);return await Y.commitConfig(),{id:Z,disabled:H}})})}function P3($){let Z=$[v];return S(Z)&&S(Z.publications)?Z.publications:{}}function M3($,Z){let J=P3($);if(!Object.hasOwn(J,Z))return;let X=J[Z];if(!S(X)||X.operationId!==Z||typeof X.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(X.planDigest)||!["committed","cleaned"].includes(String(X.phase))||!Array.isArray(X.removed)||!Array.isArray(X.finalized)||X.removed.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch))||X.finalized.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw _("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function C3($,Z){let J=await i($.ctx);if(J.status!=="ready")throw $0(J,"publishRoster",Z);return M3(J.config,Z)}function xJ($,Z){let J=()=>{throw _("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId||!Array.isArray(Z.remove)||!Array.isArray(Z.finalize)||!Array.isArray(Z.order))J();let X=new Set;for(let z of[...Z.remove,...Z.finalize]){if(!S(z)||typeof z.id!=="string"||L2(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),E2("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of Z.remove)if($.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();for(let z of Z.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))J();if(Z.order.some((z)=>typeof z!=="string"||L2(z))||new Set(Z.order).size!==Z.order.length)J()}function T3($,Z){$.entries();let J=$.config[v],X={...P3($.config)};Object.defineProperty(X,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function yJ($,Z,J){let X=new Set;for(let B of O2($.config)){if(!S(B)||typeof B.id!=="string")continue;if(X.has(B.id))throw _("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(B.id)}let z=new Set(Z.remove.map((B)=>B.id)),G=J.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==Z.order.length||Z.order.some((B)=>!G.some((W)=>W.id===B))||G.some((B)=>!Z.order.includes(B.id)))throw _("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function D3($,Z){await $.assertAll();for(let X of Z.removed)if(t($.stateAccount(X.id)?.[g])?.credentialEpoch===X.credentialEpoch&&!$.rosterRow(X.id))$.dropStateAccount(X.id);for(let X of Z.finalized){let z=$.stateAccount(X.id),G=t(z?.[g]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let B={...z[g]};delete B.staged,$.setStateAccount(X.id,{...z,[g]:B})}}await $.commitState(void 0,{durable:!0});let J={...Z,phase:"cleaned"};return T3($,J),await $.commitConfig({durable:!0}),J}async function L3($,Z,J={}){return a("publishRoster"),l($.ctx,"publishRoster",Z?.operationId??"",J.onFailure,async(X,z)=>{if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw _("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=z2(Z),B=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((W)=>S(W)&&typeof W.id==="string");for(let W=0;;W++){let Q=await i($.ctx);if(Q.status!=="ready")throw $0(Q,"publishRoster",Z.operationId);let Y=new Map(B.map(({id:H})=>[H,h(Q.rows.find((q)=>q.id===H)??{id:H})]));for(let H of[...new Set(Y.values())].sort())await X.acquire(Z0($,{id:H}));await X.acquire(J.providerLock??$.providerLock);for(let H of J.extraLocks??[])await X.acquire(H);let V=await w($.ctx,X,z,{operation:"publishRoster",rowId:Z.operationId},async(H)=>{let q=H.rows();if(B.some(({id:P})=>h(q.find((L)=>L.id===P)??{id:P})!==Y.get(P)))return;let F=M3(H.config,Z.operationId);if(F){if(F.planDigest!==G)throw _("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(F.phase==="cleaned")return{outcome:"already-cleaned",receipt:F};return H.markPublicationDecision(),await H.syncConfig(),{outcome:"cleaned",receipt:await D3(H,F)}}xJ($,Z);let U=yJ(H,Z,q),j=[];for(let P of Z.remove){H.assertNotStaged(P.id);let L=q.find((C)=>C.id===P.id);if(!L)throw _("publishRoster",P.id,"attribution","the removed row no longer exists");if(G6(P.id,L,P.attribution,"publishRoster"),!L.credential||P.fingerprint!==void 0&&D0(L.credential)!==P.fingerprint)throw _("publishRoster",P.id,"attribution","the removed secret no longer matches");j.push(L)}let K=[];for(let P of Z.finalize){let L=q.find((f)=>f.id===P.id),C=t(H.stateAccount(P.id)?.[g]);if(!L||L.staged?.reservation!==P.reservation||C?.staged?.reservation!==P.reservation||L.enabled)throw _("publishRoster",P.id,"row-staged","the finalized row is not disabled under this reservation");let T=H.stateAccount(P.id),A=H.rosterRow(P.id),x=T?.[n],I=x===void 0?void 0:z2(x);if(!C?.staged||C.staged.label!==A?.label||C.staged.disabledReason!==L.disabledReason||C.staged.providerState!==I)throw _("publishRoster",P.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");G6(P.id,L,P.attribution,"publishRoster"),K.push(L)}let N=U.find((P)=>P.torn);if(N)throw _("publishRoster",Z.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let D=new Set;for(let P of U){if(!(Z.finalize.find((C)=>C.id===P.id)?.enabled??P.enabled)||P.type!=="oauth"||P.identity===void 0)continue;if(D.has(P.identity))throw _("publishRoster",P.id,"invalid-input","the final enabled roster repeats a known identity");D.add(P.identity)}for(let P of U)if(P.identity!==void 0&&P.fingerprint!==void 0&&U.some((L)=>L.id!==P.id&&L.identity!==void 0&&L.identity!==P.identity&&L.fingerprint===P.fingerprint))throw _("publishRoster",P.id,"attribution","the resulting pool gives the same secret different known identities");for(let P of K)if(P.identity!==void 0&&j.some((L)=>L.identity!==void 0&&L.identity!==P.identity&&L.fingerprint===P.fingerprint))throw _("publishRoster",P.id,"attribution","the staged secret belonged to a different known identity");await Z6(H,Z.operationId,J.protect);let O={operationId:Z.operationId,planDigest:G,phase:"committed",removed:j.map((P)=>({id:P.id,credentialEpoch:P.credentialEpoch??1})),finalized:Z.finalize.map((P,L)=>({id:P.id,credentialEpoch:K[L]?.credentialEpoch??1,reservation:P.reservation,enabled:P.enabled}))};for(let P of Z.remove)H.dropRosterRows(P.id);for(let P of Z.finalize){let L=H.rosterRow(P.id);L.enabled=P.enabled;let C={...H.entry(P.id)};if(delete C.staged,P.enabled)delete C.disabledReason;else C.disabledReason=P.disabledReason;H.setEntry(P.id,C)}let M=H.roster().filter((P)=>!S(P)||typeof P.id!=="string"||q.find((L)=>L.id===P.id)?.invalid==="roster");return H.config.accounts=[...Z.order.map((P)=>H.rosterRow(P)),...M],T3(H,O),await H.syncState(),await H.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await D3(H,O)}},{completeTorn:!1});if(V)return V;if(await X.releaseAll(),W>=1)throw _("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class w1{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,J,X,z){this.rt=$,this.hook=Z,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire($,Z){if(!this.hook)return;if(Z==="load"){if(this.firedAtLoad.has($))return;this.firedAtLoad.add($)}let J=this.run($,Z);this.inflight.add(J),J.finally(()=>this.inflight.delete(J))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run($,Z){let J=this.rt(),{ctx:X}=J,z=new A0(X.lockDefaults,X.lockEnv),G={writes:0};try{let B=await w(X,z,G,{operation:"pull",rowId:$},async(Y)=>{if(Y.reservation($)!==void 0)return;await Y.completeTorn();let V=Y.row($);if(V?.unbound&&V.enabled&&V.type==="oauth"&&V.credential&&!V.invalid)r("pull",V);if(!V?.candidate||V.type!=="oauth")return;if(!V.hasEntry)Y.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await Y.commitConfig();let H=Y.row($);if(!H?.credential||H.credentialEpoch===void 0)return;return{id:$,credential:H.credential,credentialEpoch:H.credentialEpoch,...H.identity!==void 0?{identity:H.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete($);return}await X.hold?.("pull-before-request",$);let W;try{W=await this.hook?.(B)}catch(Y){throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Y})}await(J.publishQuota??((Y,V,H)=>o4(J,Y,V,H)))($,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},W)}catch(B){this.firedAtLoad.delete($);let W=n0(B,"pull",$,G);if(this.onFailure)try{await this.onFailure($,W)}catch(Q){this.logger?.warn("pull failure hook threw",{rowId:$,error:Q instanceof Error?Q.message:String(Q)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:W.kind})}finally{await z.releaseAll()}}}var _3=100,B6=128;class u1{rt;timeoutMs;clock;pending=new Map;warned=new Set;wake=new Set;logger;timer;committedAt;running;closing;closed=!1;stopped=!1;failures=0;constructor($,Z=1000,J=S3){this.rt=$,this.timeoutMs=Z,this.clock=J,this.logger=$.ctx.logger??o("store")}async record($,Z,J){try{this.assertOpen($),f1($,Z);let X=structuredClone({id:$,attribution:Z,observation:J}),{row:z,result:G}=await M0(this.rt,"pull",$);J4($,X.attribution,z),X4(this.rt.ctx,$,this.overlayRow({...z,quota:R0(G.config,$)?.quota}).quota,X.observation),await this.room($),this.assertOpen($);let B=this.pending.get($)??[];if(B.push(X),this.pending.set($,B),B.length>=B6)this.flushNow();else this.schedule(_3)}catch(X){throw n0(X,"pull",$,{writes:0})}}queued($){return this.pending.get($)?.length??0}async room($){if(this.queued($)<B6)return;let{ctx:Z}=this.rt,J=Math.max(0,...Z.storeLocks.map((z)=>z.timeoutMs??Z.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued($)>=B6){this.assertOpen($),this.flushNow();let z=X-performance.now();if(z<=0)throw _("pull",$,"lock-contention",`pool quota queue for ${$} is full (${B6} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let B=()=>{clearTimeout(W),this.wake.delete(B),G()},W=setTimeout(B,z);this.wake.add(B)})}}assertOpen($){if(this.closed)throw _("pull",$,"invalid-input","pool quota writer is closed")}overlayRow($){let Z=$;for(let J of this.pending.get($.id)??[])try{J4($.id,J.attribution,$),Z={...Z,quota:X4(this.rt.ctx,$.id,Z.quota,J.observation),needsFirstReading:!1}}catch{}return Z}overlay($){return $.map((Z)=>this.overlayRow(Z))}schedule($){if(this.running||this.timer||!this.pending.size||this.stopped)return;let Z=this.closed?0:(this.committedAt??-1/0)+O3-this.clock.now();if(this.timer=this.clock.schedule(Math.max($,Z),()=>{return this.timer=void 0,this.flush()}),!this.closed)this.timer.unref?.()}cancelTimer(){this.timer?.cancel(),this.timer=void 0}flushNow(){if(this.running)return;this.cancelTimer(),this.flush()}flush(){if(this.running||this.stopped||!this.pending.size)return this.running??Promise.resolve();let $=[...this.pending.values()].flat(),Z={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new A0(Z.lockDefaults,Z.lockEnv);return this.running=(async()=>{try{await w(Z,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let B of $){let{id:W,attribution:Q,observation:Y}=B,V=JSON.stringify([W,Q.credentialEpoch,Q.identity]);try{z.assertNotStaged(W),J4(W,Q,z.row(W))}catch(F){if(!(F instanceof b))throw F;if(!this.warned.has(V))this.warned.add(V),this.warn("pool quota publication dropped; account binding changed",{id:W,kind:F.kind});continue}let H=z.entry(W);if(!H)continue;let q;try{q=X4(Z,W,H.quota,Y)}catch(F){let U=`codec:${V}`;if(!this.warned.has(U))this.warned.add(U),this.warn("pool quota publication dropped; the quota codec refused it",{id:W,error:F instanceof Error?F.message:String(F)});continue}z.setEntry(W,{...H,quota:q,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set($);for(let[z,G]of this.pending){let B=G.filter((W)=>!X.has(W));if(B.length)this.pending.set(z,B);else this.pending.delete(z)}this.failures=0}catch(X){if(!this.stopped&&this.failures++===0)this.warn("pool quota publication delayed; retrying",{error:X instanceof Error?X.message:String(X)})}finally{await J.releaseAll(),this.running=void 0;for(let z of this.wake)z();let X=this.failures?Math.min(5000,100*2**Math.min(this.failures,6))*(0.5+Math.random()):_3;this.schedule(X)}})(),this.running}warn($,Z){try{this.logger.warn($,Z)}catch{}}close(){if(this.closing)return this.closing;return this.closed=!0,this.closing=this.drain(),this.closing}async drain(){this.cancelTimer();let $,Z,J=new Promise((X)=>{Z=()=>{if(!this.pending.size)X()},this.wake.add(Z),Z()});try{this.flush(),await Promise.race([J,new Promise((X)=>{$=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout($),this.cancelTimer(),this.wake.delete(Z),this.pending.size)this.warn("pool quota drain timed out; pending readings left",{accounts:this.pending.size,readings:[...this.pending.values()].reduce((X,z)=>X+z.length,0)});this.pending.clear();for(let X of this.wake)X()}}}import{randomUUID as gJ}from"node:crypto";function p1($,Z){if(X2("refresh",$,Z?.staged),!Z)throw _("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw _("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw _("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw _("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function A3($){return _("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function E3($,Z,J,X={}){a("refresh");let{ctx:z}=$;return l(z,"refresh",Z,X.onFailure,async(G,B)=>{let{row:W}=await M0($,"refresh",Z);p1(Z,W);let Q=await X.refuse?.(W);if(Q!==void 0)return{status:"refused",rowId:Z,reason:Q};let Y=h(W),V;for(let U=0;;U++){await G.acquire(Z0($,{id:Z,identity:Y===Z?void 0:Y})),await G.acquire(X.providerLock??$.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await w(z,G,{writes:0},{operation:"refresh",rowId:Z},async(N)=>{let D=p1(Z,N.row(Z));if(r("refresh",D),!D.hasEntry)N.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),D=p1(Z,N.row(Z));if(h(D)!==Y)return{keyNow:h(D)};let O=await X.refuse?.(D);if(O!==void 0)return{refused:O};return{row:D,credential:D.credential,credentialEpoch:D.credentialEpoch,identity:D.identity}});if("refused"in K)return{status:"refused",rowId:Z,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),U>=1)throw _("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);Y=K.keyNow;continue}V=K;break}if(I1(V.credential.lastRefreshedAt,z.now()))throw A3(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let H;try{H=await J(V.credential,V.row)}catch(U){throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof H?.refresh!=="string"||!H.refresh.trim())throw _("refresh",Z,"provider","the provider returned no refresh token",!0);let q=H.providerState===void 0?void 0:v0(z.providerState,"refresh",Z,H.providerState,"the provider state the provider returned"),F=await w(z,G,B,{operation:"refresh",rowId:Z},async(U)=>{let j=U.row(Z),K=U.entry(Z);if(!j||j.invalid||!K||K.credentialEpoch!==V.credentialEpoch||j.identity!==V.identity)throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${Z} changed credential while its refresh was in flight; the rotation is discarded`});r("refresh",j);let N=await X.refuse?.(j);if(N!==void 0)return{refused:N};let D=z.now(),O=j.credential?.type==="oauth"?j.credential.lastRefreshedAt:void 0;if(I1(O,D))throw A3(Z);let M={type:"oauth",access:H.access,refresh:H.refresh,expires:H.expires},P=j.identity!==void 0&&H.identity!==void 0&&j.identity!==H.identity?{expectedIdentity:j.identity,returnedIdentity:H.identity}:void 0,L=P?{mark:gJ(),enabled:!1,reason:`${C2}${JSON.stringify(P)}`}:void 0,C=j.identity===void 0&&H.identity?H.identity:void 0,T=await J6($,U,Z,M,{stamp:$4(O,D),transition:L,identity:C,...q!==void 0?{providerState:z4(z.providerState,"refresh",Z,j.providerState,q)}:{}});if(L!==void 0)Z4(U,Z,L),await U.commitConfig();let A=j.identity;if(C!==void 0)J2(U,Z,C),A=C,await U.commitConfig();return{stored:T,identity:A,contradiction:P,refused:void 0}});if(F.refused!==void 0)return{status:"refused",rowId:Z,reason:F.refused};if(F.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...F.contradiction,credential:F.stored};if(X.onPersisted)try{let U=X.onPersisted;await G0("refresh",()=>U(Z,F.stored),!0)}catch(U){throw new b({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:F.stored,message:"the after-persist hook threw; the rotation stays committed",cause:U})}return{status:"rotated",rowId:Z,credential:F.stored,...F.identity!==void 0?{identity:F.identity}:{}}})}import{isDeepStrictEqual as R3}from"node:util";var Y6=Object.freeze(["version","accounts",v]);function Q6($){let Z={};for(let[J,X]of Object.entries($))if(!Y6.includes(J))W6(Z,J,X);return Z}function W6($,Z,J){Object.defineProperty($,Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function fJ($,Z){let J={};for(let[X,z]of Object.entries($))if(Y6.includes(X)||X==="commonAuthLimits")W6(J,X,z);else if(Object.hasOwn(Z,X))W6(J,X,Z[X]);for(let[X,z]of Object.entries(Z))if(!Object.hasOwn($,X))W6(J,X,z);return J}function l1($){return new b({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}var vJ=new I3;async function b3($){let Z=async([X=$.ctx.configPath]=[])=>{let z=await e$(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:Q6(z.config)}},J=r4?await Z():await vJ.read([$.ctx.configPath],Z);return structuredClone(J)}async function k3($,Z,J={}){a("updateSettings");let{ctx:X}=$,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Q of J.extraLocks??[])await G.acquire(Q);let W=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let Q=await i(X);if(Q.status!=="ready")throw $0(Q,"updateSettings",void 0);let Y=Q6(Q.config),V=structuredClone(Y),H=await G0("updateSettings",()=>Z(V)),q=H===void 0?V:H;if(!S(q))throw l1("the settings mutator must produce an object");let F=Y6.filter((K)=>Object.hasOwn(q,K));if(F.length>0)throw l1(`settings cannot set the pool-owned key(s) ${F.join(", ")}`);if(Object.hasOwn(q,"commonAuthLimits")&&(!Object.hasOwn(Y,"commonAuthLimits")||!R3(q.commonAuthLimits,Y.commonAuthLimits)))throw l1("settings cannot alter commonAuthLimits; use updateLimitsNamespace");let U=fJ(Q.config,q);if(R3(Q6(U),Y))return{settings:Y,outcome:"unchanged"};let j={operation:"updateSettings",rowId:void 0};return await P0(X.configPath,U,{beforeRename:async()=>{await X.onStep?.("before-config-write",j),await G.assertAll()}}),B.writes++,await X.onStep?.("after-config-write",j),{settings:Q6(U),outcome:"updated"}}finally{await G.releaseTo(W)}})}var x3=new Map;function hJ($){let Z=x3.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},x3.set($,Z);return Z}function y3($){if($.status==="ready")return{status:"ready",schemaVersion:a0,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function B4($){let Z=hJ($.configPath),J={..._1,...$.lockOptions},X={provider:$.provider,configPath:$.configPath,statePath:$.statePath,codec:$.quota,...$.providerState?{providerState:$.providerState}:{},now:$.now??Date.now,storeLocks:$.storeLocks??[{name:"save",path:$.configPath},{name:"save",path:$.statePath}],lockDefaults:J,lockEnv:{...$.onLockEvent?{onLockEvent:$.onLockEvent}:{},...$.onLockStep?{onLockStep:$.onLockStep}:{},...$.onRenewalTimer?{onRenewalTimer:$.onRenewalTimer}:{}},removedIds:Z.removedIds,requireCredentialStamps:$.requireCredentialStamps===!0,requireRemovedFingerprint:$.requireRemovedFingerprint===!0,...$.logger?{logger:$.logger}:{},...$.onStep?{onStep:$.onStep}:{},...$.hold?{hold:$.hold}:{}},z=new w1(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:X,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(Y,V)=>z.fire(Y,V)},B=$.coalesceQuota?new u1(G,$.quotaDrainTimeoutMs,$.quotaCommitTimer):void 0,W=(Y,V,H)=>B?B.record(Y,V,H):o4(G,Y,V,H);G.publishQuota=W;let Q=(Y)=>{if(Y.status==="ready"&&B)return{...Y,rows:B.overlay(Y.rows)};return Y};return{async load(){let Y=Q(await i(X));if(Y.status==="ready"){for(let V of Y.rows)if((V.candidate||V.torn&&V.enabled)&&V.type==="oauth"&&V.needsFirstReading)z.fire(V.id,"load")}return y3(Y)},async read(){return y3(Q(await i(X)))},async initialize(Y={}){return{status:await Z3(X,Y.dropKeys??[])}},add:(Y,V)=>Y3(G,Y,V),publishRoster:(Y,V)=>L3(G,Y,V),publication:(Y)=>C3(G,Y),replace:(Y,V,H,q)=>V3(G,Y,V,H,q),rotate:(Y,V,H,q)=>H3(G,Y,V,H,q),updateProviderState:(Y,V,H,q)=>G3(G,Y,V,H,q),disable:(Y,V,H)=>q3(G,Y,V,H),enable:(Y,V)=>j3(G,Y,V),remove:(Y,V)=>F3(G,Y,V),reorder:(Y,V)=>K3(G,Y,V),readSettings:()=>b3(G),updateSettings:(Y,V)=>k3(G,Y,V),updateLimitsNamespace:(Y,V)=>J3(G,Y,V),recordIdentity:(Y,V,H,q)=>N3(G,Y,V,H,q),refresh:(Y,V,H)=>E3(G,Y,V,H),recordQuota:W,close:()=>B?.close()??Promise.resolve(),dispose:()=>B?.close()??Promise.resolve(),requestReading:(Y)=>z.fire(Y,"admission"),pullsSettled:()=>z.settled()}}var mJ=[/\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 s1($={}){let{redactStrings:Z}=g3({...$,extraValuePatterns:[...mJ,...$.extraValuePatterns??[]]});return(J)=>Z(J)}class u extends Error{code;constructor($,Z,J){super(Z,J);this.name="CommandError",this.code=$}}var f3=/^[a-z][a-z0-9-]{0,63}$/,d1={code:"action-failed",text:"That action failed."},wJ=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 Q4($){if($ instanceof u)return{code:f3.test($.code)?$.code:d1.code,text:$.message};if($ instanceof b)return{code:`pool-${$.kind}`,text:wJ.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return d1}var v3="This cannot be undone. Continue?",uJ=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function pJ($){let Z=$.toLowerCase().replace(/[-_]/g,"");return uJ.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function lJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function c1($,Z,J){if(typeof $==="string"){let z=J.redact($);if(z!==$)J.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>c1(z,`${Z}[${G}]`,J));if(!lJ($))return $;let X={};for(let[z,G]of Object.entries($)){if(pJ(z)){J.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(X,z,{value:c1(G,`${Z}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function h3($,Z,J){let X={redact:J.redact,dropped:[],redacted:[]},z=c1($,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:Z,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:Z,fields:X.redacted});return z}function dJ($){return{value:String($.value),label:String($.label)}}function cJ($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(dJ),...$.value!==void 0?{value:$.value}:{}};case"toggle":return{kind:"toggle",id:$.id,label:$.label,value:$.value===!0};case"number":return{kind:"number",id:$.id,label:$.label,...$.value!==void 0?{value:$.value}:{},...$.min!==void 0?{min:$.min}:{},...$.max!==void 0?{max:$.max}:{},...$.required?{required:!0}:{}};case"text":return{kind:"text",id:$.id,label:$.label,...$.value!==void 0&&!$.masked?{value:$.value}:{},...$.placeholder!==void 0?{placeholder:$.placeholder}:{},...$.masked?{masked:!0}:{},...$.required?{required:!0}:{}}}}function a1($){if($.irreversible===!0)return{message:$.confirm||v3,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function m3($){let Z=a1($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(cJ),...Z?{confirm:Z}:{}}}function sJ($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function aJ($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:sJ($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(m3)}}function iJ($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(aJ),actions:(Z.actions??[]).map(m3),...Z.facts!==void 0?{facts:Z.facts}:{}}}function w3($,Z,J){return{command:$,title:Z,sections:J.map(iJ)}}function u3($,Z,J,X){return h3({command:$,menu:w3($,Z,J)},$,X)}function p3($,Z,J,X,z){return h3({command:$,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:f3.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:w3($,Z,J)},$,z)}var n3="disabled from the command menu";function nJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function C0($){return nJ($)?{...$}:{}}function rJ($){if($.status!=="ready")return[];let Z=new Set;return $.rows.filter((J)=>{if(Z.has(J.id))return!1;return Z.add(J.id),!0})}function oJ($,Z){return $.label??Z??$.id}function V6($,Z){return r0($.quota)?b0($.quota,Z):void 0}function r3($,Z){return`${$} ${Z}${$===1?"":"s"}`}var R2="Actions";function tJ($){if($.status==="pending-migration")return"The account pool has not been migrated yet.";if($.status==="error")return`The ${$.file} file cannot be read: ${$.reason}`;return}function l3($,Z){switch(Z.outcome){case"added":return`Added ${$}.`;case"added-disabled":return`Added ${$}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${$}.`;case"rotated":return`${$} was already in the pool; its credential was updated.`;case"exists":return`${$} was already in the pool; its credential is unchanged.`}}function d3($){return Q4($).text}async function eJ($){let{store:Z}=$,J=await Z.read(),X=await Z.readSettings(),z=await $.routing?.vaultOrder?.();return{load:J,rows:rJ(J),settings:X.status==="error"?{}:X.settings,...z?{vault:z}:{}}}function H6($,Z){let J=Z.accounts?.describeIdentity?Z.accounts.describeIdentity($):$.identity;return{account:{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...J!==void 0?{identity:J}:{}},name:oJ($,J)}}function $X($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=Z.rows.map((H)=>H.id),B=tJ(Z.load),W=Z.rows.filter((H)=>H.enabled).length,Q=Z.rows.map((H,q)=>{let{account:F,name:U}=H6(H,$),j=[H.type==="api"?"API key":"OAuth",...F.identity!==void 0?[F.identity]:[],...!H.invalid&&!H.enabled&&H.disabledReason?[`disabled: ${H.disabledReason}`]:[]].join(" · "),K=H.invalid?"invalid":H.enabled?"enabled":"disabled",N=[];if(!H.invalid&&H.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(H.id,n3,z),`Disabled ${U}.`}});if(!H.invalid&&!H.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(H.id,z),`Enabled ${U}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((D,O)=>({value:String(O+1),label:String(O+1)})),value:String(q+1)}],run:async({values:D})=>{let O=Number(D.position),M=G.filter((L)=>L!==H.id);return M.splice(O-1,0,H.id),(await J.reorder(M,z)).outcome==="unchanged"?`${U} is already at position ${O}.`:`Moved ${U} to position ${O}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await J.remove(H.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${U}.`}}),{id:H.id,label:U,detail:j,group:"Accounts",status:K,account:F,actions:N}}),Y=$.accounts?.login,V=[];if(Y&&!B)V.push({id:"add",label:Y.label??"Add account",group:R2,knobs:Y.knobs??[],run:async({values:H,invocation:q})=>{let F=await Y.run(H,q);if(F.status==="cancelled")return{ok:!1,text:F.message??"Login cancelled."};if(F.status==="ready"){let U=await J.add(F.account,z);return l3(F.account.label??U.id,U)}return F.completion.then(async(U)=>{if(!U){q.notify("Login cancelled.","warning");return}let j=await J.add(U,z);q.notify(l3(U.label??j.id,j))},(U)=>{q.notify(`Adding the account failed: ${d3(U)}`,"error")}).catch((U)=>{q.notify(`Adding the account failed: ${d3(U)}`,"error")}),F.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[Z.rows.length===0?"No accounts yet":`${r3(Z.rows.length,"account")}, ${W} enabled`],items:B?[]:Q,actions:V}}}function ZX($,Z){let J=$.quota?.scope??"all",X=$.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(V,H)=>{if($.quota?.check)await $.quota.check(V,H);else{for(let q of V)$.store.requestReading(q);await $.store.pullsSettled()}},B=Z.rows.filter((V)=>V.candidate),W=B.map((V)=>{let{account:H,name:q}=H6(V,$),F=V6(V,J);return{id:V.id,label:q,group:z,status:I0(F,{now:X,form:"compact"}),detail:I0(F,{now:X,form:"full"}),account:H,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([V.id],U),`Checked quota for ${q}.`}}]}}),Q=Z.rows.filter((V)=>!V.candidate).map((V)=>{let{name:H}=H6(V,$),q=V.invalid?"invalid":!V.enabled?"disabled":V.credential===void 0?"no credential":"unavailable",F=I0(V6(V,J),{now:X,form:"compact"});return`${H} (${q}): ${F}`}),Y=[];if(B.length>0)Y.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:R2,run:async({invocation:V})=>{let H=B.map((q)=>q.id);return await G(H,V),`Checked quota for ${r3(H.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Q,items:W,actions:Y}}}async function JX($,Z){try{return await $.reorder(Z)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new u("vault-invalid-order",J.message,{cause:J});throw J}}function i1($){return new u("vault-invalid-order",$)}function XX($){let Z=$.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>Z.filter((z)=>z.id===X||z.label===X);return{ids:Z.map((X)=>X.id),nameOf:(X)=>Z.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let z=Z.find((G)=>G.id===X);return z&&!/[,\n]/.test(z.label)&&J(z.label).length===1?z.label:X},resolve:(X)=>{let z=[];for(let G of X){let B=J(G);if(B.length===0)throw i1(`"${G}" is not a vault account.`);if(B.length>1)throw i1(`"${G}" matches more than one vault account; enter those accounts by route id.`);let W=B[0].id;if(z.includes(W))throw i1(`"${G}" names an account already in the order.`);z.push(W)}return z}}}function zX($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=C0(Z.settings.routing).mode,W=typeof B==="string"&&G.some((K)=>K.value===B)?B:"ordered",Q=a3(W),Y=Z.vault?XX(Z.vault):void 0,V=Y?Y.ids:Z.rows.map((K)=>K.id),H=(K)=>Y?Y.nameOf(K):K,q=i3(V,Q.placement,$.routing?.formerMainId??s3),U=[`Mode: ${G.find((K)=>K.value===W)?.label??W}`];if(V.length>0)U.push(`${Y?"Vault account order":"Roster order"}: ${V.map(H).join(", ")}`);if(Q.mode==="ordered"&&q.join()!==V.join())U.push(`Tried in order: ${q.map(H).join(", ")}`);let j=[{id:"mode",label:"Change mode",group:R2,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:W}],run:async({values:K})=>{let N=String(K.mode);return await J.updateSettings((D)=>{D.routing={...C0(D.routing),mode:N};return},z),`Routing mode set to ${G.find((D)=>D.value===N)?.label??N}.`}}];if(V.length>1)j.push({id:"order",label:"Set order",group:R2,knobs:[{kind:"text",id:"order",label:Y?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:Y?V.map(Y.entryOf).join(", "):V.join(", "),required:!0}],run:async({values:K})=>{let D=String(K.order).split(Y?/[,\n]+/:/[\s,]+/).map((M)=>M.trim()).filter((M)=>M.length>0),O=Z.vault&&Y?await JX(Z.vault,Y.resolve(D)):await J.reorder(D,z);return O.outcome==="unchanged"?"The order is unchanged.":`Order set to ${O.ids.map(H).join(", ")}.`}});if($.routing?.sameAccountWait){let N=[{value:"0",label:"Don't wait"},{value:"15",label:"15 minutes"},{value:"max",label:"Until the cache expires"}],D=C0(Z.settings.routing).maxSameAccountWait,O=String(D===0||D==="max"?D:15),M=(P)=>N.find((L)=>L.value===P)?.label??P;U.push(`Longest wait on the same account: ${M(O)}`),j.push({id:"maxSameAccountWait",label:"Longest wait on the same account",group:R2,knobs:[{kind:"choice",id:"maxSameAccountWait",label:"Longest wait on the same account",choices:N,value:O}],run:async({values:P})=>{let L=String(P.maxSameAccountWait),C=L==="max"?"max":Number(L);return await J.updateSettings((T)=>{T.routing={...C0(T.routing),maxSameAccountWait:C};return},z),`Longest wait on the same account set to ${M(L)}.`}})}return{id:"routing",slot:"routing",title:"Routing",content:{lines:U,actions:j}}}function GX($,Z){if($.limits?.labels)return[...$.limits.labels];let J=$.quota?.scope??"all",X=[];for(let z of Z.rows)for(let G of V6(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function BX($,Z){let J=$.quota?.scope??"all",X=new Map;for(let z of Z.rows)for(let G of V6(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,c3(G));return(z)=>X.get(z)??z}function QX($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=C0(Z.settings.killswitch),B=G.enabled===!0,W=C0(G.accounts),Q=GX($,Z),Y=BX($,Z),V=B?"on":"off",H=Z.rows.map((q)=>{let{account:F,name:U}=H6(q,$),j=C0(W[q.id]),K=Q.filter((N)=>typeof j[N]==="number");return{id:q.id,label:U,group:`Floors · killswitch ${V}`,status:K.length===0?"no floors":K.map((N)=>`${Y(N)} ≥${j[N]}%`).join(" · "),account:F,actions:[{id:"floors",label:"Set floors",knobs:Q.map((N)=>({kind:"number",id:N,label:`Minimum % left for ${Y(N)}`,min:0,max:100,...typeof j[N]==="number"?{value:j[N]}:{}})),run:async({values:N})=>{return await J.updateSettings((D)=>{let O=C0(D.killswitch),M=C0(O.accounts),P=C0(M[q.id]);for(let L of Q){let C=N[L];if(typeof C==="number")P[L]=C;else if(C===null)delete P[L]}if(Object.keys(P).length>0)M[q.id]=P;else delete M[q.id];if(Object.keys(M).length>0)O.accounts=M;else delete O.accounts;D.killswitch=O;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${V}`],items:H,actions:[{id:"killswitch",label:B?"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:R2,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:q})=>{let F=q.enabled===!0;return await J.updateSettings((U)=>{U.killswitch={...C0(U.killswitch),enabled:F};return},z),`Killswitch ${F?"on":"off"}.`}}]}}}async function o3($){let Z=await eJ($);return[$X($,Z),ZX($,Z),zX($,Z),QX($,Z)]}var WX=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),n1=["accounts","quota","routing","limits"];function t3($,Z){let{sessionId:J}=$,X=$.notify.bind($);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X(Z(String(z))):X(Z(String(z)),G)})}function YX($,Z){switch($.kind){case"choice":{let J=Z??$.value;if(typeof J==="string"&&$.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${$.label}.`}}case"toggle":{let J=Z??$.value;return typeof J==="boolean"?{value:J}:{problem:`${$.label} must be on or off.`}}case"number":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${$.label} needs a number.`};if($.min!==void 0&&X<$.min)return{problem:`${$.label} must be at least ${$.min}.`};if($.max!==void 0&&X>$.max)return{problem:`${$.label} must be at most ${$.max}.`};return{value:X}}case"text":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${$.label} must be text.`}}}}function VX($,Z){let J={};for(let X of $){let z=Z&&Object.hasOwn(Z,X.id)?Z[X.id]:void 0,G=YX(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function HX($,Z){let J=$.find((z)=>z.id===Z.sectionId);if(!J)return;return(Z.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===Z.itemId)?.actions)?.find((z)=>z.id===Z.actionId)}function G2($){let Z=$.logger??o("commands"),J=s1($.redaction),X={logger:Z,redact:J},z=$.now??Date.now,G=$.extras??[],B=$.replace??{},W=n1.filter((q)=>!B[q]);for(let q of n1)if(B[q]&&$[q]!==void 0)throw Error(`the ${q} section is replaced; its built-in options cannot also be given`);let Q=$.store;if(W.length>0&&!Q)throw Error(`a store is required for the built-in ${W.join(", ")} section${W.length>1?"s":""}`);let Y=new Set;for(let q of G){if(WX.has(q.id)||Y.has(q.id))throw Error(`extra section id ${q.id} is taken`);Y.add(q.id)}async function V(q,F,U,j){try{return{id:q,slot:F,title:U.title,content:await U.build(j)}}catch(K){return Z.warn("command menu section failed to build",{command:$.command,section:q,error:J(K instanceof Error?K.message:String(K))}),{id:q,slot:F,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function H(q){let F=Q&&W.length>0?await o3({store:Q,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],U=[];for(let j of n1){let K=B[j];if(K)U.push(await V(j,j,K,q));else{let N=F.find((D)=>D.slot===j);if(N)U.push(N)}}if($.cache)U.push(await V("cache","cache",$.cache,q));if($.diagnostics)U.push(await V("diagnostics","diagnostics",$.diagnostics,q));for(let j of G)U.push(await V(j.id,"extra",j,q));return U}return{command:$.command,async open(q){let F=t3(q,J);return u3($.command,$.title,await H(F),X)},async apply(q,F){let U=t3(F,J),j=async(M)=>p3($.command,$.title,await H(U),M,X),K=q.command===$.command?HX(await H(U),q):void 0;if(!K)return j({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=a1(K);if(N&&q.confirmed!==!0)return j({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let D=VX(K.knobs??[],q.values);if("problem"in D)return j({ok:!1,code:"invalid-input",text:D.problem});let O;try{let M=await K.run({values:D.values,...q.itemId!==void 0?{itemId:q.itemId}:{},invocation:U});O=typeof M==="string"?{ok:!0,text:M}:{ok:M.ok,text:M.text,...M.ok?{}:{code:M.code??"refused"}}}catch(M){let P=Q4(M);Z.warn("command menu action failed",{command:$.command,section:q.sectionId,action:q.actionId,code:P.code,error:J(M instanceof Error?M.message:String(M))}),O={ok:!1,...P}}return j(O)}}}function UX($){return $===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($)}function qX($){if($===null||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.command!=="string"||typeof Z.sectionId!=="string"||typeof Z.actionId!=="string")return;if(Z.itemId!==void 0&&typeof Z.itemId!=="string")return;if(Z.sessionId!==void 0&&typeof Z.sessionId!=="string")return;if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return;let J={};if(Z.values!==void 0){if(Z.values===null||typeof Z.values!=="object"||Array.isArray(Z.values))return;for(let[X,z]of Object.entries(Z.values)){if(!UX(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:Z.command,sectionId:Z.sectionId,actionId:Z.actionId,...typeof Z.itemId==="string"?{itemId:Z.itemId}:{},...Z.values!==void 0?{values:J}:{},...Z.confirmed===!0?{confirmed:!0}:{},...typeof Z.sessionId==="string"?{sessionId:Z.sessionId}:{}}}function E($,Z){return $.namespace===Z.namespace&&$.accountId===Z.accountId&&$.incarnation===Z.incarnation}function e3($,Z){if($.kind!==Z.kind)return!1;if($.kind==="model")return Z.kind==="model"&&$.model===Z.model;if($.kind==="family")return Z.kind==="family"&&$.family===Z.family;return!0}function jX($){return{requestId:$.requestId,originalUrl:$.originalUrl,requestStartedAt:$.clockNow,saw429:!1,tried:[],excludedForRequest:[],retains:[],retainedAttempts:[],excludedAttempts:[],switchedAttempts:[],switches:0}}function U6($,Z,J){return $.excludedForRequest.some((X)=>E(X.account,Z)&&e3(X.scope,J))}function I2($,Z){switch(Z.type){case"response":{let J=$.tried.some((X)=>E(X.account,Z.account)&&e3(X.scope,Z.scope))?$.tried:[...$.tried,{account:{...Z.account},scope:{...Z.scope}}];return{...$,tried:J,saw429:$.saw429||Z.status===429,...Z.kind==="payment-balance"?{sawPaymentBalance:!0}:{},lastStatus:Z.status}}case"retain":{if(Z.cause==="credential-recovery"||$.retainedAttempts.includes(Z.attemptId))return $;let J=$.retains.find((X)=>E(X.account,Z.account));return{...$,retainedAttempts:[...$.retainedAttempts,Z.attemptId],retains:[...$.retains.filter((X)=>!E(X.account,Z.account)),{account:{...Z.account},count:(J?.count??0)+1,startedAt:J?.startedAt??Z.clockNow,lastRetainedAt:Z.clockNow}]}}case"exclude":if($.excludedAttempts.includes(Z.attemptId))return $;return{...$,excludedAttempts:[...$.excludedAttempts,Z.attemptId],excludedForRequest:U6($,Z.account,Z.scope)?$.excludedForRequest:[...$.excludedForRequest,{account:{...Z.account},scope:{...Z.scope}}]};case"switch":return $.switchedAttempts.includes(Z.attemptId)?$:{...$,switchedAttempts:[...$.switchedAttempts,Z.attemptId],switches:$.switches+1};case"blocked":return $.blockedSince===void 0?{...$,blockedSince:Z.clockNow}:$;case"selected":{let{blockedSince:J,...X}=$;return X}}}var r1=Object.freeze({refundHybridToken:!0,cancelDiscardedBody:!0,addMark:!1,addCooldown:!1,penalizeHealth:!1,chargeSwitch:!1});function B2($){return $!==void 0&&Number.isFinite($)&&$>=0?$:300000}function q6(){let $=new Map;return{get size(){return $.size},recordAccepted(Z){if(!E(Z.accountKey,Z.currentAccountKey)||!Number.isFinite(Z.lastAcceptedAt))return!1;let J=$.get(Z.sessionId);if(J&&J.lastAcceptedAt>Z.lastAcceptedAt)return!1;let X=typeof Z.ttlMs==="number"?[Z.ttlMs]:Z.ttlMs,z=X?.length?Math.max(...X.map(B2)):B2(void 0);if($.set(Z.sessionId,Object.freeze({accountKey:Object.freeze({...Z.accountKey}),lastAcceptedAt:Z.lastAcceptedAt,ttlMs:z})),$.size>256){let G,B=Number.POSITIVE_INFINITY;for(let[W,Q]of $)if(Q.lastAcceptedAt<B)G=W,B=Q.lastAcceptedAt;if(G!==void 0)$.delete(G)}return!0},get(Z){return $.get(Z)},forgetSession(Z){$.delete(Z)}}}function j6($,Z,J){switch($.kind){case"pool":return!0;case"family":return J(Z)===$.family;case"model":return $.model===Z}}var W4=3621000;function h0($){return $===0||$===15||$==="max"?$:15}function Y4($){let Z=h0($.maxSameAccountWait),J=$.activity;if(Z===0||!J||!E(J.accountKey,$.accountKey)||!Number.isFinite(J.lastAcceptedAt))return;let X=B2(J.ttlMs),z=J.lastAcceptedAt+X;if(X===0||!Number.isFinite(z))return;return{cacheExpiresAt:z,maxWaitMs:Z==="max"?Number.POSITIVE_INFINITY:900000}}import{createHash as FX}from"node:crypto";function o1($,Z){let J=FX("sha256").update($).digest().readUInt32BE(0);return 1000*(Math.max(1,Math.ceil(Z/1000))+J%21)}function F6($,Z){if(!Number.isFinite($.maxAgeMs)||$.maxAgeMs<0)return;let J;for(let X of $.candidates){if(!E(X.account,X.readingAccount)||X.identity!==void 0&&X.readingIdentity!==void 0&&X.identity!==X.readingIdentity)continue;let z=X.windows.filter((Q)=>Q.blockedBy&&j6(Q.scope,$.effectiveModel,$.familyOf));if(!z.length)continue;let G=z.map((Q)=>{let Y=Q.reset,V=Y?.observedAt??Y?.checkedAt;return Y&&V!==void 0&&Number.isFinite(V)&&Z-V<=$.maxAgeMs&&Number.isFinite(Y.at)&&Y.at>Z?Y.at:void 0});if(G.some((Q)=>Q===void 0))continue;let B=Math.max(...G);if(J&&J.resetAt<=B)continue;let W=z.some((Q)=>Q.blockedBy!=="exhausted"&&Q.reset?.at===B);J={account:X.account,resetAt:B,checkpoint:{accountKey:{...X.account},decidedAt:Z,blockers:W?[]:z.flatMap((Q)=>Q.blockedBy==="exhausted"&&Q.reset?[{window:Q.window,resetAt:Q.reset.at}]:[])}}}return J}function $5($,Z){return $.source==="pool"&&$.reason==="quota"&&Z.terminalMetadata==="setting-capped-fresh"}function Z5($,Z){return $5($,Z)&&h0($.scan?.maxSameAccountWait)===0}function J5($,Z,J,X){if(!$5(X,Z))return;let z=X.scan,G=h0(z?.maxSameAccountWait),B=z&&F6(z,$.now),W=B?B.resetAt-$.now:300000,Q=z?.activity,Y=z?.accountKey??$.attempted,V=Q&&Y&&E(Q.accountKey,Y)?B2(Q.ttlMs)||300000:300000,H=Math.min(W,G==="max"?V:900000),q=G===0||$.host==="pi"&&$.wake?.kind==="terminal",F=q?B?W:void 0:H,U=Z.refusals.quota[$.host],j={action:"refuse",reason:"quota",family:$.host==="pi"?"pi-final":q?"json-412":U.family,messageKey:X.messageKey??U.messageKey,retryable:$.host!=="pi"&&!q,hostRetry:$.host==="pi"||q?"veto":"leave",history:J,...F===void 0?{}:{retryAfterMs:F},...B?{resetAt:B.resetAt}:{}};if(!B||q||$.host==="opencode1")return j;let K={delayMs:H,retryAfterMs:H,resetAt:B.resetAt,target:$.now+H,checkpoint:B.checkpoint,waitKind:"terminal",reason:"terminal-quota",retryable:!0,hostRetry:"leave",history:J};if($.host==="pi")return{...K,action:"wait-then-reselect"};if($.hostPhase!=="retry")return j;if($.remainingRetries!==void 0&&$.remainingRetries<1)return{action:"pass",reason:"host-retries-exhausted",retryable:!0,hostRetry:"leave",history:J};if($.remainingRetries===void 0||H>W4)return j;return{...K,action:"hold",account:B.account}}function t1($,Z,J){return{accountKey:{...$},decidedAt:Z,blockers:J.filter((X)=>X.confirmed&&Number.isFinite(X.resetAt)).map((X)=>({window:X.window,resetAt:X.resetAt}))}}function X5($,Z,J,X){let{checkpoint:z,target:G}=$;if(!E(Z,z.accountKey)||!Number.isFinite(G)||!Number.isFinite(z.decidedAt)||G<z.decidedAt||!Number.isFinite(X)||X<G)return[];let B=(W)=>{let Q=W.resetAt;return W.confirmed&&Q!==void 0&&Number.isFinite(Q)&&Q<=G&&z.blockers.some((Y)=>Y.window===W.window&&Number.isFinite(Y.resetAt)&&Q<=Y.resetAt)};return J.filter((W)=>B(W)&&J.filter((Q)=>Q.confirmed&&Q.window===W.window).every(B)).map((W)=>W.window)}function K6($,Z){return $!==void 0&&Number.isFinite($)&&$>Z}function b2($,Z){return Z.execution==="engine"&&$.phase==="after-limit"?"veto":"leave"}function k0($,Z,J,X,z){let G=z&&J5($,Z,J,z);if(G)return G;let B=Z.refusals[X][$.host];return{action:"refuse",reason:X,family:z?.family??B.family,messageKey:z?.messageKey??B.messageKey,retryable:z?.retryable??B.retryable,hostRetry:z?.hostRetry??B.hostRetry,history:J,...z?.retryAfterMs===void 0?{}:{retryAfterMs:z.retryAfterMs},...z?.resetAt===void 0?{}:{resetAt:z.resetAt}}}function KX($,Z,J,X,z){let G=$.hold;if(Z.shortLimit.holdBound==="disabled"||$.host==="opencode2"&&($.hostPhase!=="retry"||$.remainingRetries===void 0||!($.remainingRetries>=1))||!X?.admitted||!G||G.maxWaitMs<=0||Number.isNaN(G.maxWaitMs)||!Number.isFinite(G.cacheExpiresAt)||G.maxDelayMs!==void 0&&(!Number.isFinite(G.maxDelayMs)||G.maxDelayMs<0)||!z.length||z.some((Y)=>!K6(Y.resetAt,$.now)))return;let B=Math.max(...z.map((Y)=>Y.resetAt)),W=Z.shortLimit.jitter==="session-sha256"?o1($.sessionId,B-$.now):B-$.now,Q=$.now+W;if(!Number.isFinite(Q)||Q>Math.min(G.cacheExpiresAt,$.now+G.maxWaitMs)||$.host==="opencode2"&&W>W4||G.maxDelayMs!==void 0&&W>G.maxDelayMs)return;return{action:"hold",account:X.account,delayMs:W,retryAfterMs:W,target:Q,checkpoint:t1(X.account,$.now,z),reason:"confirmed-limit",retryable:!0,hostRetry:$.phase==="pre-send"?"leave":b2($,Z),history:J}}function NX($,Z,J,X){let z=Z.poolWaiting;if(z.kind==="off"||!X.length)return;J=I2(J,{type:"blocked",clockNow:$.clockNow});let B=X.map((F)=>{let U=F.blockers.filter((j)=>!(j.kind==="soft"&&X.length===1&&z.singleEligibleSoftExemption));if(U.some((j)=>!K6(j.until,$.now)))return;return U.length?{candidate:F,time:Math.max(...U.map((j)=>j.until))}:void 0}).filter((F)=>F!==void 0).reduce((F,U)=>!F||U.time<F.time?U:F,void 0),W=B?B.time-$.now:X.some((F)=>F.blockers.some((U)=>U.kind!=="soft"))?z.hardFallbackMs:void 0,Q=$.poolWaitBudgetMs??z.budgetMs,Y=$.clockNow-(J.blockedSince??$.clockNow);if(Q>0&&(Y>=Q||W!==void 0&&W>Q))return k0($,Z,J,"quota",$.terminal);let V=z.requestDeadlineMs-($.clockNow-J.requestStartedAt);if(V<=0)return k0($,Z,J,"incomplete");if(W===void 0)return k0($,Z,J,"quota",$.terminal);let H=Math.min(W,V,Q>0?Q-Y:Number.POSITIVE_INFINITY),q=B?.candidate??X[0];if(!q)return;return{action:"wait-then-reselect",delayMs:H,target:$.now+H,checkpoint:t1(q.account,$.now,q.confirmedBlockers??[]),reason:"pool-blocked",retryable:!0,hostRetry:b2($,Z),history:J}}function e1($,Z){let J=$.history,X=(C,T=$.phase==="pre-send"?!0:$.failureRetryable??!0,A="leave")=>({action:"pass",reason:C,retryable:T,hostRetry:A,history:J});if($.phase==="after-limit"&&$.host==="opencode2"&&(!$.delivery.owned||!$.delivery.attributable))return X("not-owned");let z=$.status??$.signal?.status;if($.phase==="after-limit"&&$.attempted)J=I2(J,{type:"response",account:$.attempted,scope:$.requestScope,status:z,kind:Z.terminalStatusHistory?.paymentBalance&&$.signalApplicable!==!1&&$.signal&&E($.signal.account,$.attempted)?$.signal.kind:void 0});if($.phase==="after-limit"&&!$.delivery.replayable)return X("unsafe-output",!1,"veto");let G=$.candidates.filter((C)=>C.admitted),B=G.filter((C)=>!U6(J,C.account,$.requestScope)),W=B.find((C)=>$.attempted&&E(C.account,$.attempted)),Q=$.signalApplicable!==!1&&$.signal&&$.attempted&&E($.signal.account,$.attempted)?$.signal:void 0;if(Z.requestExclusion==="on"&&Q?.kind==="model-unavailable"&&W)return{action:"exclude-for-request",account:W.account,scope:$.requestScope,effects:r1,reason:"model-unavailable",retryable:!0,hostRetry:b2($,Z),history:J};if(G.length&&!B.length)return k0($,Z,J,"model-unavailable");if($.host==="opencode2"&&$.hostPhase==="retry"&&Z.execution==="host"&&$.remainingRetries!==void 0&&$.remainingRetries<1)return $.terminal&&($.terminal.retryable===!1||Z5($.terminal,Z))?k0($,Z,J,$.terminal.reason,$.terminal):X("host-retries-exhausted");if($.wake&&$.phase==="pre-send"){let C=$.wake,T=B.find((c)=>E(c.account,C.checkpoint.accountKey)),A=T?.confirmedBlockers??(T&&Q&&E(Q.account,T.account)?Q.windows:[]),x=T?X5(C,T.account,A,$.now):[],I=$.hold,f=C.kind==="terminal"||I!==void 0&&Number.isFinite(I.cacheExpiresAt)&&$.now<=I.cacheExpiresAt&&C.target<=I.cacheExpiresAt&&I.maxWaitMs>0&&C.target-C.checkpoint.decidedAt<=I.maxWaitMs;if(T&&Number.isFinite(C.target)&&C.target>=C.checkpoint.decidedAt&&$.now>=C.target&&f&&T.blockers.every((c)=>c.until!==void 0&&Number.isFinite(c.until)&&c.until<=$.now)&&(T.ready||A.some((c)=>c.confirmed))&&A.filter((c)=>c.confirmed).every((c)=>x.includes(c.window)))return{action:"retain",account:T.account,liftedWindows:x,reason:"wait-elapsed",retryable:!0,hostRetry:"leave",history:I2(J,{type:"selected"})}}if($.credentialRecovery&&W)return{action:"retain",account:W.account,reason:"credential-recovery",...$.credentialRecovery.retryMs===void 0?{}:{retryMs:$.credentialRecovery.retryMs},retryable:!0,hostRetry:b2($,Z),history:J};let Y=Z.unconfirmedRetainLimit,V=$.unconfirmedRetainCount,H=z===429&&Y!==void 0&&V!==void 0,q=Z.advance[$.host];if($.phase==="after-limit"&&Z.terminalStatusHistory?.paymentBalance&&(Q?.kind==="payment-cap"||z===402&&Q?.kind!=="payment-balance"))return X("unhandled-failure");if($.phase==="after-limit"&&!Q&&!H&&!$.terminal&&(q.attributedLimitOnly||z===void 0||!q.statuses.includes(z)))return X("unhandled-failure");let F=B.find((C)=>$.selection&&E(C.account,$.selection.account)&&C.placementEligible),U=F&&(F.ready||Z.poolWaiting.kind==="earliest"&&Z.poolWaiting.singleEligibleSoftExemption&&B.length===1&&F.blockers.length>0&&F.blockers.every((C)=>C.kind==="soft")),j=U&&(!$.attempted||!E(F.account,$.attempted))?F:void 0,K=(C,T="ready-alternative")=>({action:"reroute",account:C.account,pin:$.selection?.pin??"preserve",reason:T,retryable:!0,hostRetry:b2($,Z),history:I2(J,{type:"selected"})}),N=$.phase==="pre-send"?W??B.find((C)=>$.selection&&E(C.account,$.selection.account)):W,D=(N?.confirmedBlockers??($.phase==="after-limit"?Q?.windows:void 0)??[]).filter((C)=>C.confirmed);if(D.length){if(Z.shortLimit.preference==="ready-alternative-first"&&j)return K(j);let C=KX($,Z,J,N,D);if(C)return C}let O=Z.unknown[$.host],M=$.phase==="after-limit"&&!D.length&&(z===429||Q?.kind==="rate-limit"||Q?.kind==="quota-exhausted"||Q?.kind==="capacity"),P=H&&V>=Y;if(M&&W&&(O.affinity==="always"||$.affinity==="sticky")){if(H&&P){if(j)return K(j,"unconfirmed-retry-limit")}else if(H||O.action==="retain"){let C=[...$.retryHintsMs??[],Q?.retryAfterMs].filter((T)=>T!==void 0&&Number.isFinite(T)&&(H||T>=0));return{action:"retain",account:W.account,reason:"unconfirmed-limit",...H?{retryMs:Math.min(60000,...C.map((T)=>Math.max(0,T))),incrementUnconfirmedRetain:!0}:O.hint==="minimum"?{retryMs:Math.min(O.defaultMs,...C)}:{},retryable:!0,hostRetry:b2($,Z),history:J}}else if(O.action==="pass")return X("unconfirmed-limit")}if(j)return K(j);if($.phase==="pre-send"&&U)return K(F);if($.host==="opencode2"&&$.hostPhase==="request"&&Z.markedPool.requestEscape==="ignore-timed-marks-if-all-marked"&&F&&B.every((C)=>!C.ready)&&B.every((C)=>C.blockers.length>0&&C.blockers.every((T)=>T.kind==="hard")))return K(F);let L=NX($,Z,J,B);if(L)return L;if($.phase==="pre-send"&&!B.length)return k0($,Z,J,$.terminal?.reason??"auth",$.terminal);if($.host==="opencode2"&&$.hostPhase==="retry"&&!$.terminal){if(Z.markedPool.retryExhaustion==="host-delay")return X("host-delay");if(Z.markedPool.retryExhaustion==="same-host-delay"&&W)return{action:"retain",account:W.account,reason:"host-delay",retryable:!0,hostRetry:"leave",history:J}}if(Z.terminalPolicy==="status-history"&&Z.terminalStatusHistory&&$.host!=="opencode2"&&!$.terminal){let C=$.phase==="pre-send"&&B.length>0&&B.every((x)=>!x.ready),T=B.filter((x)=>x.placementEligible),A=$.phase==="pre-send"&&Z.terminalStatusHistory.paymentBalance&&T.length>0&&T.every((x)=>!x.ready&&x.blockers.length>0&&x.blockers.every((I)=>I.cause==="payment-balance"&&K6(I.until,$.now)));if(A||C||z===401&&J.saw429||Z.terminalStatusHistory.paymentBalance&&J.saw429&&J.sawPaymentBalance){let x=(A?T:B).flatMap((I)=>I.blockers.map((f)=>f.until)).filter((I)=>K6(I,$.now));return k0($,Z,J,"quota",{source:"pool",reason:"quota",...A?Z.terminalStatusHistory.paymentBalance:{},retryAfterMs:x.length?Math.max(Z.terminalStatusHistory.minRetryMs,Math.min(...x)-$.now):Z.terminalStatusHistory.defaultRetryMs})}return X("original-response")}if($.terminal)return k0($,Z,J,$.terminal.reason,$.terminal);if(Q?.kind==="auth"||Q?.kind==="account-access")return k0($,Z,J,"auth");if(Q||z===429||B.some((C)=>C.blockers.length))return k0($,Z,J,"quota");return X("no-override")}function k2($){if(!Number.isFinite($))return"unknown";let Z=Math.ceil(Math.max(0,$)/1000);if(Z<60)return`${Z}s`;let J=Math.ceil(Z/60),X=Math.floor(J/1440);if(X>=100)return"over 99 days";let z=Math.floor(J/60)%24,G=J%60;if(X>0)return`${X}d ${z}h ${G}m`;if(z>0)return`${z}h ${G}m`;return`${G}m`}var x2=({resetAt:$,now:Z})=>k2($-Z);var Z9=Symbol.for("@cortexkit/common-auth/limits-envelope-error");class H4 extends Error{[Z9]="conflict";constructor(){super("Conflicting limits envelope writers");this.name="LimitsEnvelopeConflictError"}}class U4 extends Error{[Z9]="unsupported";constructor(){super("Invalid or unsupported limits namespace schema");this.name="LimitsEnvelopeUnsupportedError"}}function J9($){let Z=$&&typeof $==="object"&&Reflect.get($,Z9);return Z==="conflict"||Z==="unsupported"?Z:void 0}function m0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}var Q2=($)=>Number.isSafeInteger($)&&$>=0,$9=($)=>typeof $==="number"&&Number.isFinite($),z5=($)=>$===void 0||$==="rate-limit"||$==="payment-balance",V4=($,Z)=>Array.isArray($)&&$.every(Z);function B5($,Z){return m0($)&&$.namespace===Z&&typeof $.accountId==="string"&&typeof $.incarnation==="string"}function G5($,Z){if(!m0($)||!m0($.scope))return!1;let J=$.scope;return B5($.account,Z)&&typeof $.window==="string"&&(J.kind==="pool"||J.kind==="family"&&typeof J.family==="string"||J.kind==="model"&&typeof J.model==="string")}function DX($,Z){return $.namespace===Z&&typeof $.generation==="string"&&Q2($.revision)&&Q2($.lowWatermark)&&V4($.marks,(J)=>m0(J)&&G5(J.key,Z)&&["latest-evidence","max-until","overwrite"].includes(J.mergeLaw)&&V4(J.entries,(X)=>m0(X)&&z5(X.cause)&&$9(X.until)&&$9(X.evidenceAt)&&Q2(X.baseRevision)&&Q2(X.committedRevision)))&&V4($.tombstones,(J)=>m0(J)&&G5(J.key,Z)&&Q2(J.revision)&&z5(J.cause))&&V4($.operationIds,(J)=>m0(J)&&typeof J.producerId==="string"&&typeof J.operationId==="string"&&Q2(J.revision))&&V4($.access,(J)=>m0(J)&&B5(J.account,Z)&&$9(J.eligibilityStateUpdatedAt)&&Q2(J.committedRevision))}class q4{namespace;logger;replaced=!1;terminal;constructor($,Z){this.namespace=$,this.logger=Z}assertWritable(){if(this.terminal)throw this.terminal}decode($){if(this.assertWritable(),$===void 0)return{};let Z;if(!m0($))Z="malformed";else if($.schemaVersion!==1)throw this.terminal=new U4,this.terminal;else if(typeof $.namespace==="string"&&$.namespace!==this.namespace)Z="foreign-namespace";else if(!DX($,this.namespace))Z="malformed";if(!Z)return{snapshot:$};if(this.replaced)throw this.terminal=new H4,this.terminal;return{replacement:Z}}didCommit($){if(!$||this.replaced)return!1;this.replaced=!0;try{this.logger?.warn(`limits envelope replaced: ${$}`)}catch{}return!0}}var PX=[/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],MX=new RegExp(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","stream disconnected before completion","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"].join("|"),"i");function y2($){return PX.some((Z)=>Z.test($))||MX.test($)}class N6 extends Error{messageKey;code="unsafe-wording";constructor($){super(`Unsafe refusal template: ${$}`);this.messageKey=$,this.name="UnsafeWordingError"}}function X9($){let Z=new Map(Object.entries($.refusals??{})),J=new Map(Object.entries($.retryable??{}));for(let[X,z]of Z)for(let G of[void 0,"45s","2m","1h 30m","99d 23h 59m","over 99 days"])for(let B of[[],["this account"]]){let W=Object.freeze({labels:Object.freeze(B),reset:G}),Q;try{Q=z(W)}catch{throw new N6(X)}if(typeof Q!=="string"||y2(Q))throw new N6(X)}return Object.freeze({formatReset:$.formatReset,render:(X,z,G)=>(G?Z:J).get(X)?.(z)})}var CX=/[^\s@]+@[^\s@]+\.[^\s@]+/;function z9($){return CX.test($)}function G9($){return z9($)||y2($)?"this account":$}class B9 extends Error{code="ECONNRESET";syscall="sticky-routing";isRetryable=!0;constructor($){super($,{cause:{code:"ECONNRESET",syscall:"sticky-routing"}});this.name="ClaudeIncompleteError"}}function D6($,Z=0){if($===void 0||!Number.isFinite($)||$<0)return;let J=$-Q9(Z);return J>=0?Math.ceil(J/1000):void 0}function Q9($){return Number.isFinite($)&&$>=0?$:0}function W5($){return $.resetAt!==void 0&&Number.isFinite($.resetAt)?$.resetAt:void 0}function TX($){return $===void 0?"The reset is unknown.":`Reset at ${$}.`}function Y5($,Z,J,X){let z=!X&&J!==void 0?` Retry in ${k2(J*1000)}.`:"";return`${$==="pi-final"?"The request cannot continue.":"No account is available."}${z} ${TX(Z)}`}function V5($,Z,J){let X=W5($),z=X===void 0?void 0:x2({resetAt:X,now:Z}),G=D6($.retryAfterMs,$.noticeDelayMs);return Y5($.family,z,G,J)}function LX($,Z){let J=$.now+Q9($.noticeDelayMs??0),X=()=>V5($,J,Z);try{let z=W5($),G=z===void 0?void 0:($.messages?.formatReset??x2)({resetAt:z,now:J}),B=D6($.retryAfterMs,$.noticeDelayMs),W=Object.freeze({labels:Object.freeze($.labelPolicy==="relogin"?($.parameters?.labels??[]).map(G9):[]),reset:G,retryIn:!Z&&B!==void 0?k2(B*1000):void 0}),Q=$.messages?.render($.messageKey,W,Z);return typeof Q==="string"?Q:Y5($.family,G,B,Z)}catch{return X()}}function Q5($,Z){switch($){case"openai-429":return JSON.stringify({error:{message:Z,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}});case"claude-429":return JSON.stringify({type:"error",error:{type:"rate_limit_error",message:Z}});case"json-412":return JSON.stringify({error:{code:412,status:"FAILED_PRECONDITION",message:Z}});case"claustrum-429":return JSON.stringify({error:"claustrum-auth: accounts-rate-limited"});case"claustrum-402":return JSON.stringify({error:"claustrum-auth: insufficient balance"});default:return Z}}function W9($){let Z=$.family==="json-412"||$.family==="pi-final",J={family:$.family,disposition:"refuse",retryable:!Z,hostRetry:Z||$.host==="opencode2"?"veto":"leave"},X=Q5($.family,LX($,Z));if(Z&&(y2(X)||z9(X))){let B=$.now+Q9($.noticeDelayMs??0);X=Q5($.family,V5($,B,!0))}if($.family==="claude-econnreset")return{...J,kind:"throw",error:new B9(X)};if($.family==="pi-final")return{...J,kind:"text",body:X};let z=new Headers($.family==="json-412"?$.extraHeaders:void 0);z.set("content-type","application/json"),z.delete("retry-after");let G=D6($.retryAfterMs,$.noticeDelayMs);if(G!==void 0)z.set("retry-after",String(G));return{...J,kind:"http",status:$.family==="json-412"?412:$.family==="claustrum-402"?402:429,headers:z,body:X}}function w0($,Z){return E($.account,Z.account)&&($.identity===void 0||Z.identity===void 0||$.identity===Z.identity)}function Y9($,Z){if(!w0($,Z))return Z;return{...Z,identity:Z.identity??$.identity}}function V9($,Z,J){if(!w0($,Z))return"identity-replaced";if(!J($,Z))return"credential-epoch";return}var H9=Object.freeze({kind:"failure-ladder",mergeLaw:"max-until",hintFloorMs:2000,quotaSteps:Object.freeze([60000,300000,1800000,7200000]),byKind:Object.freeze({"rate-limit":30000}),byReason:Object.freeze({"server-error":20000,unknown:60000}),capacity:Object.freeze({baseMs:45000,spreadMs:15000}),defaultMs:60000});function P6($,Z,J,X=0){let z=Z.filter((G)=>G.baseRevision>=X);if($!=="max-until"){let G=z.reduce((B,W)=>{if(!B)return W;if($==="latest-evidence"&&W.evidenceAt!==B.evidenceAt)return W.evidenceAt>B.evidenceAt?W:B;return W.committedRevision>B.committedRevision?W:B},void 0);return G&&J<G.until?[G]:[]}return z.filter((G,B)=>J<G.until&&!z.some((W,Q)=>Q!==B&&W.until>=G.until&&W.baseRevision>=G.baseRevision&&(W.until>G.until||W.baseRevision>G.baseRevision||W.committedRevision>G.committedRevision||W.committedRevision===G.committedRevision&&Q<B))).sort((G,B)=>G.committedRevision-B.committedRevision)}function j4($,Z){if($.eligibilityStateUpdatedAt!==Z.eligibilityStateUpdatedAt)return $.eligibilityStateUpdatedAt>Z.eligibilityStateUpdatedAt?$:Z;return $.committedRevision>Z.committedRevision?$:Z}var U5=1024;function U9($){return $==="rate-limit"||$==="payment-balance"?$:void 0}function M6($,Z){return U9($.cause)===void 0||$.cause===Z}function q5($){return JSON.stringify([p($.key),U9($.cause)])}function T0($,Z){return{schemaVersion:1,namespace:$,generation:Z,revision:0,lowWatermark:0,marks:[],tombstones:[],operationIds:[],access:[]}}function OX($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function p($){let Z=$.scope;return JSON.stringify([OX($.account),Z.kind,Z.kind==="model"?Z.model:Z.kind==="family"?Z.family:null,$.window])}function H5($){return JSON.stringify([$.producerId,$.operationId])}function W2($,Z){let J=new Map;for(let Q of $.tombstones){let Y=p(Q.key),V=J.get(Y);if(V)V.push(Q);else J.set(Y,[Q])}let X=$.marks.flatMap((Q)=>{let Y=J.get(p(Q.key)),V=P6(Q.mergeLaw,Y?Q.entries.filter((H)=>!Y.some((q)=>M6(q,H.cause)&&H.baseRevision<q.revision)):Q.entries,Z);return V.length?[{...Q,entries:V}]:[]}),z=$.lowWatermark,G=(Q)=>{let Y=[...Q].sort((H,q)=>H.revision-q.revision),V=Math.max(0,Y.length-U5);for(let H of Y.slice(0,V))z=Math.max(z,H.revision+1);return Y.slice(V)},B=G($.tombstones),W=G($.operationIds);return{...$,revision:Math.max($.revision,z),marks:X,tombstones:B,operationIds:W,lowWatermark:z}}function Y2($,Z,J){let X=W2($,J.now),z=[];for(let G of Z){let B=(K)=>{z.push({producerId:G.producerId,operationId:G.operationId,status:"rejected",reason:K})};if(G.binding.account.namespace!==X.namespace){B("wrong-namespace");continue}if(G.baseRevision<X.lowWatermark){B("below-watermark");continue}if(G.baseRevision>X.revision){B("future-revision");continue}let W=J.bindings.find((K)=>E(K.account,G.binding.account));if(!W){B("unknown-account");continue}let Q=V9(G.binding,W,J.authorizeEpoch);if(Q){B(Q);continue}let Y=X.operationIds.find((K)=>H5(K)===H5(G));if(Y){z.push({...Y,status:"duplicate"});continue}let V=W.account,H=X.revision+1,q=[...X.marks],F=[...X.tombstones],U=[...X.access];if(G.type==="mark"){let K={account:V,scope:G.scope,window:G.window},N=p(K),D=q.find((M)=>p(M.key)===N);if(F.some((M)=>G.baseRevision<M.revision&&M6(M,G.cause)&&p(M.key)===N)){B("cleared");continue}if(D&&D.mergeLaw!==G.mergeLaw){B("merge-law-conflict");continue}let O=P6(G.mergeLaw,[...D?.entries??[],{until:G.until,evidenceAt:G.evidenceAt,baseRevision:G.baseRevision,committedRevision:H,...G.cause==="rate-limit"||G.cause==="payment-balance"?{cause:G.cause}:{}}],J.now);if(q=q.filter((M)=>p(M.key)!==N),O.length)q.push({key:K,mergeLaw:G.mergeLaw,entries:O})}else if(G.type==="clear"){let K=U9(G.cause),N=G.keys.map((M)=>({...M,account:V})).filter((M)=>G.cause===void 0||!q.some((P)=>p(P.key)===p(M)&&P.entries.some((L)=>L.cause!==G.cause))),D=new Set(N.map(p)),O=G.evidenceAt;if(O!==void 0&&q.some((M)=>D.has(p(M.key))&&M.entries.some((P)=>P.evidenceAt>O))){B("newer-evidence");continue}q=q.filter((M)=>!D.has(p(M.key))),F=F.filter((M)=>!D.has(p(M.key))||K!==void 0&&M.cause!==K);for(let M of new Map(N.map((P)=>[p(P),P])).values())F.push({key:M,revision:H,...K===void 0?{}:{cause:K}})}else{let K={account:V,state:G.state,eligibilityStateUpdatedAt:G.eligibilityStateUpdatedAt,committedRevision:H},N=U.find((D)=>E(D.account,V));U=U.filter((D)=>!E(D.account,V)),U.push(N?j4(N,K):K)}let j={producerId:G.producerId,operationId:G.operationId,revision:H};X=W2({...X,revision:H,marks:q,tombstones:F,access:U,operationIds:[...X.operationIds,j]},J.now),z.push({...j,status:"committed"})}return{snapshot:X,outcomes:z}}import{realpathSync as SX}from"node:fs";import{basename as j5,dirname as F5,join as AX,resolve as EX}from"node:path";function F4($){let Z=EX($),J=[j5(Z)],X=F5(Z);for(;;)try{return AX(SX.native(X),...J.reverse())}catch(z){let G=z.code;if(G!=="ENOENT"&&G!=="ENOTDIR")throw z;let B=F5(X);if(B===X)return Z;J.push(j5(X)),X=B}}class L0 extends Error{code;constructor($){super($);this.code=$,this.name="LimitsPersistenceRefusal"}}import{randomUUID as kX}from"node:crypto";import{isDeepStrictEqual as N5}from"node:util";import{AsyncResource as RX}from"node:async_hooks";import{randomUUID as K5}from"node:crypto";import{isDeepStrictEqual as IX}from"node:util";var bX=new RX("common-auth-limits-recovery");class K4{logger;running;listeners=new Set;constructor($){this.logger=$}subscribe=($)=>{return this.listeners.add($),()=>this.listeners.delete($)};schedule($){if(this.running)return;this.running=bX.runInAsyncScope(async()=>{await Promise.resolve();let Z=!1;try{await $(),Z=!0}catch(J){try{this.logger?.warn("limits envelope recovery failed; agreement remains degraded",{error:J instanceof Error?J.message:String(J)})}catch{}}finally{if(this.running=void 0,Z)for(let J of this.listeners)try{J()}catch{}}})}}class V2{seen;missingGeneration;incorporated;remember($,Z){if(this.seen&&this.seen.revision>$.revision)return;if(this.seen=structuredClone($),this.missingGeneration=void 0,Z)this.incorporated=structuredClone(Z)}retained($){let Z=IX($,this.incorporated)?void 0:$;return[this.seen,Z].filter((J)=>J!==void 0&&(J===this.seen||J.revision>0))}lost($,Z){return this.retained(Z).some((J)=>!$||J.generation!==$.generation||$.revision<J.revision||J.tombstones.some((X)=>X.revision>$.lowWatermark&&!$.tombstones.some((z)=>p(z.key)===p(X.key)&&M6(z,X.cause)&&z.revision>=X.revision)))}recover($,Z,J,X){if(!$)this.missingGeneration??=K5();let z=$??T0(J,this.missingGeneration??K5()),G=[...this.retained(Z),z],B=new Map,W=new Map,Q=new Map,Y=new Map,V=0;for(let q of G){V=Math.max(V,q.revision,q.lowWatermark);for(let F of q.marks){let U=p(F.key),j=B.get(U);if(j&&j.mergeLaw!==F.mergeLaw)throw Error("limits-recovery-merge-law-conflict");B.set(U,{...F,entries:[...j?.entries??[],...F.entries]});for(let K of F.entries)V=Math.max(V,K.baseRevision,K.committedRevision)}for(let F of q.tombstones){let U=q5(F),j=W.get(U);if(!j||j.revision<F.revision)W.set(U,F);V=Math.max(V,F.revision)}for(let F of q.operationIds){let U=JSON.stringify([F.producerId,F.operationId]),j=Q.get(U);if(!j||j.revision<F.revision)Q.set(U,F);V=Math.max(V,F.revision)}for(let F of q.access){let{namespace:U,accountId:j,incarnation:K}=F.account,N=JSON.stringify([U,j,K]),D=Y.get(N);Y.set(N,D?j4(D,F):F),V=Math.max(V,F.committedRevision)}}let H=V+1;if(!Number.isSafeInteger(H))throw Error("limits-revision-exhausted");return W2({...z,revision:H,lowWatermark:H,marks:[...B.values()],tombstones:[...W.values()],operationIds:[...Q.values()],access:[...Y.values()]},X)}}function D5($,Z){return Z.flatMap((J)=>J.credentialEpoch===void 0?[]:[{account:{namespace:$,accountId:J.id,incarnation:String(J.credentialEpoch)},credentialEpoch:String(J.credentialEpoch),...J.identity===void 0?{}:{identity:J.identity}}])}async function q9($){let{store:Z,namespace:J}=$;if(!Z.updateLimitsNamespace)throw new L0("limits-unsupported");let X=Z.updateLimitsNamespace.bind(Z),z=kX(),G=new V2,B=new q4(J,$.logger),W=new K4($.logger),Q=$.now??Date.now,Y=async()=>{let F=await Z.read();if(F.status!=="ready"){if(F.status==="error"&&F.kind==="snapshot-contended")throw Error(F.reason);throw new L0("pool-not-ready")}return D5(J,F.rows)},V=async()=>{let F=await Z.readSettings();if(F.status!=="ready")throw new L0("pool-not-ready");return B.decode(F.settings.commonAuthLimits)},H=async(F)=>{B.assertWritable();let U=await Y(),j=await V(),K;for(let N=0;N<3;N++){let D=await Y(),O=await V(),M=N5(U,D)&&N5(j,O);if(K={snapshot:j.snapshot??T0(J,z),bindings:U,authoritative:M},M){if(!j.replacement&&G.lost(j.snapshot,F))return W.schedule(()=>q.commit([],F)),{snapshot:G.recover(j.snapshot,F,J,Q()),bindings:U,authoritative:!1,degradedAgreement:!0};if(j.snapshot)G.remember(j.snapshot);return K}U=D,j=O}return K},q={namespace:J,read:H,subscribe:W.subscribe,async commit(F,U){B.assertWritable();let j,K,N=()=>{if(B.didCommit(K)&&j)G=new V2,G.remember(j.snapshot,U)};try{await X((D,O)=>{let M=D5(J,O),P=B.decode(D),L=P.snapshot;K=P.replacement;let C=!K&&G.lost(L,U),T=Y2(C?G.recover(L,U,J,Q()):L??T0(J,z),F,{now:Q(),bindings:M,authorizeEpoch:(A,x)=>A.credentialEpoch===x.credentialEpoch});return j={...T,bindings:M,authoritative:!0,degradedAgreement:C},T.snapshot},{beforePublish:()=>B.assertWritable(),onPublished:N})}catch(D){if(B.assertWritable(),D instanceof b&&(D.kind==="pending-migration"||D.kind==="load-error"))throw new L0("pool-not-ready");throw D}if(!j)throw Error("Pool limits mutator was not called");return N(),G.remember(j.snapshot,U),j}};return await H(),q}function g2($){if($&&typeof $==="object"){for(let Z of Object.values($))g2(Z);Object.freeze($)}return $}function _0($){return{opencode1:$,opencode2:$,pi:$}}var H2={action:"reselect",affinity:"always",hint:"none",defaultMs:60000},P5={...H2,action:"retain",affinity:"sticky"},C5={family:"local-auth",messageKey:"auth.no-account",retryable:!1,hostRetry:"leave"};function T6($,Z){return{auth:_0(C5),quota:_0($),incomplete:_0(Z),"model-unavailable":_0({family:"json-412",messageKey:"model-unavailable",retryable:!1,hostRetry:"veto"})}}var C6={kind:"off"},T5={requestEscape:"off",retryExhaustion:"terminal"},L5={statuses:[],attributedLimitOnly:!0},M5={family:"json-412",messageKey:"quota.pool-exhausted",retryable:!1,hostRetry:"veto"},_5=g2({unconfirmedRetainLimit:2,evidence:"per-field-overlay",markers:_0({kind:"reset",mergeLaw:"latest-evidence",defaultMs:60000}),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"on",unknown:{opencode1:{...H2,action:"retain",hint:"minimum"},opencode2:H2,pi:{...H2,action:"pass"}},shortLimit:{holdBound:"cache-ttl",preference:"same-account-first",jitter:"session-sha256"},retainBound:"none",poolWaiting:C6,execution:"host",requestExclusion:"off",advance:_0(L5),markedPool:T5,terminalMetadata:"setting-capped-fresh",terminalPolicy:"provided",refusals:T6({family:"claude-429",messageKey:"quota.all-accounts",retryable:!0,hostRetry:"leave"},{family:"claude-econnreset",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),O5=g2({evidence:"typed",markers:_0(H9),readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:_0(H2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:{kind:"earliest",budgetMs:300000,requestDeadlineMs:600000,hardFallbackMs:60000,singleEligibleSoftExemption:!0},execution:"engine",requestExclusion:"on",advance:_0({statuses:[429,503,529],attributedLimitOnly:!1}),markedPool:T5,terminalMetadata:"baseline",terminalPolicy:"pool",refusals:T6(M5,{...M5,messageKey:"incomplete.timeout"})}),o0=g2({evidence:"named-window",markers:{opencode1:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},opencode2:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},pi:C6},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:{opencode1:P5,opencode2:H2,pi:P5},shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:C6,execution:"host",requestExclusion:"off",advance:_0({statuses:[401,403,429],attributedLimitOnly:!1}),markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"same-host-delay"},terminalMetadata:"baseline",terminalPolicy:"provided",refusals:T6({family:"openai-429",messageKey:"quota.no-route",retryable:!0,hostRetry:"leave"},{family:"openai-429",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),S5=g2({evidence:"hints-only",markers:{opencode1:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"},opencode2:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"marker"},pi:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"}},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:_0(H2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:C6,execution:"host",requestExclusion:"off",advance:{opencode1:{statuses:[401,429],attributedLimitOnly:!1},opencode2:L5,pi:{statuses:[401,429],attributedLimitOnly:!1}},markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"host-delay"},terminalMetadata:"baseline",terminalPolicy:"status-history",terminalStatusHistory:{minRetryMs:1000,defaultRetryMs:60000,paymentBalance:{family:"claustrum-402",messageKey:"payment.insufficient-balance"}},refusals:T6({family:"claustrum-429",messageKey:"quota.accounts-rate-limited",retryable:!0,hostRetry:"leave"},{...C5,messageKey:"incomplete.no-account"})}),xX=g2({"confirmed-affinity":_5,"earliest-pool-engine":O5,"window-router":o0,"status-vault-order":S5});import{AsyncResource as yX}from"node:async_hooks";var _6=Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1"),gX="@cortexkit/common-auth/limits-registry/schema-v",L6=1000,A5=5000,U2=new yX("common-auth-limits"),fX={now:()=>Date.now(),setTimeout($,Z){let J=setTimeout($,Z);return J.unref?.(),J},clearTimeout:($)=>clearTimeout($)};function vX(){for(let J of Object.getOwnPropertySymbols(globalThis))if(Symbol.keyFor(J)?.startsWith(gX)&&J!==_6)throw Error("limits-schema-mismatch");let $=Reflect.get(globalThis,_6);if($){if($.schemaVersion!==1||!($.namespaces instanceof Map))throw Error("limits-schema-mismatch");return $}let Z={schemaVersion:1,namespaces:new Map};return Reflect.set(globalThis,_6,Z),Z}function q2($){return JSON.stringify([$.producerId,$.operationId])}class E5{adapter;clock;restrictive;listeners=new Set;owners=0;activity=q6();journal=new Map;failed=new Set;restrictions=new Map;snapshot;recoveryView;bindings=[];lastReloadAt=Number.NEGATIVE_INFINITY;lastActivity=Number.NEGATIVE_INFINITY;lastReadAttempt=Number.NEGATIVE_INFINITY;generation=0;degradedAgreement=!1;abandoned;lastFailure;dirty=!0;live=!1;publicationTimer;reloadTimer;unsubscribe;reading;writing;handoff=Promise.resolve();resolveAbandonment;abandonment=new Promise(($)=>{this.resolveAbandonment=$});constructor($){this.adapter=$.adapter,this.clock=$.clock??fX,this.restrictive=$.isAccessRestrictive}fail($){if(this.abandoned)return;let Z=J9($);if(Z){this.abandoned=Z,this.lastFailure=$,this.live=!1,this.generation++,this.cancelTimers(),this.unsubscribe?.(),this.unsubscribe=void 0,this.journal.clear(),this.failed.clear(),this.restrictions.clear(),this.recoveryView=void 0,this.resolveAbandonment();for(let J of this.listeners)try{J.onAbandon?.(Z)}catch{}return}this.degradedAgreement=!0,this.lastFailure=$}reconcile($){if(this.abandoned)return!1;if($.snapshot.schemaVersion!==1||$.snapshot.namespace!==this.adapter.namespace)throw Error("limits-schema-mismatch");if(!$.authoritative){if($.degradedAgreement&&this.snapshot&&$.snapshot.revision>this.snapshot.revision)this.recoveryView=$;return this.fail(Error("limits-unverifiable-snapshot")),!1}if(this.snapshot&&$.snapshot.generation===this.snapshot.generation&&$.snapshot.revision<this.snapshot.revision)return!1;this.snapshot=$.snapshot,this.recoveryView=void 0,this.bindings=$.bindings.map((Z)=>{let J=this.bindings.find((X)=>E(X.account,Z.account));return J?Y9(J,Z):Z});for(let[Z,J]of this.restrictions){let X=J.command,z=this.bindings.find((B)=>E(B.account,X.binding.account)),G=this.snapshot.access.find((B)=>E(B.account,X.binding.account));if(!z||!w0(z,X.binding)||X.type==="access"&&G&&G.committedRevision>J.revision&&G.eligibilityStateUpdatedAt>=X.eligibilityStateUpdatedAt)this.restrictions.delete(Z)}if($.degradedAgreement)this.fail(Error("limits-envelope-recovered"));return!$.degradedAgreement}touch(){this.lastActivity=this.clock.now(),this.armReload()}cancelTimers(){if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);if(this.reloadTimer!==void 0)this.clock.clearTimeout(this.reloadTimer);this.publicationTimer=this.reloadTimer=void 0}schedulePublish($){if(!this.live)return;if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);U2.runInAsyncScope(()=>{this.publicationTimer=this.clock.setTimeout(()=>{this.publicationTimer=void 0,U2.runInAsyncScope(()=>{this.flush()})},$)})}armReload(){if(!this.live||this.reading||this.reloadTimer!==void 0||this.clock.now()-this.lastActivity>=A5)return;U2.runInAsyncScope(()=>{this.reloadTimer=this.clock.setTimeout(()=>{if(this.reloadTimer=void 0,!this.live||this.clock.now()-this.lastActivity>=A5)return;U2.runInAsyncScope(()=>{this.reload()})},Math.max(0,this.lastReadAttempt+L6-this.clock.now()))})}async start($){if(this.abandoned)throw this.lastFailure;this.adapter=$,this.live=!0;let Z=++this.generation;if(await this.reload(),this.abandoned||!this.snapshot)throw this.lastFailure??Error("limits-hydration-failed");if(this.unsubscribe=$.subscribe?.(()=>{if(!this.live||this.generation!==Z)return;this.dirty=!0,U2.runInAsyncScope(()=>{this.reload()})}),this.journal.size)this.schedulePublish(0)}reload(){if(this.abandoned)return Promise.resolve();if(this.reading)return this.reading;let $=this.clock.now();return this.lastReadAttempt=$,this.reading=U2.runInAsyncScope(async()=>{try{if(this.dirty=!1,this.reconcile(await this.adapter.read(this.snapshot))){if(this.lastReloadAt=$,!this.journal.size&&!this.failed.size&&!this.restrictions.size)this.degradedAgreement=!1,this.lastFailure=void 0}}catch(Z){this.dirty=!0,this.fail(Z)}}).finally(()=>{this.reading=void 0,this.armReload()}),this.reading}provisional(){if(this.abandoned)return T0(this.adapter.namespace,this.snapshot?.generation??"");let $=this.recoveryView?.snapshot??this.snapshot,Z=[...this.journal.values()].map((X)=>X.command).filter((X)=>X.type==="mark"),J=Y2(W2($,this.clock.now()),Z,{now:this.clock.now(),bindings:this.bindings,authorizeEpoch:(X,z)=>X.credentialEpoch===z.credentialEpoch}).snapshot;return{...this.snapshot,marks:J.marks,tombstones:$.tombstones,access:$.access}}enqueue($,Z){if(this.abandoned)return;if($.binding.account.namespace!==this.adapter.namespace)throw Error("wrong-namespace");let J=q2($);if(this.journal.has(J)||this.snapshot.operationIds.some((z)=>q2(z)===J))return;this.journal.set(J,{command:structuredClone($),event:Z}),this.touch();let X=[...this.journal.values()].some((z)=>z.command.type!=="mark");this.schedulePublish(X?0:L6)}flush(){if(this.abandoned)return this.writing??Promise.resolve();if(this.writing)return this.writing;if(!this.journal.size)return Promise.resolve();return this.writing=U2.runInAsyncScope(async()=>{let $=[...this.journal.values()];while($.length&&!this.abandoned){try{let X=await this.adapter.commit($.map((z)=>z.command),this.snapshot);if(this.abandoned)return;if(this.reconcile(X),!X.authoritative)throw Error("limits-unverifiable-commit");for(let z of $){let G=X.outcomes.find((B)=>q2(B)===q2(z.command));if(!G)throw Error("limits-missing-acknowledgement");this.settle(z,G)}}catch(X){if(J9(X)){this.fail(X);return}if(this.abandoned)return;if(X instanceof L0&&X.code==="pool-not-ready")for(let z of $)this.settle(z,{...z.command,status:"rejected",reason:"pool-not-ready"});else{for(let z of $)if(this.journal.has(q2(z.command)))this.failed.add(q2(z.command));this.fail(X);break}}let Z=[...this.journal.values()],J=Z.findLastIndex((X)=>X.command.type!=="mark");$=Z.slice(0,J+1)}}).finally(()=>{if(this.writing=void 0,this.journal.size&&this.live)this.schedulePublish(L6);if(this.degradedAgreement&&this.live)this.armReload()}),this.writing}settle($,Z){let J=$.command,X=q2(J);if(this.journal.delete(X),this.failed.delete(X),Z.status==="rejected"){if(this.fail(Error(Z.reason??"limits-command-rejected")),J.type==="access"&&this.restrictive(J.state)){if(this.restrictions.set(X,{command:J,revision:this.snapshot.revision}),Z.reason==="below-watermark"&&J.baseRevision<this.snapshot.lowWatermark&&($.recoveryRetries??0)<3)this.journal.set(X,{...$,recoveryRetries:($.recoveryRetries??0)+1,command:{...J,baseRevision:this.snapshot.revision}})}for(let z of this.listeners)try{z.onRejected?.(J,Z)}catch{}}else if(Z.revision!==void 0&&(J.type==="mark"||$.event==="success"))for(let z of this.listeners)try{z.onEvent?.({type:J.type==="mark"?"mark":"success",command:J,revision:Z.revision})}catch{}}async beforeDispatch($){if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};this.touch();let Z=()=>[...this.journal.values()].some((z)=>z.command.type!=="mark"&&E(z.command.binding.account,$.account));if(Z())await Promise.race([this.flush(),this.abandonment]);if(this.dirty||this.clock.now()-this.lastReloadAt>=L6)await Promise.race([this.reload(),this.abandonment]);if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};let J=(this.recoveryView?.bindings??this.bindings).find((z)=>E(z.account,$.account)),X=this.provisional();return{snapshot:X,blocked:Z()||!J||!w0(J,$)||[...this.restrictions.values()].some((z)=>E(z.command.binding.account,$.account))||[...this.snapshot.access,...X.access].some((z)=>E(z.account,$.account)&&this.restrictive(z.state))}}async stop(){this.live=!1,this.generation++,this.cancelTimers(),await this.flush(),await this.reading,this.unsubscribe?.(),this.unsubscribe=void 0,this.cancelTimers()}}async function j9($){let Z=vX(),J=Z.namespaces.get($.adapter.namespace);if(!J)J=new E5($),Z.namespaces.set($.adapter.namespace,J);let X=J,z={onAbandon:$.onAbandon,onEvent:$.onEvent,onRejected:$.onRejected},G=X.owners++===0;if(X.listeners.add(z),G)X.handoff=X.handoff.catch(()=>{}).then(()=>X.start($.adapter));try{await X.handoff}catch(Q){throw X.listeners.delete(z),X.owners--,X.live=!1,X.cancelTimers(),Q}let B=!1,W=()=>{if(B)throw Error("limits-registry-disposed")};return{get abandoned(){return X.abandoned},get snapshot(){return W(),X.provisional()},get lastReloadAt(){return X.lastReloadAt},get degradedAgreement(){return X.degradedAgreement},get lastFailure(){return X.lastFailure},get pendingCommands(){return X.journal.size},activity:X.activity,observe(Q){return W(),{binding:structuredClone(Q),baseRevision:X.snapshot.revision}},enqueue(Q,Y){W(),X.enqueue(Q,Y)},beforeDispatch(Q){return W(),X.beforeDispatch(Q)},flush(){return W(),X.flush()},reload(){return W(),X.reload()},dispose(){if(B)return X.handoff;if(B=!0,X.owners--,!X.owners)X.handoff=X.handoff.then(()=>X.stop()).finally(()=>X.listeners.delete(z));else X.listeners.delete(z);return X.handoff}}}function t0($){let Z=Reflect.get(globalThis,Symbol.for("cortexkit.routing"));if(typeof Z!=="function")return;let J=Z($);return typeof J==="object"&&J!==null?J:void 0}function F9($){try{let J=t0($.sessionId);if(!J||typeof J.accountFor!=="function")return}catch{return}let Z=Y4($);if(!Z||!Number.isFinite($.now))return 0;return Math.floor(Math.max(0,Math.min(Z.maxWaitMs,Z.cacheExpiresAt-$.now))/1000)}function R($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as wX}from"node:fs";import{rm as b5}from"node:fs/promises";import{dirname as uX,join as p5}from"node:path";import{resolveClaustrumConnectionPath as pX}from"@cortexkit/claustrum-client";function R5($,Z){if(!$)return;let J=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function K9($){if(!R($)||typeof $.minor!=="number"||!Number.isSafeInteger($.minor)||typeof $.exponent!=="number"||!Number.isInteger($.exponent))return;let Z=$.minor/10**$.exponent;return Number.isFinite(Z)?Z:void 0}function hX($){let Z=K9($.total),J=K9($.remaining);if(Z===void 0||J===void 0||Z<0||J<0)return;let X=Z-J,z=$.spendable===!1,G=Z>0?X/Z*100:z?100:0;return{limit:Z,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...R($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function mX($,Z){if(!R($))return;let J=K9($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function N9($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&R(Z)&&R(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function I5($,Z){let J=R5($.usage?.primary,Z.fetchedAt);if(!J||!Number.isFinite(Z.fetchedAt))return;let X=R5($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((Y)=>R(Y)&&Y.id==="individual_limit"):void 0,G=R(z)?hX(z):void 0,B=Array.isArray($.spend)?$.spend.find((Y)=>R(Y)&&Y.id==="credits"):void 0,W=mX(B,Z.fetchedAt),Q=R($.savedResets)?$.savedResets.availableCount:void 0;return{primary:J,...W&&{credits:W},...W&&R(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof Q==="number"&&Number.isFinite(Q)&&Q>=0&&{resetCreditsAvailable:Q},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function O6($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var D9="ck auth reclassify --from-registry";function S6($,Z){if(Z===void 0)return"No ChatGPT login in the vault has the `openai-native` category, or the grant is missing. Check `ck auth status` for categories and `ck auth grant` for the grant.";if(Z.grants===0)return`The vault has no grant letting ${$} read OpenAI accounts. Grant it with \`${O6($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${D9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var Q0=o("vault"),l5="openai-auth";var lX={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},d5={opencode:"OpenCode",pi:"Pi"},dX=[{selector:{category:"openai-native"},operation:"read"}];function M9($){return y5(l5,$)}function cX($){return`ChatGPT for ${d5[$]}`}function k6($){return p5(uX($),"openai-auth-vault")}function j2($,Z){return{...f5({stateDir:$,host:Z}),rosterPath:p5($,`${Z}-roster.json`)}}var c5=2000,rU=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],sX={"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-grant-unreached":`Request refused locally: this host is connected to the credential vault, whose grant for it reaches no ChatGPT login, and local accounts are not used while it is connected. Logins without the openai-native category are not reached: run ${D9} to fill empty category sets, then check the CATEGORIES column with ck auth status. 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 oU($,Z){if($!=="vault-no-grant")return sX[$];return`Request refused locally: this host is connected to the credential vault, which has no grant letting it read OpenAI accounts, and local accounts are not used while it is connected. Disconnect this host from the vault, or grant it access with: ${O6(Z)}`}function tU($){let Z=$.snapshot();if(Z===void 0)return"vault-unreachable";if(Z.rows.length===0){let J=$.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function aX($){let Z=I6($);return Z?b6(Z):void 0}class iX{host;name;paths;#Z;#$;#Q=new Map;#W=new Map;#q=new Map;#j;#J;#Y;#z;#F=!1;#K=!1;#V=Promise.withResolvers();#H="unknown";#U;constructor($){this.#Z=$,this.host=$.host,this.name=M9($.host),this.paths=j2($.stateDir,$.host),this.#$=new w5({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:lX,pluginId:l5,connect:()=>this.#C(),isCustodyActive:()=>this.#L(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:aX,insula:{provider:"codex",normalize:I5},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onDiscovery:(Z)=>this.#_(Z),onError:(Z)=>this.#X("vault roster refresh failed",Z),logger:{...Q0,warn:(Z,J)=>{if(Z!=="skipped insula provider poll")Q0.warn(Z,J)}}})}#N(){return(this.#Z.connectionFile??pX)()}#D(){return{connectionFile:this.#N(),projectRoot:this.#Z.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>Q0.debug("vault transport error",{errorClass:$})}}#C(){return(this.#Z.connectScoped?.()??u5(this.#D())).then(($)=>{return this.#j=$.insula!==void 0,$})}#G($,Z,J){let X=this.#q.get($);if(X?.source===Z&&X.reason===J)return;this.#q.set($,{source:Z,reason:J}),Q0.info("vault background quota source changed",{routeId:$,source:Z,reason:J})}#T(){return this.#Z.connectEnrollment?.()??g5(this.#D())}#X($,Z){this.#J=x0(Z),Q0.warn($,{host:this.host,error:this.#J,...Z instanceof x5&&Z.reason?{reason:Z.reason}:{}})}#B(){if(f2())return"host";return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=wX($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#B(),Z=await v5(this.paths,this.name);if($===this.#B()){if(Z!==this.#H)Q0.info("vault authority",{host:this.host,authority:Z});return this.#H=Z,this.#U=$,Z}return"unreadable"}enrolled(){return f2()||this.#U!==this.#B()||this.#H!=="local"}async#L(){if(this.#U!==this.#B())await this.authority();return this.enrolled()}start(){if(this.#F||this.#K)return;this.#F=!0,this.#$.start()}#_($){if(this.#z===$)return;this.#z=$,$.finally(()=>{if(this.#z===$)this.#z=void 0;this.#V.resolve()}).catch(()=>{})}#P(){return this.#$.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(!["vault","host"].includes(await this.authority()))return;let $=this.#z;if($)await $.catch(()=>{return});if(this.snapshot()||!["vault","host"].includes(await this.authority()))return;await(this.#z??this.#P()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let $=this.#z;if($)await $.catch(()=>{return});let Z=await this.#P();return this.#J=void 0,Z}catch($){return this.#X("vault roster refresh failed",$),this.#$.snapshot()}}snapshot(){return this.#$.snapshot()}watchState(){return this.#$.watchState()}keptReceiptState(){return this.#$.keptReceiptState()}grantReach(){return this.#$.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap(($)=>$.accountIdentity!==void 0?[$.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let $=new Map((this.snapshot()?.rows??[]).map((Z)=>[Z.routeId,Z]));return this.#$.routingRows().map((Z)=>{let J=$.get(Z.id)?.accountIdentity;return{id:Z.id,credentialId:$.get(Z.id)?.credentialId,kind:Z.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...Z.quota!==void 0?{quota:Z.quota}:{}}})}owns($){return(this.snapshot()?.rows??[]).some((Z)=>Z.routeId===$)}async send($,Z,J){let X=!1;try{return await this.#$.send($,(z)=>{return X=!0,Z(z.accessToken,z)},{site:J.site,...J.signal?{signal:J.signal}:{}})}catch(z){if(X)throw z;this.#X("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#$.authorize($,Z.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure($,Z){if(Z!==401)return;try{await this.#$.reportFailure($,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot($,Z,J,X){let z=A6(Z,(this.#Z.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#$.recordQuota($,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}reportUsage($,Z,J){try{let X;if("headers"in Z){let z={};if(Z.headers.forEach((G,B)=>{if(B.startsWith("x-codex-"))z[B]=G}),Object.keys(z).length===0)return;X={headers:z}}else X={frame:Z.frame};this.#$.reportUsage({routeId:$,credentialId:J.credentialId,reading:{provider:"codex",observedAtMs:(this.#Z.now??Date.now)(),...X,...J.accountIdentity?{account:J.accountIdentity}:{}}})}catch{}}pollQuota($,Z=!0){let J=this.#W.get($);if(J)return J;let X=this.#O($,Z).finally(()=>{this.#W.delete($)});return this.#W.set($,X),X}async#O($,Z){if(Z){await this.authority(),await this.#$.refreshInsulaQuota();let J=(await R6(this.paths.rosterPath))?.rows.find((W)=>W.routeId===$),X,z=await this.#$.pollInsulaQuotaForRoute($,async()=>{this.#G($,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#M($,Z);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let W=A6(N9(z,this.routes().find((Y)=>Y.id===$)?.quota),z.primary.checkedAt,!0);if(!W)return this.#G($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#$.recordAccountQuota($,J.accountIdentity,W))return this.#G($,"insula",null),{ok:!0};return this.#G($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#$.lookupInsulaQuotaForRoute($),B=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G($,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#M($,Z)}async#M($,Z){let J,X=this.#Z.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,B)=>{try{let W=Z?void 0:await this.#$.cachedInsulaQuota(B);if(W!==void 0){let Y=A6(N9(W,this.routes().find((V)=>V.id===$)?.quota),W.primary.checkedAt,!0);if(!Y)throw Error("unusable insula reading");return await this.#$.recordQuota($,Y,B),new Response(null,{status:200})}let Q=await N4({accessToken:G,fetchImpl:X,now:this.#Z.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:$,logger:Q0});return await this.recordSnapshot($,Q,!0,B),J=void 0,new Response(null,{status:200})}catch(W){J=x0(W);let Q=W?.status;if(typeof Q==="number")return new Response(null,{status:Q});throw W}},{site:"quota"}).catch((G)=>{J=x0(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading($){let Z=this.#Q.get($);if(Z)return Z;let J=this.pollQuota($,!1).catch((X)=>{Q0.warn("vault quota poll failed",{routeId:$,error:x0(X)})}).finally(()=>{this.#Q.delete($)});return this.#Q.set($,J),J}async pollStale($){let Z=(this.#Z.now??Date.now)(),J=[];for(let X of this.routes()){let z=nX(X.quota);if(z!==void 0&&Z-z<$)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder($){let Z=await this.authority();if(Z!=="vault"&&Z!=="host")throw Error("Vault order can only be changed in vault mode.");return this.#$.reorder($)}async decline($){await this.#$.decline($),Q0.info("vault account declined",{routeId:$})}async accept($){await this.#$.accept($),Q0.info("vault account accepted",{routeId:$})}async status(){let $=await this.authority(),Z;try{Z=$==="host"?{state:"idle"}:await E6(this.paths,this.name)}catch(X){this.#X("vault enrollment state unreadable",X),Z={state:"blocked",proposedName:this.name,code:X instanceof k5?X.kind:"unreadable-state"}}let J=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:J!==void 0,accounts:J?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){if(await this.authority()==="host")throw new u("vault-host",P9);let $=await this.#T().catch((Z)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${x0(Z)}. Is the vault running?`)});try{let Z=new h5({client:$,paths:this.paths,proposedName:this.name,displayName:cX(this.host),requestedGrants:dX,...this.#Z.now?{now:this.#Z.now}:{}}),J=await Z.status();if(J.state==="denied"||J.state==="blocked")await Z.resetTerminal();let X=await Z.reconcile();if(Q0.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{$.close()}}waitForApproval($={}){return this.#Y??=(async()=>{let Z=$.sleep??((G)=>new Promise((B)=>setTimeout(B,G))),J=$.pollIntervalMs??2000,X=Date.now()+($.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if($.onPending?.(z),Date.now()>=X)return z;await Z(J),z=await this.connectStep()}return z})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){if(await this.authority()==="host")throw new u("vault-host",P9);await b5(this.paths.tokenPath,{force:!0}),await b5(this.paths.statePath,{force:!0}),await this.#Z.afterDisconnect?.(),await this.authority(),this.#J=void 0,Q0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())m5({mode:"custody",auth:$,provider:"openai"})}close(){this.#K=!0,this.#V.resolve(),this.#$.close()}async dispose(){this.close(),await this.#$.dispose()}}function nX($){if(!$)return;let Z=b0($).limits.map((J)=>J.checkedAt);return Z.length>0?Math.max(...Z):void 0}function x6($,Z){if(Z.state!=="pending")return[];if(!Z.requestId)return[`The vault did not take the enrollment request yet${Z.retryCode?` (${Z.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${Z.requestId} for ${$} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${Z.requestId}`,...Z.requestedGrantsStatus==="sent"?[]:[`Then grant OpenAI access to the name you approved with --name (defaults to ${$}):`,` ${O6($)}`]]}function s5($,Z,J){let X=`${d5[$]} (${J.state==="approved"?J.approvedName??Z:Z})`;switch(J.state){case"approved":return`${X}: connected to the Claustrum vault.`;case"idle":return`${X}: not connected to the Claustrum vault.`;case"pending":return J.requestId?`${X}: waiting for approval of request ${J.requestId}.`:`${X}: enrollment request not taken yet${J.retryCode?` (${J.retryCode})`:""}.`;case"denied":return`${X}: the vault denied the enrollment request.`;case"blocked":return`${X}: enrollment stopped (${J.code}).`;case"unavailable":return`${X}: the vault is unavailable (${J.code}).`;case"busy":return`${X}: another process is enrolling right now.`}}function C9($,Z){if((Z.state==="blocked"||Z.state==="unavailable")&&Z.code==="unknown_method")return{ok:!1,text:'Enrollment stopped (unknown_method). This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), then run Connect again.'};switch(Z.state){case"approved":{let J=Z.approvedName??$.name,X=$.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${J}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?`. ${S6(J,$.grantReach())}`:"."}`}}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 (${Z.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...x6($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
|
|
2
|
-
`)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var T9="/backend-api/wham/rate-limit-reset-credits",rX=`https://chatgpt.com${T9}`,t5=`${T9}/consume`,oX=`https://chatgpt.com${t5}`,tX=300000,eX=60000,$z=15000,Zz=60000;function v2($){return{configPath:$.configPath,statePath:$.statePath}}class W0 extends Error{kind;cooldownUntil;constructor($,Z,J){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=J}}class F2 extends Error{kind;status;constructor($,Z,J){super(Z);this.name="ResetCreditError",this.kind=$,this.status=J}}function e5($,Z,J){return{authorization:`Bearer ${$}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function g6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function $Z($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function f6($){if(!g6($)||typeof $.redeemRequestId!=="string"||$.redeemRequestId.length===0||typeof $.creditId!=="string"||$.creditId.length===0||typeof $.startedAt!=="number"||!Number.isFinite($.startedAt)||$.chatgptAccountId!==void 0&&(typeof $.chatgptAccountId!=="string"||$.chatgptAccountId.length===0))return;return{redeemRequestId:$.redeemRequestId,creditId:$.creditId,startedAt:$.startedAt,...typeof $.chatgptAccountId==="string"?{chatgptAccountId:$.chatgptAccountId}:{},...ZZ($.rejectedStatus)?{rejectedStatus:$.rejectedStatus}:{},...typeof $.unknownAnswers==="number"&&Number.isSafeInteger($.unknownAnswers)&&$.unknownAnswers>0?{unknownAnswers:$.unknownAnswers}:{}}}function ZZ($){return typeof $==="number"&&$>=400&&$<500&&$!==408&&$!==409&&$!==425&&$!==429}function y6($){return $.kind==="http_error"&&ZZ($.status)}function JZ($,Z){return $.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z||$.rejectedStatus!==void 0}function Jz($,Z){if($.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z)throw new W0("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function XZ($){return Boolean($&&Object.hasOwn($,"inFlight"))}function zZ($,Z){return Z-$.startedAt<tX}function h2($,Z){if(!u0(Z))return;return $.reset?.[Z]}function GZ($){if(!$.reset)$.reset=Object.create(null);return $.reset}function BZ($,Z,J){if(!u0(Z))return;let X=GZ($),z=X[Z]??{},G=z.lastOutcome;delete z.inFlight,z.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[Z]=z}function QZ($,Z){let J=$Z($),X=f6($?.inFlight);if(XZ($)&&!X)return{kind:"corrupt",beforeState:J};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:J,cooldownUntil:$.cooldownUntil};if(X&&zZ(X,Z))return{kind:"claim",beforeState:J,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:J,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:J}}async function Xz($,Z){if(!u0(Z))return{kind:"fresh",beforeState:void 0};let J=await $.loadAccountsFn(v2($));return QZ(J?h2(J,Z):void 0,$.now())}async function zz($,Z){let J;if(await $.mutateAccountsFn((X)=>{let z=$.now(),G=h2(X,Z);if(J=QZ(G,z),J.kind==="corrupt")BZ(X,Z,z);return X},v2($)),!J)throw Error("corrupt reset state mutation did not run");return J}async function Gz($,Z,J,X){if(!u0(Z))return{kind:"fresh",beforeState:void 0};let z;if(await $.mutateAccountsFn((G)=>{let B=$.now(),W=h2(G,Z),Q=$Z(W),Y=f6(W?.inFlight);if(XZ(W)&&!Y)return BZ(G,Z,B),z={kind:"corrupt",beforeState:Q},G;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>B)return z={kind:"cooldown",beforeState:Q,cooldownUntil:W.cooldownUntil},G;if(Y&&zZ(Y,B))return z={kind:"claim",beforeState:Q,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}},G;if(Y&&!JZ(Y,X))return z={kind:"expired_unreconciled",beforeState:Q,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}},G;let V=v6(J);if(!V)return z={kind:"fresh",beforeState:Q},G;let H={redeemRequestId:$.randomUUID(),creditId:V.id,startedAt:B,...X===void 0?{}:{chatgptAccountId:X}},q=GZ(G);return q[Z]={...W,inFlight:H},z={kind:"claim",beforeState:Q,claim:{inFlight:H,selectedCredit:V}},G},v2($)),!z)throw Error("reset claim mutation did not run");return z}async function Bz($,Z,J,X,z){if(!u0(Z))return;if(!O9(X.kind))return Qz($,Z,J,X,z);await $.mutateAccountsFn((G)=>{let B=h2(G,Z),W=f6(B?.inFlight);if(!B||!W||W.redeemRequestId!==J.redeemRequestId||W.creditId!==J.creditId)return G;let Q=$.now();if(delete B.inFlight,B.lastOutcome={code:X.kind,at:Q},X.kind==="reset"||X.kind==="already_redeemed")B.cooldownUntil=Q+Zz;else delete B.cooldownUntil;return G},v2($));return}function a5($,Z){let J=f6($?.inFlight);return J&&J.redeemRequestId===Z.redeemRequestId&&J.creditId===Z.creditId?J:void 0}async function Qz($,Z,J,X,z){let G=y6(X)?X.status:void 0;if(!(J.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===J.rejectedStatus){let Q=await $.loadAccountsFn(v2($));return a5(Q?h2(Q,Z):void 0,J)}let W;return await $.mutateAccountsFn((Q)=>{W=void 0;let Y=h2(Q,Z),V=a5(Y,J);if(!Y||!V)return Q;let H={...V};if(H.chatgptAccountId===void 0&&z!==void 0)H.chatgptAccountId=z;if(G===void 0)delete H.rejectedStatus,H.unknownAnswers=(V.unknownAnswers??0)+1;else if((V.unknownAnswers??0)===(J.unknownAnswers??0))H.rejectedStatus=G;return Y.inFlight=H,W=H,Q},v2($)),W}function D4($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let J=Date.parse($.resetsAt);return!Number.isFinite(J)||J>Z}function L9($,Z,J){if(!(Z||D4($.primary,J)||D4($.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function i5($,Z){let J=$[Z];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function Wz($){if(!g6($))return;let Z=i5($,"granted_at"),J=i5($,"reset_type");if(typeof $.id!=="string"||typeof $.status!=="string"||typeof $.expires_at!=="string"||Number.isNaN(Date.parse($.expires_at))||typeof $.is_supported_by_plan!=="boolean"||Z===null||J===null)return;return{id:$.id,status:$.status,...Z===void 0?{}:{grantedAt:Z},expiresAt:$.expires_at,...J===void 0?{}:{resetType:J},isSupportedByPlan:$.is_supported_by_plan}}async function _9($,Z,J){let X;try{X=await $(rX,{method:"GET",headers:e5(Z,T9,J),signal:AbortSignal.timeout($z)})}catch{throw new F2("http_error","reset credit list request failed")}if(!X.ok)throw new F2("http_error",`reset credit list request failed: ${X.status}`,X.status);let z;try{z=await X.json()}catch{throw new F2("invalid_response","reset credit list response was not valid JSON",X.status)}if(!g6(z))throw new F2("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((B)=>{let W=Wz(B);return W===void 0?[]:[W]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function v6($){return[...$].filter(WZ).sort((Z,J)=>Date.parse(Z.expiresAt)-Date.parse(J.expiresAt))[0]}function WZ($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function YZ($){return $.filter(WZ).length}function O9($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function Yz($,Z,J,X,z){let G;try{G=await $(oX,{method:"POST",headers:{...e5(Z,t5,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:X}),signal:AbortSignal.timeout(eX)})}catch(Y){return{kind:"ambiguous",raw:Y}}let B;try{B=await G.text()}catch(Y){return G.ok?{kind:"ambiguous",raw:Y}:{kind:"http_error",raw:Y,status:G.status}}let W=B,Q=!1;try{W=JSON.parse(B),Q=!0}catch{}if(!G.ok)return{kind:"http_error",raw:W,status:G.status};if(!Q||!g6(W)||!O9(W.code))return{kind:"ambiguous",raw:W};return{kind:W.code,raw:W}}function n5($){if($.kind==="cooldown")throw new W0("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function r5(){throw new W0("expired_unreconciled","the previous reset attempt outcome is unknown")}function o5($,Z){return{target:$,selectedCredit:void 0,beforeState:Z,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function Vz($){if($.kind==="reset"||$.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if($.kind==="nothing_to_reset"||$.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(y6($))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 Hz($,Z){if($)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(Z)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 VZ($,Z){if(!u0(Z.accountKey))throw new W0("invalid_account_key","the reset account key is reserved");let J=await $.resolveTarget(Z.accountKey);if(J.chatgptAccountId!==Z.expectedChatgptAccountId)throw new W0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=J.chatgptAccountId,z=J.accountKey==="main"?void 0:X,G=await Xz($,Z.accountKey);if(G.kind==="corrupt"){if(G=await zz($,Z.accountKey),G.kind==="corrupt")return o5(J,G.beforeState)}if(G.kind==="cooldown")n5(G);let B;if(G.kind==="claim")B=G.claim;else if(G.kind==="expired_unreconciled"&&(Z.retry||!JZ(G.claim.inFlight,X))){if(!Z.retry)r5();B=G.claim}else{if(Z.retry)throw new W0("retry_without_inflight","there is no active reset credit redemption to retry");let[q,F]=await Promise.all([$.fetchUsage(J),_9($.fetchImpl,J.accessToken,z)]),U=L9(q,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!U.ok)throw new W0("not_exhausted",U.reason);if(!v6(F.credits))throw new W0("no_eligible_credit","no eligible reset credit was returned");let j=await Gz($,Z.accountKey,F.credits,X);if(j.kind==="corrupt")return o5(J,j.beforeState);if(j.kind==="cooldown")n5(j);if(j.kind==="expired_unreconciled")r5();if(j.kind!=="claim")throw new W0("no_eligible_credit","no eligible reset credit was available while claiming");B=j.claim}Jz(B.inFlight,X);let W=await Yz($.fetchImpl,J.accessToken,z,B.inFlight.creditId,B.inFlight.redeemRequestId),Q,Y=!1;try{Q=await Bz($,Z.accountKey,B.inFlight,W,X)}catch{Y=!0}let V=Y&&O9(W.kind),H=y6(W)&&!Y&&Q?.rejectedStatus!==void 0;return{target:J,selectedCredit:B.selectedCredit,beforeState:G.beforeState,outcome:W,retrySafety:V?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":y6(W)&&!H?Hz(Y,Q):Vz(W),...H?{refused:!0}:{},...V?{finalizeStateWriteFailed:!0}:{}}}async function HZ($){let Z=[];for(let J of $)try{Z.push(...await J.run())}catch(X){Z.push({code:"doctor-check-failed",message:`Check ${J.id} failed: ${X instanceof Error?X.message:String(X)}`})}return{findings:Z}}function UZ($,Z){let J=[$];if(Z.findings.length===0)return J.push("No problems found."),J;for(let X of Z.findings){let z=X.repair?" (repair available)":"";J.push(`- ${X.message}${z}`)}return J}async function qZ($,Z){let J={applied:[],declined:[],failed:[]};for(let X of Z.findings){let z=X.repair;if(!z)continue;if(!await $.confirm(`Apply repair: ${z.label}?`)){J.declined.push(X);continue}try{await z.apply(),J.applied.push(X)}catch(G){J.failed.push({finding:X,error:G}),$.print(`Repair failed: ${z.label}: ${G instanceof Error?G.message:String(G)}`)}}return J}function S9($){let Z=$.title??"Auth doctor";return{id:"doctor",label:$.label??"Auth doctor",hint:"check accounts and offer repairs",async run(J){let X=await HZ($.checks);for(let B of UZ(Z,X))J.print(B);let z=X.findings.filter((B)=>B.repair);if(z.length===0){if(X.findings.length>0)J.print("No repairs are available.");return}let G=await qZ(J,X);J.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as Uz}from"node:child_process";function FZ($,Z=process.platform,J=Uz){try{if(Z==="win32"){let z=`Start-Process '${$.replaceAll("'","''")}'`,G=J("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(z,"utf16le").toString("base64")],{stdio:"ignore",windowsHide:!0});return G.on("error",()=>{}),G.unref(),G.pid!==void 0}let X=J(Z==="darwin"?"open":"xdg-open",[$],{stdio:"ignore"});return X.on("error",()=>{}),X.unref(),X.pid!==void 0}catch{return!1}}function jZ($,Z){if($.print(""),$.print("Open this URL in your browser and complete sign-in:"),$.print(""),$.print(Z.url),$.print(""),Z.instructions)$.print(Z.instructions),$.print("")}async function h6($,Z){let J=new AbortController,X=await $.begin({headless:!1,signal:J.signal});X.completion.catch(()=>{}),jZ(Z,X);let z=!1;try{z=await($.openBrowser??FZ)(X.url)!==!1}catch{z=!1}if(!z)J.abort(),Z.print("Could not open a browser. Switching to device authorization."),Z.print(""),X=await $.begin({headless:!0}),jZ(Z,X);return X.completion}var k={hide:"\x1B[?25l",show:"\x1B[?25h",up:($=1)=>`\x1B[${$}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:($,Z)=>`\x1B[${$};${Z}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function A9($){let Z=$.toString(),J=[];for(let X=0;X<Z.length;){let z=Z[X];if(z==="\x1B"){let G=Z.slice(X,X+3),B=G[1]==="["||G[1]==="O"?G[2]:void 0;if(B&&"ABCD".includes(B)){let Q={A:"up",B:"down",C:"right",D:"left"}[B];if(Q)J.push(Q);X+=3}else if(X+1===Z.length){if(X===0)J.push("escape-start");X+=1}else if((Z[X+1]==="["||Z[X+1]==="O")&&X+2>=Z.length)break;else X+=1;continue}if(z==="\r"||z===`
|
|
3
|
-
`)J.push("enter");else if(z==="\x03")J.push("escape");else if(z&&z>=" ")J.push("char");X+=1}return J}var
|
|
1
|
+
import{$d as I6,Bd as a3,Cd as n3,Ce as N4,Dd as i3,De as Z7,Ee as F8,Fd as x7,Gd as y7,Ge as K8,Hd as S3,He as _4,Id as A3,Jd as b3,Je as T4,Kd as x5,Ke as u0,Ld as y5,Me as Q1,Nd as u6,Od as P9,Pd as f2,Pe as N8,Qe as tZ,Sd as g5,Ud as f5,Vd as v5,Ve as C4,Wd as R6,Xd as h5,Zd as m5,_d as w5,_e as G7,ae as O7,af as B7,be as u5,bf as Q7,ce as p5,df as D8,ee as f7,ef as P8,fe as b4,ge as v7,gf as E6,he as X7,hf as K7,ie as z7,jf as vZ,me as b6,ne as k6,qf as N7,rd as r0,sd as g7,td as B1,ud as s3,wd as w6,xd as I0,yd as fZ,zd as b0,ze as O4}from"./index-3mbw88h7.js";import{Bf as d4,Cf as e$,vf as o$,wf as P0,xf as t$,yf as y1,zf as K0}from"./index-snq7bwr6.js";import{Mf as d7}from"./index-gkye2xh1.js";import{$f as k4,Tf as f3,Xf as o,Yf as C7,_f as H$,ag as U$,bg as x0}from"./index-pc4vrrex.js";import{eg as o4,lg as r$}from"./index-2f330s35.js";class b extends Error{operation;rowId;phase;retryable;kind;committed;constructor($){super($.message??`${$.operation} failed (${$.kind}, ${$.phase})`,$.cause===void 0?void 0:{cause:$.cause});this.name="PoolOperationError",this.operation=$.operation,this.rowId=$.rowId,this.phase=$.phase,this.retryable=$.retryable,this.kind=$.kind,this.committed=$.committed}}class i2 extends Error{operation;constructor($){super(`${$} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=$}}var C2="identity-contradicted: ",L1="duplicate-identity";function s0($,Z,J){let X=$.rosterRow(Z);if(!X)return;X.enabled=!1;let z=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");$.setEntry(Z,{...z,disabledReason:G?z.disabledReason:J})}function r2($,Z){let J=$.rosterRow(Z);if(!J)return;J.enabled=!0;let X=$.entry(Z);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,$.setEntry(Z,z)}}function T2($,Z){let J=$.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===Z),X=[];for(let z of J.slice(1))s0($,z.id,"duplicate-identity"),X.push(z.id);return X}function J2($,Z,J){let X=$.rosterRow(Z);if(!X)return[];return X.accountId=J,T2($,J)}import{AsyncLocalStorage as y$}from"node:async_hooks";var l4=new y$,g$=new y$;function a($){if(l4.getStore()!==void 0)throw new i2($)}function f$(){if(l4.getStore()?.storeLocksReleased===!1||g$.getStore())throw new i2("updateLimitsNamespace")}function z0($){return g$.run(!0,$)}function G0($,Z,J=!1){return l4.run({operation:$,storeLocksReleased:J&&l4.getStore()?.storeLocksReleased!==!1},async()=>await Z())}async function v$($,Z,J,X,z){if(!Z)return;try{await G0($,()=>Z(J,X),!0)}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:J,error:G instanceof Error?G.message:String(G)})}}import{setTimeout as LJ}from"node:timers/promises";var _1=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function QJ($,Z,J){let X=(B)=>{try{let W=J.onLockEvent?.({type:B,name:$.name,path:$.path});if(W&&(typeof W==="object"||typeof W==="function")&&"then"in W&&typeof W.then==="function")Promise.resolve(W).catch(()=>{})}catch{}},z={...Z,...WJ($)},G=performance.now();for(;;){let B=await K0({name:$.name,path:$.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>X("contended"),...J.onRenewalTimer?{onRenewalTimer:(Y)=>J.onRenewalTimer?.({name:$.name,path:$.path},Y)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...J.onLockStep?{onStep:(Y)=>J.onLockStep?.({name:$.name,path:$.path},Y)}:{}});if(B){X("acquired");let Y={name:$.name,path:$.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),X("released")}};try{await Y.assertOwned()}catch(V){throw await Y.release(),V}return Y}let W=z.timeoutMs-(performance.now()-G);if(W<=0)throw new d4({target:$.path,name:$.name,timeoutMs:z.timeoutMs});let Q=Math.floor(Math.random()*(z.retryMs+1));await new Promise((Y)=>setTimeout(Y,Math.min(z.retryMs+Q,W)))}}function WJ($){let Z={};if($.ttlMs!==void 0)Z.ttlMs=$.ttlMs;if($.timeoutMs!==void 0)Z.timeoutMs=$.timeoutMs;if($.retryMs!==void 0)Z.retryMs=$.retryMs;if($.renew!==void 0)Z.renew=$.renew;if($.renewIntervalMs!==void 0)Z.renewIntervalMs=$.renewIntervalMs;return Z}class A0{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await QJ($,this.defaults,this.env);return this.held.push(Z),await this.assertAll(),Z}async assertAll(){for(let $ of this.held)await $.assertOwned()}async releaseTo($){while(this.held.length>$)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}function X2($,Z,J){if(J!==void 0)throw new b({operation:$,rowId:Z,kind:"row-staged",phase:$==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${Z} is reserved for roster publication`})}import{createHash as o2}from"node:crypto";var v="commonAuthPool",a0=1,N0="rows",c4="retiredEpochs",t2=1,O1=300000,g=v;function YJ($){let Z=JSON.parse(JSON.stringify($)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(S(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J(Z)}function z2($){return o2("sha256").update(YJ($)).digest("hex")}function h$($){if(!S($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function VJ($){if(!S($)||typeof $.reservation!=="string"||!$.reservation||typeof $.disabledReason!=="string")return;if(Object.keys($).some((Z)=>!["reservation","label","disabledReason","providerState"].includes(Z)))return;if("label"in $&&typeof $.label!=="string")return;if("providerState"in $&&(typeof $.providerState!=="string"||!/^[a-f0-9]{64}$/.test($.providerState)))return;return $}var i="commonAuthProviderState";function S($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var HJ=new Set(["__proto__","constructor","prototype"]);function L2($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(HJ.has($))return"id is a reserved object key";return}function S1($){let Z=typeof $==="string"?$.trim():"";if(!Z)return!1;try{let J=new URL(Z);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function m$($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function D0($){return o2("sha256").update(m$($)).digest("hex")}function E0($){return o2("sha256").update(`credential-stamp\x00${m$($)}`).digest("hex")}function f0($){let Z=$.type==="oauth"?["oauth",typeof $.access==="string"?$.access:null,$.refresh,typeof $.expires==="number"&&Number.isFinite($.expires)?$.expires:null]:["api",$.apiKey,$.baseURL.trim(),$.authHeader??"authorization-bearer"];return o2("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function A1($,Z,J,X={}){return{credentialEpoch:Z,digest:E0($),dispatch:f0($),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function _2($,Z){let J=$?.credentialBound?z0(()=>$.credentialBound?.(Z)):Z;return o2("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function e2($,Z,J,X){if(!Z||J===void 0)return;if(!S($)||!Object.hasOwn($,i))return;let z=t($[g]);if(!z||z.providerState===void 0||z.digest!==E0(Z)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function s($){return Number.isSafeInteger($)&&$>=1}function t($){if(!S($))return;let Z=$.credentialEpoch;if(!s(Z))return;if(typeof $.digest!=="string")return;if("dispatch"in $&&typeof $.dispatch!=="string")return;if("replace"in $&&$.replace!==!0)return;if("providerState"in $&&typeof $.providerState!=="string")return;let J="staged"in $?VJ($.staged):void 0;if("staged"in $&&!J)return;let X={...J?{staged:J}:{},...typeof $.dispatch==="string"?{dispatch:$.dispatch}:{},...$.replace===!0?{replace:!0}:{},...typeof $.providerState==="string"?{providerState:$.providerState}:{}};if(!("binding"in $))return"dispatch"in $||"replace"in $||"providerState"in $||"staged"in $?void 0:{credentialEpoch:Z,digest:$.digest};let z=$.binding;if(!S(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!S1(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...X,binding:{...typeof z.identity==="string"?{identity:z.identity}:{},...typeof z.baseURL==="string"?{baseURL:z.baseURL.trim()}:{},...z.authHeader==="authorization-bearer"||z.authHeader==="x-api-key"?{authHeader:z.authHeader}:{}}}}function UJ($,Z,J){if($.identity!==J)return!1;if($.baseURL!==void 0&&(Z.type!=="api"||Z.baseURL!==$.baseURL))return!1;if($.authHeader!==void 0&&(Z.type!=="api"||Z.authHeader!==$.authHeader))return!1;return!0}function qJ($,Z,J,X){if(!$)return"none";if(!S(X)||!Object.hasOwn(X,g))return"missing";let z=t(X[g]);if(!z)return"malformed";if(z.digest!==E0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!UJ(z.binding,$,J))return"mismatched";if(z.dispatch!==f0($))return"mismatched";return"bound"}function E1($){if(!$.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in $)return{status:"error",reason:"config file is not valid JSON"};let Z=$.value;if(!S(Z))return{status:"error",reason:"config root is not an object"};if("accounts"in Z&&!Array.isArray(Z.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(v in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let J=Z[v];if(!S(J))return{status:"error",reason:`${v} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${v}.schemaVersion is invalid`};if(X>a0)return{status:"error",reason:`${v}.schemaVersion ${X} is newer than ${a0}`};if(N0 in J&&!S(J[N0]))return{status:"error",reason:`${v}.${N0} is not an object`};return{status:"ready",exists:!0,config:Z}}function w$($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!S($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!S($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function O2($){return Array.isArray($.accounts)?$.accounts:[]}function u$($){let Z=$[v];if(!S(Z))return{};let J=Z[N0];return S(J)?J:{}}function jJ($){return S($.accounts)?$.accounts:{}}function FJ($){if(!S($))return"not an object";let Z=L2($.id);if(Z)return Z;if($.type==="api")return S1($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function KJ($,Z){if(!S($))return;let J=$.credentialEpoch;if(!s(J))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let X="quota"in $&&Z.decode?z0(()=>Z.decode?.($.quota)):$.quota;if("quota"in $&&!z0(()=>Z.validate(X)))return;if("staged"in $&&!h$($.staged))return;return{credentialEpoch:J,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:X}:{}}}function NJ($,Z){if(!S(Z))return;if($.type==="api"){let X=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if($.corrupt===!0)return;let J=Z.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.lastRefreshedAt==="number"?{lastRefreshedAt:Z.lastRefreshedAt}:{}}}function s4($,Z){return O2($).find((J)=>S(J)&&J.id===Z)}function p$($){if(!S($[v]))$[v]={};return $[v]}function R1($){let Z=p$($);if(!S(Z[N0]))Z[N0]={};return Z[N0]}function R0($,Z){let J=u$($),X=Object.hasOwn(J,Z)?J[Z]:void 0;return S(X)?X:void 0}function a4($,Z,J){Object.defineProperty(R1($),Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function l$($,Z){let J=$[v];if(!S(J))return;let X=J[c4];if(!S(X)||!Object.hasOwn(X,Z))return;let z=X[Z];return s(z)?z:void 0}function d$($,Z){let J=R0($,Z)?.credentialEpoch;return s(J)?J:void 0}function n4($,Z){return Math.max(l$($,Z)??0,d$($,Z)??0)+1}function c$($,Z){let J=[...Z];if(J.length===0)return;let X=p$($),z=S(X[c4])?X[c4]:{},G={},B=(W,Q)=>Object.defineProperty(G,W,{value:Q,enumerable:!0,writable:!0,configurable:!0});for(let[W,Q]of Object.entries(z))if(s(Q))B(W,Q);for(let W of J)B(W,Math.max(l$($,W)??0,d$($,W)??1));X[c4]=G}function n0($,Z,J,X){let z=u$($),G=jJ(Z),B=new Set,W=[];for(let Q of O2($)){let Y=FJ(Q),V=S(Q)&&typeof Q.id==="string"?Q.id:void 0,H=V===void 0?void 0:z[V],q=S(H)&&Object.hasOwn(H,"staged"),F=q?h$(H.staged):void 0;if(Y||!S(Q)||V===void 0||B.has(V)){if(V!==void 0&&!B.has(V))B.add(V);if(V!==void 0)W.push({id:V,type:S(Q)&&Q.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,V),candidate:!1,invalid:"roster",stamp:"none",...F?{staged:F}:{}});continue}B.add(V);let U=Q.type==="api"?"api":"oauth",j=Object.hasOwn(z,V),K=j?KJ(z[V],J):void 0,N=NJ(Q,G[V]),D=Q.enabled!==!1,O=K?K.credentialEpoch:j?void 0:1,M=typeof Q.accountId==="string"&&Q.accountId?Q.accountId:void 0,P={id:V,type:U,enabled:D,needsFirstReading:K?K.needsFirstReading:U==="oauth",hasEntry:j,candidate:!1,...typeof Q.label==="string"?{label:Q.label}:{},...typeof Q.addedAt==="number"?{addedAt:Q.addedAt}:{},...M!==void 0?{identity:M}:{},...N?{credential:N,fingerprint:D0(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...F?{staged:F}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...DJ(G[V],N,O,M,X),stamp:qJ(N,O,M,G[V])};if(j&&!K)P.invalid="entry";else P.candidate=D&&N!==void 0&&!q;W.push(P)}return W}function DJ($,Z,J,X,z){if(!S($)||!Object.hasOwn($,i))return{};let G=e2($,Z,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let B=$[i];if(!z||!z0(()=>z.validate(B)))return{providerStateDropped:"invalid"};if(_2(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function h($){return $.identity??$.id}function $4($,Z){if($===void 0||$>Z+O1)return Z;return Math.max(Z,$+1)}function I1($,Z){return $4($,Z)>Z+O1}function S2($){let{id:Z,credential:J,identity:X,label:z,addedAt:G}=$;return{id:Z,...z!==void 0?{label:z}:{},type:J.type,addedAt:G,...X!==void 0?{accountId:X}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}}}function s$($,Z){if($.type==="api")return{apiKey:$.apiKey};return{...$.access!==void 0?{access:$.access}:{},refresh:$.refresh,...$.expires!==void 0?{expires:$.expires}:{},...Z!==void 0?{lastRefreshedAt:Z}:{}}}function a$($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function n$($,Z={}){if(!S($))return"credential must be an object";if($.type==="oauth"){if(typeof $.refresh!=="string"||!$.refresh.trim())return"oauth credential needs a refresh token";return}if($.type==="api"){if(typeof $.apiKey!=="string"||!$.apiKey.trim())return"api credential needs an api key";if($.apiKey.trim()!==$.apiKey)return"api key must not carry surrounding whitespace";if(!(Z.baseURLOptional&&$.baseURL===void 0)&&!S1($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var i4="transition",i$="transitionMark";function PJ($){if(!S($))return;let Z=$[i4];if(!S(Z))return;if(typeof Z.mark!=="string"||Z.mark.length===0)return;if(Z.enabled===!0)return{mark:Z.mark,enabled:!0};if(Z.enabled===!1&&typeof Z.reason==="string")return{mark:Z.mark,enabled:!1,reason:Z.reason};return}function Z4($,Z,J){if(J.enabled)r2($,Z);else s0($,Z,J.reason??"");if(!$.rosterRow(Z))return;let X=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...X,[i$]:J.mark}),!J.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)T2($,z.identity)}function MJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function CJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function TJ($,Z,J,X={}){let z=S(Z.accounts)?Z.accounts:{},G=new Map;for(let B of n0($,Z,J)){if(B.invalid||B.staged||!B.credential)continue;let W=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!S(W))continue;let Q=t(W[g]);if(!Q?.binding)continue;if(Q.digest!==E0(B.credential))continue;let Y=B.credentialEpoch??1;if(Q.credentialEpoch>Y){if(!CJ(Q))continue;if(X.requireCredentialStamps){if(Q.dispatch===void 0)continue;if(Q.dispatch!==f0(MJ(B.credential,Q.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...Q,binding:Q.binding}})}else if(Q.credentialEpoch===Y&&Q.dispatch!==void 0&&Q.dispatch===f0(B.credential)&&Q.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:Q.binding.identity});else if(Q.credentialEpoch===Y&&Q.binding.identity===B.identity){if(X.requireCredentialStamps&&Q.dispatch!==f0(B.credential))continue;let V=PJ(W[g]);if(V&&R0($,B.id)?.[i$]!==V.mark)G.set(B.id,{kind:"transition",transition:V})}}return G}function b1($,Z,J,X){let G={...$.entry(Z)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(C2))delete G.disabledReason;$.setEntry(Z,G);let B=$.rosterRow(Z);if(!B)return;if(X.identity!==void 0)B.accountId=X.identity;else delete B.accountId;if(X.baseURL!==void 0)B.baseURL=X.baseURL;if(X.authHeader!==void 0)B.authHeader=X.authHeader}function k1($,Z,J,X={}){let z=TJ($,Z,J,X);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),B={rows:()=>n0(G,Z,J),rosterRow:(W)=>s4(G,W),entry:(W)=>R0(G,W),setEntry:(W,Q)=>a4(G,W,Q)};for(let[W,Q]of z)if(Q.kind==="replace")b1(B,W,Q.stamp.credentialEpoch,Q.stamp.binding);for(let[W,Q]of z)if(Q.kind==="identity")J2(B,W,Q.identity);else if(Q.kind==="transition")Z4(B,W,Q.transition);else if(Q.stamp.binding.identity!==void 0)T2(B,Q.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function x1($,Z,J,X={}){let{config:z,torn:G}=k1($,Z,J,X),B=n0(z,Z,J,X.providerState);for(let W of B){if(G.includes(W.id))W.torn=!0,W.candidate=!1;if(X.requireCredentialStamps&&W.stamp!=="bound")W.unbound=!0,W.candidate=!1}return B}async function r4($){try{return await r$($,o4)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function g1($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function $3($){return E1(g1(await r4($)))}async function n($){for(let Z=0;Z<3;Z++){let J=await r4($.configPath),X=await r4($.statePath),z=await r4($.configPath);if(J!==z){if(Z<2)await LJ(2+Math.floor(Math.random()*4));continue}let G=E1(g1(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=w$(g1(X));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:B.exists,config:G.config,state:B.state,rows:x1(G.config,B.state,$.codec,{requireCredentialStamps:$.requireCredentialStamps===!0,...$.providerState?{providerState:$.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function $0($,Z,J,X="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:$.reason});return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,retryable:!1,kind:$.status==="pending-migration"?"pending-migration":"load-error",message:$.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${$.file} file cannot be loaded: ${$.reason}`})}class Z3{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,J,X,z){this.ctx=$,this.snapshot=Z,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return x1(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row($){return this.rows().find((Z)=>Z.id===$)}reservation($){if(this.rosterRow($)){let J=this.entry($);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let Z=this.stateAccount($)?.[g];return S(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){X2(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),s4(this.config,$)}dropRosterRows($){let Z=this.roster(),J=Z.filter((X)=>!(S(X)&&X.id===$));return this.config.accounts=J,Z.length-J.length}entries(){return R1(this.config)}entry($){return this.entries(),R0(this.config,$)}setEntry($,Z){a4(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=k1(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if(Z.length===0)return;this.config=$,await this.commitConfig({counted:!1})}stateAccount($){let Z=S(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn(Z,$)?Z[$]:void 0;return S(J)?J:void 0}dropStateAccount($){if(S(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!S(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,$,{value:Z,enumerable:!0,writable:!0,configurable:!0})}async commitConfig($={}){let Z=this.roster(),J=new Set;for(let Q of Z)if(S(Q)&&typeof Q.id==="string")J.add(Q.id);let X=new Set;for(let Q of O2(this.snapshot.config))if(S(Q)&&typeof Q.id==="string"&&!J.has(Q.id))X.add(Q.id);for(let Q of Object.keys(this.entries()))if(!J.has(Q))X.add(Q);c$(this.config,X);let z=this.entries(),G={};for(let[Q,Y]of Object.entries(z))if(J.has(Q))Object.defineProperty(G,Q,{value:Y,enumerable:!0,writable:!0,configurable:!0});let B=this.config[v],W={...this.config,version:t2,accounts:Z,[v]:{...B,schemaVersion:a0,[N0]:G}};await this.write(this.ctx.configPath,W,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let Q of X)this.ctx.removedIds.add(Q);this.config=W}),this.config=W}async commitState($,Z={}){let J={...this.state,version:t2,accounts:S(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,Z.durable??!1),this.state=J,$)this.progress.committed=$}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await y1(this.ctx.statePath)}catch($){throw new b({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:$})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await y1(this.ctx.configPath)}async write($,Z,J,X=!0,z=!1,G){await t$($,Z,{durable:z,beforeRename:async()=>{await this.ctx.onStep?.(`before-${J}-write`,this.info),await this.locks.assertAll()}},()=>{if(X)this.progress.writes++;G?.()}),await this.ctx.onStep?.(`after-${J}-write`,this.info)}}async function J3($,Z){let J=new A0($.lockDefaults,$.lockEnv),X={writes:0};try{for(let W of $.storeLocks)await J.acquire(W);let z=await n($);if(z.status==="error")throw $0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[W,Q]of Object.entries(z.config))if(!Z.includes(W))G[W]=Q;G.version=t2,G[v]={schemaVersion:a0,[N0]:{}};let B={operation:"initialize",rowId:void 0};return await P0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",B),await J.assertAll()}}),X.writes++,await $.onStep?.("after-config-write",B),"initialized"}catch(z){throw i0(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function w($,Z,J,X,z,G={}){let B=Z.held.length;try{for(let Y of $.storeLocks)await Z.acquire(Y);let W=await n($);if(W.status!=="ready")throw $0(W,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let Q=new Z3($,W,Z,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))Q.assertNotStaged(X.rowId);if(G.completeTorn??!0)await Q.completeTorn();return await z(Q)}finally{await Z.releaseTo(B)}}function i0($,Z,J,X){let z=Z==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if(Z==="publishRoster"&&X.publicationDecided)return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:z,kind:"publication-incomplete",retryable:!0,message:"The publication may already be decided. Replay the same plan or check publication(operationId).",cause:$});if(Z==="publishRoster"&&$ instanceof o$)return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof b){if($.phase===z&&$.rowId===J&&$.operation===Z&&$.committed===G)return $;return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:$.kind==="after-persist-hook"?$.phase:z,retryable:$.retryable,kind:$.kind,...$.committed??G?{committed:$.committed??G}:{},message:$.message,...$.cause!==void 0?{cause:$.cause}:{}})}let B={operation:Z,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof e$)return new b({...B,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${Z} lost a lease after its first write; the intermediate stays on disk`:`${Z} lost a lease before writing; nothing was written`});if($ instanceof d4)return new b({...B,retryable:!0,kind:"lock-contention",message:$.message});return new b({...B,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function l($,Z,J,X,z){let G=new A0($.lockDefaults,$.lockEnv),B={writes:0};try{return await z(G,B)}catch(W){let Q=i0(W,Z,J,B);if(Q.kind!=="after-persist-hook")await v$(Z,X,J,Q,$.logger);throw Q}finally{await G.releaseAll()}}function Z0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(h(Z))}`,path:$.ctx.statePath}}async function M0($,Z,J){let X=await n($.ctx);if(X.status!=="ready")throw $0(X,Z,J);let z=X.rows.find((Y)=>Y.id===J),G=R0(X.config,J),B=X.state.accounts,W=S(B)&&Object.hasOwn(B,J)?B[J]:void 0,Q=S(W)?W[g]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))X2(Z,J,G.staged);if(!z&&S(Q)&&Object.hasOwn(Q,"staged"))X2(Z,J,Q.staged);if(!z)throw B0(Z,J);return{result:X,row:z}}function B0($,Z){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function r($,Z){if(Z.unbound)throw _($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function _($,Z,J,X,z=!1){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function f1($,Z){if(!s(Z?.credentialEpoch))throw _("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function J4($,Z,J){if(!J)throw B0("pull",$);if(J.invalid)throw _("pull",$,"invalid-row",`row ${$} is invalid`);if(!J.credential)throw _("pull",$,"no-credential",`row ${$} holds no credential`);if(r("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==Z.credentialEpoch||J.identity!==Z.identity)throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${$} was issued for a credential the row no longer holds`})}function X4($,Z,J,X){let z=z0(()=>$.codec.merge(J,X));if(!z0(()=>$.codec.validate(z)))throw _("pull",Z,"invalid-quota","the quota codec rejected the merged map");return z}async function t4($,Z,J,X){let{ctx:z}=$,G=new A0(z.lockDefaults,z.lockEnv),B={writes:0};try{f1(Z,J),await w(z,G,B,{operation:"pull",rowId:Z},async(W)=>{W.assertNotStaged(Z);let Q=W.row(Z);J4(Z,J,Q);let Y=W.entry(Z);if(!Y)throw B0("pull",Z);let V=X4(z,Z,Y.quota,X);W.setEntry(Z,{...Y,quota:V,needsFirstReading:!1}),await W.commitConfig()},{completeTorn:!1})}catch(W){throw i0(W,"pull",Z,B)}finally{await G.releaseAll()}}async function X3($,Z,J={}){f$();let{ctx:X}=$;await l(X,"updateLimitsNamespace",void 0,void 0,async(z,G)=>{for(let H of X.storeLocks)await z.acquire(H);let B=await n(X);if(B.status!=="ready")throw $0(B,"updateLimitsNamespace",void 0);let W=B.rows.map(({id:H,credentialEpoch:q,identity:F})=>({id:H,credentialEpoch:q,identity:F})),Q=await G0("updateLimitsNamespace",()=>Z(structuredClone(B.config.commonAuthLimits),W)),Y={...B.config,commonAuthLimits:Q},V={operation:"updateLimitsNamespace",rowId:void 0};try{await P0(X.configPath,Y,{beforeRename:async()=>{await X.onStep?.("before-config-write",V),await z.assertAll(),J.beforePublish?.()}})}catch(H){if(H&&typeof H==="object"&&"published"in H&&H.published===!0)J.onPublished?.();throw H}G.writes++,J.onPublished?.(),await X.onStep?.("after-config-write",V)})}function v0($,Z,J,X,z="the provider state"){if(!$)throw _(Z,J,"invalid-input","the store was opened without a provider-state codec");let G;try{let B=JSON.stringify(X);G=B===void 0?void 0:JSON.parse(B)}catch{G=void 0}if(G===void 0)throw _(Z,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!z0(()=>$.validate(G)))throw _(Z,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function z4($,Z,J,X,z){if(X===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:v0($,Z,J,z0(()=>$.merge?.(structuredClone(X),structuredClone(z))),"the merged provider state")}}function z3($,Z,J,X,z){let G=$?.onReplace,B=G?z0(()=>G(Z.providerState===void 0?void 0:structuredClone(Z.providerState),{id:Z.id,credentialEpoch:J,...Z.identity!==void 0?{previousIdentity:Z.identity}:{},...X!==void 0?{identity:X}:{},...z!==void 0?{incoming:structuredClone(z)}:{}})):z;if(B===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:B};return{kind:"set",value:v0($,"replace",Z.id,B,"the provider state onReplace returned")}}function G3($,Z,J,X,z){if(Z.kind==="set")return _2($,Z.value);if(Z.kind==="clear")return;return e2(J,X?.credential,z,X?.identity)}async function B3($,Z,J,X,z={}){a("updateProviderState");let{ctx:G}=$,B="updateProviderState";return l(G,B,Z,z.onFailure,async(W,Q)=>{let Y=G.providerState;if(!Y)throw _(B,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw _(B,Z,"invalid-input","a mutator is required");let V=S(J)?J.credentialEpoch:void 0;if(!s(V))throw _(B,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:H}=await M0($,B,Z);await W.acquire(Z0($,H));for(let q of z.extraLocks??[])await W.acquire(q);return w(G,W,Q,{operation:B,rowId:Z},async(q)=>{let F=q.row(Z);if(!F)throw B0(B,Z);if(h(F)!==h(H))throw _(B,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(F.invalid)throw _(B,Z,"invalid-row",`row ${Z} failed validation`);if(!F.credential)throw _(B,Z,"no-credential",`row ${Z} holds no credential`);if(r(B,F),(F.credentialEpoch??1)!==V||F.identity!==J.identity)throw _(B,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let j=await v1(q,Y,B,F,X);if(j.kind!=="changed")return{id:Z,outcome:"unchanged",...j.kind==="unchanged"&&j.value!==void 0?{providerState:j.value}:{}};return q.setStateAccount(Z,j.account),await q.commitState(),j.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:j.value}})})}var Q3=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function v1($,Z,J,X,z,G=!1){let{id:B,credential:W}=X;if(!W)throw _(J,B,"no-credential",`row ${B} holds no credential`);let Q=X.credentialEpoch??1,Y=$.stateAccount(B),V=Y?.[g],H=t(V);if(!S(V)||!H?.binding||H.digest!==E0(W)||H.credentialEpoch!==Q||H.binding.identity!==X.identity)throw _(J,B,"unbound-credential",`row ${B}'s credential carries no stamp of this store to bind a provider state to (stamp ${X.stamp}); rotate or replace it first`);let q=X.providerState===void 0?void 0:structuredClone(X.providerState),F=await G0(J,()=>z(q,X));if(G&&F===Q3)return{kind:"declined"};let U=F===void 0?void 0:v0(Z,J,B,F,"the provider state the mutator returned"),j=Y!==void 0&&Object.hasOwn(Y,i);if(U===void 0?!j:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let K={...Y};if(U===void 0){delete K[i];let N={...V};delete N.providerState,K[g]=N}else{K[i]=U;let N=_2(Z,U);if(H.providerState!==N)K[g]={...V,providerState:N}}return{kind:"changed",...U!==void 0?{value:U}:{},account:K}}import{randomUUID as W3}from"node:crypto";async function J6($,Z,J){if(!J)return;let X=$.rows().map((G)=>{let{id:B,type:W,label:Q,enabled:Y,disabledReason:V,identity:H,credentialEpoch:q,stamp:F,staged:U,torn:j,invalid:K}=G;return{id:B,type:W,label:Q,enabled:Y,disabledReason:V,identity:H,credentialEpoch:q,stamp:F,staged:U,torn:j,invalid:K}}),z=await G0($.info.operation,()=>J({id:Z,row:X.find((G)=>G.id===Z),rows:X,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw _($.info.operation,Z,"row-protected",z)}var _J=["access","refresh","expires","lastRefreshedAt","apiKey"];function OJ($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function SJ($,Z,J){if(J.type!=="api")return J;let X=$.rosterRow(Z);if(!S(X)){if(J.baseURL===void 0)throw _($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=$.row(Z)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:OJ(X),B=J.baseURL?.trim()??G.baseURL,W=J.authHeader??G.authHeader;if(B!==G.baseURL||W!==G.authHeader)throw _($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:B,authHeader:W}}function Y3($,Z,J,X){let z=$.rosterRow(Z),G=$.row(Z),B=X??(G?G.identity:S(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...B!==void 0?{identity:B}:{},...J.type==="api"?{baseURL:J.baseURL,authHeader:J.authHeader??"authorization-bearer"}:{}}}function e4($,Z,J,X,z={}){let G=SJ(Z,J,X),B=Z.stateAccount(J),W=z.providerState??{kind:"keep"},Q=Z.row(J)?.credentialEpoch??Z.entry(J)?.credentialEpoch,Y=typeof Q==="number"?Q:1,V=G3($.ctx.providerState,W,B,B&&Object.hasOwn(B,i)?Z.row(J):void 0,Y),H=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,q=G.type==="oauth"?z.stamp??$4(H,$.ctx.now()):void 0,F={...B??{}};for(let K of _J)delete F[K];if(z.clearErrors)delete F.lastRefreshError,delete F.lastQuotaRefreshError,delete F.quota;if(W.kind==="clear")delete F[i];else if(W.kind==="set")F[i]=W.value;let U=a$(G,q),j={...F,...s$(G,q),[g]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[i4]:z.transition}:{},...A1(U,Y,z.binding??Y3(Z,J,U,z.identity),{replace:z.binding!==void 0,...V!==void 0?{providerState:V}:{}})}};return{stored:U,account:j}}async function $6($,Z,J){return $.setStateAccount(Z,J.account),await $.commitState(J.stored),J.stored}async function X6($,Z,J,X,z={}){return $6(Z,J,e4($,Z,J,X,z))}async function AJ($,Z,J){if(!Z.credential||Z.stamp!=="bound")return;let X=$.stateAccount(Z.id),z=e2(X,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...X??{},[g]:A1(Z.credential,Z.credentialEpoch??1,Y3($,Z.id,Z.credential,J),z!==void 0?{providerState:z}:{})}),await $.commitState()}function m1($,Z,J){let X=$==="add"?L2(Z):void 0;if(X)throw _($,Z,"invalid-input",X);let z=n$(J,{baseURLOptional:$==="rotate"});if(z)throw _($,Z,"invalid-input",z)}function z6($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if(X&&X.type!==J.type)throw _($,Z,"type-mismatch",`row ${Z} holds a ${J.type} credential`);return J}function E2($,Z,J){if(J!==void 0&&!s(S(J)?J.credentialEpoch:void 0))throw _($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function G6($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw _($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function Z6($,Z){return _($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function G4($,Z){return _($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function EJ($,Z,J,X){let{id:z,credential:G,identity:B}=J;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!A2(Z.state,z))return;let W=()=>{throw _("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Q=Z.stateAccount(z),Y=t(Q?.[g]);if(!Y?.binding||Y.dispatch===void 0||Y.replace)return W();if(G.type==="api"&&(Y.binding.baseURL===void 0||Y.binding.authHeader===void 0))return W();let V=G.type==="api"?{...G,baseURL:Y.binding.baseURL,authHeader:Y.binding.authHeader}:G,[H]=n0({accounts:[S2({id:z,credential:V,identity:Y.binding.identity,addedAt:0})],[v]:{rows:{[z]:{credentialEpoch:n4(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!H?.credential||H.invalid||H.stamp!=="bound")return W();if(B!==void 0&&B!==H.identity)return W();if(E0(G)!==Y.digest)return W();if(G.type==="api"){if(G.baseURL.trim()!==Y.binding.baseURL)return W();if((G.authHeader??"authorization-bearer")!==Y.binding.authHeader)return W()}else if(f0(G)!==Y.dispatch)return W();if(Y.providerState!==void 0&&H.providerState===void 0)return W();if(X!==void 0&&_2($.ctx.providerState,X)!==Y.providerState)return W();return H}function RJ($,Z,J,X){let{id:z,credential:G,identity:B,label:W}=J,Q=Z.rosterRow(z),Y=()=>{throw _("add",z,Q?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},V=Z.stateAccount(z),H=t(V?.[g]),q=H?.staged;if(!H?.binding||!q||H.replace||H.dispatch===void 0)return Y();if(Q&&(Q.type!==G.type||Q.label!==W||Q.accountId!==B))return Y();if(q.reservation!==J.stage?.reservation||q.label!==W||q.disabledReason!==J.disabled?.reason||H.binding.identity!==B)return Y();let F=X===void 0?void 0:z2(X),U=V?.[i],j=U===void 0?void 0:z2(U);if(q.providerState!==F||q.providerState!==j)return Y();if(E0(G)!==H.digest||f0(G)!==H.dispatch)return Y();let K=Q?Z.config:{accounts:[{...S2({id:z,credential:G.type==="api"?{...G,baseURL:H.binding.baseURL??"",authHeader:H.binding.authHeader}:G,identity:H.binding.identity,label:q.label,addedAt:0}),enabled:!1}],[v]:{rows:{[z]:{credentialEpoch:H.credentialEpoch,disabledReason:q.disabledReason,staged:{reservation:q.reservation}}}}},N=n0(K,Z.state,$.ctx.codec,$.ctx.providerState).find((D)=>D.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==q.label||N.identity!==H.binding.identity||N.disabledReason!==q.disabledReason||N.staged?.reservation!==q.reservation)return Y();if(Q)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:H.credentialEpoch};if(n4(Z.config,z)!==H.credentialEpoch)return Y();return Z.roster().push({...S2({id:z,credential:G,identity:B,label:W,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:H.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:q.disabledReason,staged:{reservation:q.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:H.credentialEpoch}))}async function V3($,Z,J={}){a("add");let{ctx:X}=$,{id:z,credential:G,identity:B,label:W}=Z,Q=Z.stage!==void 0||Z.disabled!==void 0,Y=await l(X,"add",z,J.onFailure,async(V,H)=>{m1("add",z,G);let q=J.onExisting??"rotate";if(Z.stage!==void 0&&q==="rotate")throw _("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(q)||Z.stage!==void 0&&(W!==void 0&&typeof W!=="string"||B!==void 0&&(typeof B!=="string"||!B))||Z.disabled!==void 0&&(!S(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!S(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||q==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw _("add",z,"invalid-input","staging requires a reservation and a disabled reason");let F=Z.providerState===void 0?void 0:v0(X.providerState,"add",z,Z.providerState);if(await V.acquire(Z0($,{id:z,identity:B})),G.type==="oauth")await V.acquire(J.providerLock??$.providerLock);for(let U of J.extraLocks??[])await V.acquire(U);return w(X,V,H,{operation:"add",rowId:z},async(U)=>{await J6(U,z,J.protect);let j=S(U.state.accounts)?U.state.accounts:{},K=Object.entries(j).find(([I,f])=>{if(I===z||U.rosterRow(I)||!S(f))return!1;let c=f[g];if(!S(c)||!Object.hasOwn(c,"staged"))return!1;return G.type==="oauth"?f.refresh===G.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===G.apiKey.trim()});if(K)throw _("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw _("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&q!=="rotate"&&(U.rosterRow(z)||A2(U.state,z)))return RJ($,U,Z,F);if(q==="rotate"){U.assertNotStaged(z);let I=U.rows().find((f)=>f.fingerprint===D0(G));if(I)U.assertNotStaged(I.id)}if(q==="refuse"){let I=U.rows().find((c0)=>c0.fingerprint===D0(G)||c0.id===z&&c0.credential),f=S(U.state.accounts)?U.state.accounts:{},c=Object.entries(f).find(([,c0])=>{if(!S(c0))return!1;if(G.type==="oauth")return c0.refresh===G.refresh;return typeof c0.apiKey==="string"&&c0.apiKey.trim()===G.apiKey.trim()})?.[0],x$=I?.id??c??z;if(I||c!==void 0||A2(U.state,z))throw _("add",x$,"credential-exists",`row ${x$} already holds this secret or id`)}if(q==="stage-duplicate"&&(U.rosterRow(z)||A2(U.state,z)))throw _("add",z,"id-exists",`row ${z} already exists`);let N=EJ($,U,Z,F),D=U.rows(),O=D0(G),M=q==="rotate"&&!N&&D.find((I)=>I.invalid===void 0&&I.fingerprint===O);if(M){if(U.assertNotStaged(M.id),r("add",M),B!==void 0&&M.identity!==void 0&&B!==M.identity)throw Z6("add",M.id);let I=e4($,U,M.id,G,{...F!==void 0?{providerState:z4(X.providerState,"add",M.id,M.providerState,F)}:{}});await U.completeTorn(),U.assertNotStaged(M.id);let f=await $6(U,M.id,I);return{id:M.id,outcome:"rotated",credential:f,credentialEpoch:M.credentialEpoch??1}}let P=D.find((I)=>I.id===z);if(P){if(P.invalid)throw _("add",z,"invalid-row",`row ${z} is invalid`);if(P.credential)throw _("add",z,"id-exists",`row ${z} already holds a credential`);if(r("add",P),P.type!==G.type)throw _("add",z,"type-mismatch",`row ${z} is a ${P.type} row`);if(B!==void 0&&P.identity!==void 0&&B!==P.identity)throw Z6("add",z);if(!P.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let I=e4($,U,z,G,{clearErrors:!0,...F!==void 0?{providerState:{kind:"set",value:F}}:{}});await U.completeTorn();let f=await $6(U,z,I);if(!P.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:f,credentialEpoch:P.credentialEpoch??1}}let L=n4(U.config,z);if(!s(L))throw _("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let C=N?.identity??B;U.roster().push(S2({id:z,credential:G,...C!==void 0?{identity:C}:{},...W!==void 0?{label:W}:{},addedAt:X.now()})),U.setEntry(z,{credentialEpoch:L,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let T="added";if(Z.disabled)s0(U,z,Z.disabled.reason),T="added-disabled";if(!Z.disabled&&C!==void 0&&G.type==="oauth"){if(D.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===C))s0(U,z,L1),T="added-disabled"}if(N?.credential)return await U.commitConfig(),{id:z,outcome:T,credential:N.credential,credentialEpoch:N.credentialEpoch??L};U.dropStateAccount(z);let A=e4($,U,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...W!==void 0?{label:W}:{},...F!==void 0?{providerState:z2(F)}:{}}}:{},...F!==void 0?{providerState:{kind:"set",value:F}}:{}});if(q==="rotate")await U.completeTorn();let x=await $6(U,z,A);return await U.commitConfig(),{id:z,outcome:T,credential:x,credentialEpoch:L}},{completeTorn:!1})});if(!Q&&G.type==="oauth"&&(Y.outcome==="added"||Y.outcome==="completed"))$.firePull(Y.id,"add");return Y}async function H3($,Z,J,X={},z={}){a("replace");let{ctx:G}=$,B=await l(G,"replace",Z,z.onFailure,async(W,Q)=>{m1("replace",Z,J),E2("replace",Z,z.attribution);let Y=X.providerState===void 0?void 0:v0(G.providerState,"replace",Z,X.providerState),{row:V}=await M0($,"replace",Z);if(await W.acquire(Z0($,V)),J.type==="oauth")await W.acquire(z.providerLock??$.providerLock);for(let H of z.extraLocks??[])await W.acquire(H);return w(G,W,Q,{operation:"replace",rowId:Z},async(H)=>{if(z.attribution!==void 0)G6("replace",Z,H.row(Z),z.attribution),await H.completeTorn();let q=z6("replace",Z,H.row(Z),J);if(h(q)!==h(V))throw G4("replace",Z);let F=H.entry(Z)?.credentialEpoch,U=(typeof F==="number"?F:1)+1;if(!s(U))throw _("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let j=z3(G.providerState,q,U,X.identity,Y),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(b1(H,Z,U,K),X.identity!==void 0)T2(H,X.identity);let N=await X6($,H,Z,J,{clearErrors:!0,binding:K,providerState:j});return await H.commitConfig(),{id:Z,credential:N,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")$.firePull(Z,"replace");return B}async function U3($,Z,J,X={},z={}){a("rotate");let{ctx:G}=$;return l(G,"rotate",Z,z.onFailure,async(B,W)=>{m1("rotate",Z,J),E2("rotate",Z,z.attribution);let Q=X.providerState===void 0?void 0:v0(G.providerState,"rotate",Z,X.providerState),{row:Y}=await M0($,"rotate",Z);if(await B.acquire(Z0($,Y)),X.identity!==void 0&&J.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await B.acquire(V);return w(G,B,W,{operation:"rotate",rowId:Z},async(V)=>{if(z.attribution!==void 0)G6("rotate",Z,V.row(Z),z.attribution),await V.completeTorn();let H=z6("rotate",Z,V.row(Z),J);if(h(H)!==h(Y))throw G4("rotate",Z);if(r("rotate",H),X.identity!==void 0&&H.identity!==void 0&&X.identity!==H.identity)throw Z6("rotate",Z);let q=X.identity!==void 0&&H.identity===void 0?X.identity:void 0,F=await X6($,V,Z,J,{identity:q,...Q!==void 0?{providerState:z4(G.providerState,"rotate",Z,H.providerState,Q)}:{}}),U=!1;if(!H.hasEntry)V.setEntry(Z,{credentialEpoch:1,needsFirstReading:H.type==="oauth"}),U=!0;if(X.identity!==void 0&&H.identity!==X.identity)J2(V,Z,X.identity),U=!0;if(U)await V.commitConfig();return{id:Z,credential:F}},{completeTorn:z.attribution===void 0})})}async function q3($,Z,J,X,z){a(Z);let{ctx:G}=$,B=G.providerState,W=z.attribution,Q=z.providerState;return l(G,Z,J,z.onFailure,async(Y,V)=>{if(E2(Z,J,W),Q!==void 0){if(typeof Q!=="function")throw _(Z,J,"invalid-input","the provider-state mutator must be a function");if(W===void 0)throw _(Z,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw _(Z,J,"invalid-input","the store was opened without a provider-state codec")}let{row:H}=await M0($,Z,J);await Y.acquire(Z0($,H));for(let q of z.extraLocks??[])await Y.acquire(q);return w(G,Y,V,{operation:Z,rowId:J},async(q)=>{await J6(q,J,z.protect),q.assertNotStaged(J);let F=q.row(J),U=X.enabled?z6("enable",J,F):F;if(!U||!q.rosterRow(J))throw B0(Z,J);if(h(U)!==h(H))throw G4(Z,J);if(W!==void 0)G6(Z,J,U,W);if(X.enabled&&U.disabledReason?.startsWith(C2))throw _("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let j=!X.enabled||!U.enabled||U.disabledReason!==void 0;if(X.enabled&&j&&U.type==="oauth"){let M=U.identity===void 0?void 0:q.rows().find((P)=>P.id!==J&&P.invalid===void 0&&P.type==="oauth"&&P.enabled&&P.identity===U.identity);if(M)throw _("enable",J,"duplicate-identity",`row ${M.id} is enabled with the same identity as row ${J}`)}if(Q===void 0||B===void 0){if(await q.completeTorn(),!j)return{id:J};if(X.enabled)r2(q,J);else s0(q,J,X.reason);return await q.commitConfig(),{id:J}}if(!U.credential)throw _(Z,J,"no-credential",`row ${J} holds no credential`);r(Z,U);let K=await v1(q,B,Z,U,Q,!0);if(K.kind==="declined")return{id:J,declined:!0};await q.completeTorn();let N={id:J,providerStateOutcome:K.kind==="unchanged"?"unchanged":K.value===void 0?"cleared":"updated",...K.value!==void 0?{providerState:K.value}:{}};if(K.kind==="unchanged"){if(j){if(X.enabled)r2(q,J);else s0(q,J,X.reason);await q.commitConfig()}return N}if(!j)return q.setStateAccount(J,K.account),await q.commitState(),N;let D=X.enabled?{mark:W3(),enabled:!0}:{mark:W3(),enabled:!1,reason:X.reason},O=K.account[g];return q.setStateAccount(J,{...K.account,[g]:{...O,[i4]:D}}),await q.commitState(),Z4(q,J,D),await q.commitConfig(),N},{completeTorn:!1})})}function j3($,Z,J,X={}){return q3($,"disable",Z,{enabled:!1,reason:J},X)}function F3($,Z,J={}){return q3($,"enable",Z,{enabled:!0},J)}async function K3($,Z,J={}){a("remove");let{ctx:X}=$;return l(X,"remove",Z,J.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw _("remove",Z,"invalid-input","id must be non-empty");let B=J.attribution;if(E2("remove",Z,B),J.staged!==void 0&&(!S(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw _("remove",Z,"invalid-input","a staged removal needs a reservation");let W=await n(X);if(W.status!=="ready")throw $0(W,"remove",Z);let Q=W.rows.find((V)=>V.id===Z);if(!Q&&!A2(W.state,Z))throw B0("remove",Z);let Y=h(Q??{id:Z});await z.acquire(Z0($,Q??{id:Z}));for(let V of J.extraLocks??[])await z.acquire(V);return w(X,z,G,{operation:"remove",rowId:Z},async(V)=>{let H=V.reservation(Z);if(H!==void 0){if(!S(H)||!J.staged||H.reservation!==J.staged.reservation)throw _("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(J.staged)throw _("remove",Z,"attribution",`row ${Z} is no longer reserved`);let q=V.row(Z),F=A2(V.state,Z);if(!q&&!F)throw B0("remove",Z);if(h(q??{id:Z})!==Y)throw G4("remove",Z);if(B!==void 0)if(q)B6(Z,q,B);else IJ($,V,Z,B);let U=J.protect;if(U){let j={row:q,config:V.snapshot.config,state:V.snapshot.state},K=await G0("remove",()=>U(Z,j));if(K!==void 0)throw _("remove",Z,"row-protected",K)}if(q){if(B===void 0)await V.completeTorn();V.dropRosterRows(Z),await V.commitConfig()}if(F)V.dropStateAccount(Z),await V.commitState();return{id:Z,outcome:q?"removed":"completed"}},{completeTorn:!1})})}function B6($,Z,J,X="remove"){if(G6(X,$,Z,J),Z.torn)throw _(X,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw _(X,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function IJ($,Z,J,X){let z=()=>_("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=Z.stateAccount(J),B=t(G?.[g]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let W;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();W={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")W={type:"oauth",refresh:G.refresh};else throw z();let[Q]=n0({accounts:[S2({id:J,credential:W,identity:B.binding.identity,addedAt:0})],[v]:{rows:{[J]:{credentialEpoch:B.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!Q?.credential||Q.invalid||Q.stamp!=="bound")throw z();if(B.credentialEpoch!==X.credentialEpoch||B.binding.identity!==X.identity)throw _("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function A2($,Z){let J=$.accounts;return S(J)&&Object.hasOwn(J,Z)}function h1($){return S($)&&typeof $.id==="string"?$.id:void 0}function bJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let J=new Set;for(let G of $){let B=h1(G);if(B!==void 0)J.add(B)}let X=new Set;for(let G of Z){if(typeof G!=="string")return"ids must be an array of roster ids";if(X.has(G))return`id ${G} appears more than once`;if(!J.has(G))return`id ${G} is not in the roster`;X.add(G)}let z=[...J].filter((G)=>!X.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function kJ($,Z){let J=new Map;for(let G of $){let B=h1(G);if(B===void 0)continue;let W=J.get(B);if(W)W.push(G);else J.set(B,[G])}let X=Z.flatMap((G)=>J.get(G)??[]),z=0;return $.map((G)=>h1(G)===void 0?G:X[z++])}async function N3($,Z,J={}){a("reorder");let{ctx:X}=$,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let W of J.extraLocks??[])await G.acquire(W);return w(X,G,B,{operation:"reorder",rowId:void 0},async(W)=>{let Q=W.roster(),Y=bJ(Q,Z);if(Y)throw new b({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Y});let V=[...Z],H=kJ(Q,V);if(H.every((q,F)=>q===Q[F]))return{ids:V,outcome:"unchanged"};return W.config.accounts=H,await W.commitConfig(),{ids:V,outcome:"reordered"}},{completeTorn:!1})})}async function D3($,Z,J,X,z={}){return a("recordIdentity"),l($.ctx,"recordIdentity",Z,z.onFailure,async(G,B)=>{if(typeof J!=="string"||J.length===0)throw _("recordIdentity",Z,"invalid-input","identity must be non-empty");let W=S(X)?X.credentialEpoch:void 0;if(!s(W))throw _("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Q}=await M0($,"recordIdentity",Z);await G.acquire(Z0($,Q)),await G.acquire(z.providerLock??$.providerLock);for(let Y of z.extraLocks??[])await G.acquire(Y);return w($.ctx,G,B,{operation:"recordIdentity",rowId:Z},async(Y)=>{let V=z6("recordIdentity",Z,Y.row(Z));if(h(V)!==h(Q))throw G4("recordIdentity",Z);if(r("recordIdentity",V),(V.credentialEpoch??1)!==W)throw _("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(V.identity!==void 0&&V.identity!==J)throw Z6("recordIdentity",Z);if(V.identity===void 0)await AJ(Y,V,J);let H=J2(Y,Z,J);return await Y.commitConfig(),{id:Z,disabled:H}})})}function M3($){let Z=$[v];return S(Z)&&S(Z.publications)?Z.publications:{}}function C3($,Z){let J=M3($);if(!Object.hasOwn(J,Z))return;let X=J[Z];if(!S(X)||X.operationId!==Z||typeof X.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(X.planDigest)||!["committed","cleaned"].includes(String(X.phase))||!Array.isArray(X.removed)||!Array.isArray(X.finalized)||X.removed.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch))||X.finalized.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw _("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function T3($,Z){let J=await n($.ctx);if(J.status!=="ready")throw $0(J,"publishRoster",Z);return C3(J.config,Z)}function xJ($,Z){let J=()=>{throw _("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId||!Array.isArray(Z.remove)||!Array.isArray(Z.finalize)||!Array.isArray(Z.order))J();let X=new Set;for(let z of[...Z.remove,...Z.finalize]){if(!S(z)||typeof z.id!=="string"||L2(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),E2("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of Z.remove)if($.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();for(let z of Z.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))J();if(Z.order.some((z)=>typeof z!=="string"||L2(z))||new Set(Z.order).size!==Z.order.length)J()}function L3($,Z){$.entries();let J=$.config[v],X={...M3($.config)};Object.defineProperty(X,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function yJ($,Z,J){let X=new Set;for(let B of O2($.config)){if(!S(B)||typeof B.id!=="string")continue;if(X.has(B.id))throw _("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(B.id)}let z=new Set(Z.remove.map((B)=>B.id)),G=J.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==Z.order.length||Z.order.some((B)=>!G.some((W)=>W.id===B))||G.some((B)=>!Z.order.includes(B.id)))throw _("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function P3($,Z){await $.assertAll();for(let X of Z.removed)if(t($.stateAccount(X.id)?.[g])?.credentialEpoch===X.credentialEpoch&&!$.rosterRow(X.id))$.dropStateAccount(X.id);for(let X of Z.finalized){let z=$.stateAccount(X.id),G=t(z?.[g]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let B={...z[g]};delete B.staged,$.setStateAccount(X.id,{...z,[g]:B})}}await $.commitState(void 0,{durable:!0});let J={...Z,phase:"cleaned"};return L3($,J),await $.commitConfig({durable:!0}),J}async function _3($,Z,J={}){return a("publishRoster"),l($.ctx,"publishRoster",Z?.operationId??"",J.onFailure,async(X,z)=>{if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw _("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=z2(Z),B=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((W)=>S(W)&&typeof W.id==="string");for(let W=0;;W++){let Q=await n($.ctx);if(Q.status!=="ready")throw $0(Q,"publishRoster",Z.operationId);let Y=new Map(B.map(({id:H})=>[H,h(Q.rows.find((q)=>q.id===H)??{id:H})]));for(let H of[...new Set(Y.values())].sort())await X.acquire(Z0($,{id:H}));await X.acquire(J.providerLock??$.providerLock);for(let H of J.extraLocks??[])await X.acquire(H);let V=await w($.ctx,X,z,{operation:"publishRoster",rowId:Z.operationId},async(H)=>{let q=H.rows();if(B.some(({id:P})=>h(q.find((L)=>L.id===P)??{id:P})!==Y.get(P)))return;let F=C3(H.config,Z.operationId);if(F){if(F.planDigest!==G)throw _("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(F.phase==="cleaned")return{outcome:"already-cleaned",receipt:F};return H.markPublicationDecision(),await H.syncConfig(),{outcome:"cleaned",receipt:await P3(H,F)}}xJ($,Z);let U=yJ(H,Z,q),j=[];for(let P of Z.remove){H.assertNotStaged(P.id);let L=q.find((C)=>C.id===P.id);if(!L)throw _("publishRoster",P.id,"attribution","the removed row no longer exists");if(B6(P.id,L,P.attribution,"publishRoster"),!L.credential||P.fingerprint!==void 0&&D0(L.credential)!==P.fingerprint)throw _("publishRoster",P.id,"attribution","the removed secret no longer matches");j.push(L)}let K=[];for(let P of Z.finalize){let L=q.find((f)=>f.id===P.id),C=t(H.stateAccount(P.id)?.[g]);if(!L||L.staged?.reservation!==P.reservation||C?.staged?.reservation!==P.reservation||L.enabled)throw _("publishRoster",P.id,"row-staged","the finalized row is not disabled under this reservation");let T=H.stateAccount(P.id),A=H.rosterRow(P.id),x=T?.[i],I=x===void 0?void 0:z2(x);if(!C?.staged||C.staged.label!==A?.label||C.staged.disabledReason!==L.disabledReason||C.staged.providerState!==I)throw _("publishRoster",P.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");B6(P.id,L,P.attribution,"publishRoster"),K.push(L)}let N=U.find((P)=>P.torn);if(N)throw _("publishRoster",Z.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let D=new Set;for(let P of U){if(!(Z.finalize.find((C)=>C.id===P.id)?.enabled??P.enabled)||P.type!=="oauth"||P.identity===void 0)continue;if(D.has(P.identity))throw _("publishRoster",P.id,"invalid-input","the final enabled roster repeats a known identity");D.add(P.identity)}for(let P of U)if(P.identity!==void 0&&P.fingerprint!==void 0&&U.some((L)=>L.id!==P.id&&L.identity!==void 0&&L.identity!==P.identity&&L.fingerprint===P.fingerprint))throw _("publishRoster",P.id,"attribution","the resulting pool gives the same secret different known identities");for(let P of K)if(P.identity!==void 0&&j.some((L)=>L.identity!==void 0&&L.identity!==P.identity&&L.fingerprint===P.fingerprint))throw _("publishRoster",P.id,"attribution","the staged secret belonged to a different known identity");await J6(H,Z.operationId,J.protect);let O={operationId:Z.operationId,planDigest:G,phase:"committed",removed:j.map((P)=>({id:P.id,credentialEpoch:P.credentialEpoch??1})),finalized:Z.finalize.map((P,L)=>({id:P.id,credentialEpoch:K[L]?.credentialEpoch??1,reservation:P.reservation,enabled:P.enabled}))};for(let P of Z.remove)H.dropRosterRows(P.id);for(let P of Z.finalize){let L=H.rosterRow(P.id);L.enabled=P.enabled;let C={...H.entry(P.id)};if(delete C.staged,P.enabled)delete C.disabledReason;else C.disabledReason=P.disabledReason;H.setEntry(P.id,C)}let M=H.roster().filter((P)=>!S(P)||typeof P.id!=="string"||q.find((L)=>L.id===P.id)?.invalid==="roster");return H.config.accounts=[...Z.order.map((P)=>H.rosterRow(P)),...M],L3(H,O),await H.syncState(),await H.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await P3(H,O)}},{completeTorn:!1});if(V)return V;if(await X.releaseAll(),W>=1)throw _("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class w1{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,J,X,z){this.rt=$,this.hook=Z,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire($,Z){if(!this.hook)return;if(Z==="load"){if(this.firedAtLoad.has($))return;this.firedAtLoad.add($)}let J=this.run($,Z);this.inflight.add(J),J.finally(()=>this.inflight.delete(J))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run($,Z){let J=this.rt(),{ctx:X}=J,z=new A0(X.lockDefaults,X.lockEnv),G={writes:0};try{let B=await w(X,z,G,{operation:"pull",rowId:$},async(Y)=>{if(Y.reservation($)!==void 0)return;await Y.completeTorn();let V=Y.row($);if(V?.unbound&&V.enabled&&V.type==="oauth"&&V.credential&&!V.invalid)r("pull",V);if(!V?.candidate||V.type!=="oauth")return;if(!V.hasEntry)Y.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await Y.commitConfig();let H=Y.row($);if(!H?.credential||H.credentialEpoch===void 0)return;return{id:$,credential:H.credential,credentialEpoch:H.credentialEpoch,...H.identity!==void 0?{identity:H.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete($);return}await X.hold?.("pull-before-request",$);let W;try{W=await this.hook?.(B)}catch(Y){throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Y})}await(J.publishQuota??((Y,V,H)=>t4(J,Y,V,H)))($,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},W)}catch(B){this.firedAtLoad.delete($);let W=i0(B,"pull",$,G);if(this.onFailure)try{await this.onFailure($,W)}catch(Q){this.logger?.warn("pull failure hook threw",{rowId:$,error:Q instanceof Error?Q.message:String(Q)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:W.kind})}finally{await z.releaseAll()}}}var O3=100,Q6=128;class u1{rt;timeoutMs;clock;pending=new Map;warned=new Set;wake=new Set;logger;timer;committedAt;running;closing;closed=!1;stopped=!1;failures=0;constructor($,Z=1000,J=A3){this.rt=$,this.timeoutMs=Z,this.clock=J,this.logger=$.ctx.logger??o("store")}async record($,Z,J){try{this.assertOpen($),f1($,Z);let X=structuredClone({id:$,attribution:Z,observation:J}),{row:z,result:G}=await M0(this.rt,"pull",$);J4($,X.attribution,z),X4(this.rt.ctx,$,this.overlayRow({...z,quota:R0(G.config,$)?.quota}).quota,X.observation),await this.room($),this.assertOpen($);let B=this.pending.get($)??[];if(B.push(X),this.pending.set($,B),B.length>=Q6)this.flushNow();else this.schedule(O3)}catch(X){throw i0(X,"pull",$,{writes:0})}}queued($){return this.pending.get($)?.length??0}async room($){if(this.queued($)<Q6)return;let{ctx:Z}=this.rt,J=Math.max(0,...Z.storeLocks.map((z)=>z.timeoutMs??Z.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued($)>=Q6){this.assertOpen($),this.flushNow();let z=X-performance.now();if(z<=0)throw _("pull",$,"lock-contention",`pool quota queue for ${$} is full (${Q6} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let B=()=>{clearTimeout(W),this.wake.delete(B),G()},W=setTimeout(B,z);this.wake.add(B)})}}assertOpen($){if(this.closed)throw _("pull",$,"invalid-input","pool quota writer is closed")}overlayRow($){let Z=$;for(let J of this.pending.get($.id)??[])try{J4($.id,J.attribution,$),Z={...Z,quota:X4(this.rt.ctx,$.id,Z.quota,J.observation),needsFirstReading:!1}}catch{}return Z}overlay($){return $.map((Z)=>this.overlayRow(Z))}schedule($){if(this.running||this.timer||!this.pending.size||this.stopped)return;let Z=this.closed?0:(this.committedAt??-1/0)+S3-this.clock.now();if(this.timer=this.clock.schedule(Math.max($,Z),()=>{return this.timer=void 0,this.flush()}),!this.closed)this.timer.unref?.()}cancelTimer(){this.timer?.cancel(),this.timer=void 0}flushNow(){if(this.running)return;this.cancelTimer(),this.flush()}flush(){if(this.running||this.stopped||!this.pending.size)return this.running??Promise.resolve();let $=[...this.pending.values()].flat(),Z={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new A0(Z.lockDefaults,Z.lockEnv);return this.running=(async()=>{try{await w(Z,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let B of $){let{id:W,attribution:Q,observation:Y}=B,V=JSON.stringify([W,Q.credentialEpoch,Q.identity]);try{z.assertNotStaged(W),J4(W,Q,z.row(W))}catch(F){if(!(F instanceof b))throw F;if(!this.warned.has(V))this.warned.add(V),this.warn("pool quota publication dropped; account binding changed",{id:W,kind:F.kind});continue}let H=z.entry(W);if(!H)continue;let q;try{q=X4(Z,W,H.quota,Y)}catch(F){let U=`codec:${V}`;if(!this.warned.has(U))this.warned.add(U),this.warn("pool quota publication dropped; the quota codec refused it",{id:W,error:F instanceof Error?F.message:String(F)});continue}z.setEntry(W,{...H,quota:q,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set($);for(let[z,G]of this.pending){let B=G.filter((W)=>!X.has(W));if(B.length)this.pending.set(z,B);else this.pending.delete(z)}this.failures=0}catch(X){if(!this.stopped&&this.failures++===0)this.warn("pool quota publication delayed; retrying",{error:X instanceof Error?X.message:String(X)})}finally{await J.releaseAll(),this.running=void 0;for(let z of this.wake)z();let X=this.failures?Math.min(5000,100*2**Math.min(this.failures,6))*(0.5+Math.random()):O3;this.schedule(X)}})(),this.running}warn($,Z){try{this.logger.warn($,Z)}catch{}}close(){if(this.closing)return this.closing;return this.closed=!0,this.closing=this.drain(),this.closing}async drain(){this.cancelTimer();let $,Z,J=new Promise((X)=>{Z=()=>{if(!this.pending.size)X()},this.wake.add(Z),Z()});try{this.flush(),await Promise.race([J,new Promise((X)=>{$=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout($),this.cancelTimer(),this.wake.delete(Z),this.pending.size)this.warn("pool quota drain timed out; pending readings left",{accounts:this.pending.size,readings:[...this.pending.values()].reduce((X,z)=>X+z.length,0)});this.pending.clear();for(let X of this.wake)X()}}}import{randomUUID as gJ}from"node:crypto";function p1($,Z){if(X2("refresh",$,Z?.staged),!Z)throw _("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw _("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw _("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw _("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function E3($){return _("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function R3($,Z,J,X={}){a("refresh");let{ctx:z}=$;return l(z,"refresh",Z,X.onFailure,async(G,B)=>{let{row:W}=await M0($,"refresh",Z);p1(Z,W);let Q=await X.refuse?.(W);if(Q!==void 0)return{status:"refused",rowId:Z,reason:Q};let Y=h(W),V;for(let U=0;;U++){await G.acquire(Z0($,{id:Z,identity:Y===Z?void 0:Y})),await G.acquire(X.providerLock??$.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await w(z,G,{writes:0},{operation:"refresh",rowId:Z},async(N)=>{let D=p1(Z,N.row(Z));if(r("refresh",D),!D.hasEntry)N.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),D=p1(Z,N.row(Z));if(h(D)!==Y)return{keyNow:h(D)};let O=await X.refuse?.(D);if(O!==void 0)return{refused:O};return{row:D,credential:D.credential,credentialEpoch:D.credentialEpoch,identity:D.identity}});if("refused"in K)return{status:"refused",rowId:Z,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),U>=1)throw _("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);Y=K.keyNow;continue}V=K;break}if(I1(V.credential.lastRefreshedAt,z.now()))throw E3(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let H;try{H=await J(V.credential,V.row)}catch(U){throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof H?.refresh!=="string"||!H.refresh.trim())throw _("refresh",Z,"provider","the provider returned no refresh token",!0);let q=H.providerState===void 0?void 0:v0(z.providerState,"refresh",Z,H.providerState,"the provider state the provider returned"),F=await w(z,G,B,{operation:"refresh",rowId:Z},async(U)=>{let j=U.row(Z),K=U.entry(Z);if(!j||j.invalid||!K||K.credentialEpoch!==V.credentialEpoch||j.identity!==V.identity)throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${Z} changed credential while its refresh was in flight; the rotation is discarded`});r("refresh",j);let N=await X.refuse?.(j);if(N!==void 0)return{refused:N};let D=z.now(),O=j.credential?.type==="oauth"?j.credential.lastRefreshedAt:void 0;if(I1(O,D))throw E3(Z);let M={type:"oauth",access:H.access,refresh:H.refresh,expires:H.expires},P=j.identity!==void 0&&H.identity!==void 0&&j.identity!==H.identity?{expectedIdentity:j.identity,returnedIdentity:H.identity}:void 0,L=P?{mark:gJ(),enabled:!1,reason:`${C2}${JSON.stringify(P)}`}:void 0,C=j.identity===void 0&&H.identity?H.identity:void 0,T=await X6($,U,Z,M,{stamp:$4(O,D),transition:L,identity:C,...q!==void 0?{providerState:z4(z.providerState,"refresh",Z,j.providerState,q)}:{}});if(L!==void 0)Z4(U,Z,L),await U.commitConfig();let A=j.identity;if(C!==void 0)J2(U,Z,C),A=C,await U.commitConfig();return{stored:T,identity:A,contradiction:P,refused:void 0}});if(F.refused!==void 0)return{status:"refused",rowId:Z,reason:F.refused};if(F.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...F.contradiction,credential:F.stored};if(X.onPersisted)try{let U=X.onPersisted;await G0("refresh",()=>U(Z,F.stored),!0)}catch(U){throw new b({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:F.stored,message:"the after-persist hook threw; the rotation stays committed",cause:U})}return{status:"rotated",rowId:Z,credential:F.stored,...F.identity!==void 0?{identity:F.identity}:{}}})}import{isDeepStrictEqual as I3}from"node:util";var V6=Object.freeze(["version","accounts",v]);function W6($){let Z={};for(let[J,X]of Object.entries($))if(!V6.includes(J))Y6(Z,J,X);return Z}function Y6($,Z,J){Object.defineProperty($,Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function fJ($,Z){let J={};for(let[X,z]of Object.entries($))if(V6.includes(X)||X==="commonAuthLimits")Y6(J,X,z);else if(Object.hasOwn(Z,X))Y6(J,X,Z[X]);for(let[X,z]of Object.entries(Z))if(!Object.hasOwn($,X))Y6(J,X,z);return J}function l1($){return new b({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}var vJ=new b3;async function k3($){let Z=async([X=$.ctx.configPath]=[])=>{let z=await $3(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:W6(z.config)}},J=o4?await Z():await vJ.read([$.ctx.configPath],Z);return structuredClone(J)}async function x3($,Z,J={}){a("updateSettings");let{ctx:X}=$,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Q of J.extraLocks??[])await G.acquire(Q);let W=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let Q=await n(X);if(Q.status!=="ready")throw $0(Q,"updateSettings",void 0);let Y=W6(Q.config),V=structuredClone(Y),H=await G0("updateSettings",()=>Z(V)),q=H===void 0?V:H;if(!S(q))throw l1("the settings mutator must produce an object");let F=V6.filter((K)=>Object.hasOwn(q,K));if(F.length>0)throw l1(`settings cannot set the pool-owned key(s) ${F.join(", ")}`);if(Object.hasOwn(q,"commonAuthLimits")&&(!Object.hasOwn(Y,"commonAuthLimits")||!I3(q.commonAuthLimits,Y.commonAuthLimits)))throw l1("settings cannot alter commonAuthLimits; use updateLimitsNamespace");let U=fJ(Q.config,q);if(I3(W6(U),Y))return{settings:Y,outcome:"unchanged"};let j={operation:"updateSettings",rowId:void 0};return await P0(X.configPath,U,{beforeRename:async()=>{await X.onStep?.("before-config-write",j),await G.assertAll()}}),B.writes++,await X.onStep?.("after-config-write",j),{settings:W6(U),outcome:"updated"}}finally{await G.releaseTo(W)}})}var y3=new Map;function hJ($){let Z=y3.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},y3.set($,Z);return Z}function g3($){if($.status==="ready")return{status:"ready",schemaVersion:a0,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function B4($){let Z=hJ($.configPath),J={..._1,...$.lockOptions},X={provider:$.provider,configPath:$.configPath,statePath:$.statePath,codec:$.quota,...$.providerState?{providerState:$.providerState}:{},now:$.now??Date.now,storeLocks:$.storeLocks??[{name:"save",path:$.configPath},{name:"save",path:$.statePath}],lockDefaults:J,lockEnv:{...$.onLockEvent?{onLockEvent:$.onLockEvent}:{},...$.onLockStep?{onLockStep:$.onLockStep}:{},...$.onRenewalTimer?{onRenewalTimer:$.onRenewalTimer}:{}},removedIds:Z.removedIds,requireCredentialStamps:$.requireCredentialStamps===!0,requireRemovedFingerprint:$.requireRemovedFingerprint===!0,...$.logger?{logger:$.logger}:{},...$.onStep?{onStep:$.onStep}:{},...$.hold?{hold:$.hold}:{}},z=new w1(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:X,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(Y,V)=>z.fire(Y,V)},B=$.coalesceQuota?new u1(G,$.quotaDrainTimeoutMs,$.quotaCommitTimer):void 0,W=(Y,V,H)=>B?B.record(Y,V,H):t4(G,Y,V,H);G.publishQuota=W;let Q=(Y)=>{if(Y.status==="ready"&&B)return{...Y,rows:B.overlay(Y.rows)};return Y};return{async load(){let Y=Q(await n(X));if(Y.status==="ready"){for(let V of Y.rows)if((V.candidate||V.torn&&V.enabled)&&V.type==="oauth"&&V.needsFirstReading)z.fire(V.id,"load")}return g3(Y)},async read(){return g3(Q(await n(X)))},async initialize(Y={}){return{status:await J3(X,Y.dropKeys??[])}},add:(Y,V)=>V3(G,Y,V),publishRoster:(Y,V)=>_3(G,Y,V),publication:(Y)=>T3(G,Y),replace:(Y,V,H,q)=>H3(G,Y,V,H,q),rotate:(Y,V,H,q)=>U3(G,Y,V,H,q),updateProviderState:(Y,V,H,q)=>B3(G,Y,V,H,q),disable:(Y,V,H)=>j3(G,Y,V,H),enable:(Y,V)=>F3(G,Y,V),remove:(Y,V)=>K3(G,Y,V),reorder:(Y,V)=>N3(G,Y,V),readSettings:()=>k3(G),updateSettings:(Y,V)=>x3(G,Y,V),updateLimitsNamespace:(Y,V)=>X3(G,Y,V),recordIdentity:(Y,V,H,q)=>D3(G,Y,V,H,q),refresh:(Y,V,H)=>R3(G,Y,V,H),recordQuota:W,close:()=>B?.close()??Promise.resolve(),dispose:()=>B?.close()??Promise.resolve(),requestReading:(Y)=>z.fire(Y,"admission"),pullsSettled:()=>z.settled()}}var mJ=[/\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 s1($={}){let{redactStrings:Z}=f3({...$,extraValuePatterns:[...mJ,...$.extraValuePatterns??[]]});return(J)=>Z(J)}class u extends Error{code;constructor($,Z,J){super(Z,J);this.name="CommandError",this.code=$}}var v3=/^[a-z][a-z0-9-]{0,63}$/,d1={code:"action-failed",text:"That action failed."},wJ=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 Q4($){if($ instanceof u)return{code:v3.test($.code)?$.code:d1.code,text:$.message};if($ instanceof b)return{code:`pool-${$.kind}`,text:wJ.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return d1}var h3="This cannot be undone. Continue?",uJ=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function pJ($){let Z=$.toLowerCase().replace(/[-_]/g,"");return uJ.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function lJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function c1($,Z,J){if(typeof $==="string"){let z=J.redact($);if(z!==$)J.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>c1(z,`${Z}[${G}]`,J));if(!lJ($))return $;let X={};for(let[z,G]of Object.entries($)){if(pJ(z)){J.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(X,z,{value:c1(G,`${Z}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function m3($,Z,J){let X={redact:J.redact,dropped:[],redacted:[]},z=c1($,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:Z,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:Z,fields:X.redacted});return z}function dJ($){return{value:String($.value),label:String($.label)}}function cJ($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(dJ),...$.value!==void 0?{value:$.value}:{}};case"toggle":return{kind:"toggle",id:$.id,label:$.label,value:$.value===!0};case"number":return{kind:"number",id:$.id,label:$.label,...$.value!==void 0?{value:$.value}:{},...$.min!==void 0?{min:$.min}:{},...$.max!==void 0?{max:$.max}:{},...$.required?{required:!0}:{}};case"text":return{kind:"text",id:$.id,label:$.label,...$.value!==void 0&&!$.masked?{value:$.value}:{},...$.placeholder!==void 0?{placeholder:$.placeholder}:{},...$.masked?{masked:!0}:{},...$.required?{required:!0}:{}}}}function a1($){if($.irreversible===!0)return{message:$.confirm||h3,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function w3($){let Z=a1($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(cJ),...Z?{confirm:Z}:{}}}function sJ($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function aJ($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:sJ($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(w3)}}function nJ($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(aJ),actions:(Z.actions??[]).map(w3),...Z.facts!==void 0?{facts:Z.facts}:{}}}function u3($,Z,J){return{command:$,title:Z,sections:J.map(nJ)}}function p3($,Z,J,X){return m3({command:$,menu:u3($,Z,J)},$,X)}function l3($,Z,J,X,z){return m3({command:$,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:v3.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:u3($,Z,J)},$,z)}var r3="disabled from the command menu";function iJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function C0($){return iJ($)?{...$}:{}}function rJ($){if($.status!=="ready")return[];let Z=new Set;return $.rows.filter((J)=>{if(Z.has(J.id))return!1;return Z.add(J.id),!0})}function oJ($,Z){return $.label??Z??$.id}function H6($,Z){return r0($.quota)?b0($.quota,Z):void 0}function o3($,Z){return`${$} ${Z}${$===1?"":"s"}`}var R2="Actions";function tJ($){if($.status==="pending-migration")return"The account pool has not been migrated yet.";if($.status==="error")return`The ${$.file} file cannot be read: ${$.reason}`;return}function d3($,Z){switch(Z.outcome){case"added":return`Added ${$}.`;case"added-disabled":return`Added ${$}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${$}.`;case"rotated":return`${$} was already in the pool; its credential was updated.`;case"exists":return`${$} was already in the pool; its credential is unchanged.`}}function c3($){return Q4($).text}async function eJ($){let{store:Z}=$,J=await Z.read(),X=await Z.readSettings(),z=await $.routing?.vaultOrder?.();return{load:J,rows:rJ(J),settings:X.status==="error"?{}:X.settings,...z?{vault:z}:{}}}function U6($,Z){let J=Z.accounts?.describeIdentity?Z.accounts.describeIdentity($):$.identity;return{account:{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...J!==void 0?{identity:J}:{}},name:oJ($,J)}}function $X($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=Z.rows.map((H)=>H.id),B=tJ(Z.load),W=Z.rows.filter((H)=>H.enabled).length,Q=Z.rows.map((H,q)=>{let{account:F,name:U}=U6(H,$),j=[H.type==="api"?"API key":"OAuth",...F.identity!==void 0?[F.identity]:[],...!H.invalid&&!H.enabled&&H.disabledReason?[`disabled: ${H.disabledReason}`]:[]].join(" · "),K=H.invalid?"invalid":H.enabled?"enabled":"disabled",N=[];if(!H.invalid&&H.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(H.id,r3,z),`Disabled ${U}.`}});if(!H.invalid&&!H.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(H.id,z),`Enabled ${U}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((D,O)=>({value:String(O+1),label:String(O+1)})),value:String(q+1)}],run:async({values:D})=>{let O=Number(D.position),M=G.filter((L)=>L!==H.id);return M.splice(O-1,0,H.id),(await J.reorder(M,z)).outcome==="unchanged"?`${U} is already at position ${O}.`:`Moved ${U} to position ${O}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await J.remove(H.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${U}.`}}),{id:H.id,label:U,detail:j,group:"Accounts",status:K,account:F,actions:N}}),Y=$.accounts?.login,V=[];if(Y&&!B)V.push({id:"add",label:Y.label??"Add account",group:R2,knobs:Y.knobs??[],run:async({values:H,invocation:q})=>{let F=await Y.run(H,q);if(F.status==="cancelled")return{ok:!1,text:F.message??"Login cancelled."};if(F.status==="ready"){let U=await J.add(F.account,z);return d3(F.account.label??U.id,U)}return F.completion.then(async(U)=>{if(!U){q.notify("Login cancelled.","warning");return}let j=await J.add(U,z);q.notify(d3(U.label??j.id,j))},(U)=>{q.notify(`Adding the account failed: ${c3(U)}`,"error")}).catch((U)=>{q.notify(`Adding the account failed: ${c3(U)}`,"error")}),F.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[Z.rows.length===0?"No accounts yet":`${o3(Z.rows.length,"account")}, ${W} enabled`],items:B?[]:Q,actions:V}}}function ZX($,Z){let J=$.quota?.scope??"all",X=$.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(V,H)=>{if($.quota?.check)await $.quota.check(V,H);else{for(let q of V)$.store.requestReading(q);await $.store.pullsSettled()}},B=Z.rows.filter((V)=>V.candidate),W=B.map((V)=>{let{account:H,name:q}=U6(V,$),F=H6(V,J);return{id:V.id,label:q,group:z,status:I0(F,{now:X,form:"compact"}),detail:I0(F,{now:X,form:"full"}),account:H,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([V.id],U),`Checked quota for ${q}.`}}]}}),Q=Z.rows.filter((V)=>!V.candidate).map((V)=>{let{name:H}=U6(V,$),q=V.invalid?"invalid":!V.enabled?"disabled":V.credential===void 0?"no credential":"unavailable",F=I0(H6(V,J),{now:X,form:"compact"});return`${H} (${q}): ${F}`}),Y=[];if(B.length>0)Y.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:R2,run:async({invocation:V})=>{let H=B.map((q)=>q.id);return await G(H,V),`Checked quota for ${o3(H.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Q,items:W,actions:Y}}}async function JX($,Z){try{return await $.reorder(Z)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new u("vault-invalid-order",J.message,{cause:J});throw J}}function n1($){return new u("vault-invalid-order",$)}function XX($){let Z=$.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>Z.filter((z)=>z.id===X||z.label===X);return{ids:Z.map((X)=>X.id),nameOf:(X)=>Z.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let z=Z.find((G)=>G.id===X);return z&&!/[,\n]/.test(z.label)&&J(z.label).length===1?z.label:X},resolve:(X)=>{let z=[];for(let G of X){let B=J(G);if(B.length===0)throw n1(`"${G}" is not a vault account.`);if(B.length>1)throw n1(`"${G}" matches more than one vault account; enter those accounts by route id.`);let W=B[0].id;if(z.includes(W))throw n1(`"${G}" names an account already in the order.`);z.push(W)}return z}}}function zX($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=C0(Z.settings.routing).mode,W=typeof B==="string"&&G.some((K)=>K.value===B)?B:"ordered",Q=n3(W),Y=Z.vault?XX(Z.vault):void 0,V=Y?Y.ids:Z.rows.map((K)=>K.id),H=(K)=>Y?Y.nameOf(K):K,q=i3(V,Q.placement,$.routing?.formerMainId??a3),U=[`Mode: ${G.find((K)=>K.value===W)?.label??W}`];if(V.length>0)U.push(`${Y?"Vault account order":"Roster order"}: ${V.map(H).join(", ")}`);if(Q.mode==="ordered"&&q.join()!==V.join())U.push(`Tried in order: ${q.map(H).join(", ")}`);let j=[{id:"mode",label:"Change mode",group:R2,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:W}],run:async({values:K})=>{let N=String(K.mode);return await J.updateSettings((D)=>{D.routing={...C0(D.routing),mode:N};return},z),`Routing mode set to ${G.find((D)=>D.value===N)?.label??N}.`}}];if(V.length>1)j.push({id:"order",label:"Set order",group:R2,knobs:[{kind:"text",id:"order",label:Y?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:Y?V.map(Y.entryOf).join(", "):V.join(", "),required:!0}],run:async({values:K})=>{let D=String(K.order).split(Y?/[,\n]+/:/[\s,]+/).map((M)=>M.trim()).filter((M)=>M.length>0),O=Z.vault&&Y?await JX(Z.vault,Y.resolve(D)):await J.reorder(D,z);return O.outcome==="unchanged"?"The order is unchanged.":`Order set to ${O.ids.map(H).join(", ")}.`}});if($.routing?.sameAccountWait){let N=[{value:"0",label:"Don't wait"},{value:"15",label:"15 minutes"},{value:"max",label:"Until the cache expires"}],D=C0(Z.settings.routing).maxSameAccountWait,O=String(D===0||D==="max"?D:15),M=(P)=>N.find((L)=>L.value===P)?.label??P;U.push(`Longest wait on the same account: ${M(O)}`),j.push({id:"maxSameAccountWait",label:"Longest wait on the same account",group:R2,knobs:[{kind:"choice",id:"maxSameAccountWait",label:"Longest wait on the same account",choices:N,value:O}],run:async({values:P})=>{let L=String(P.maxSameAccountWait),C=L==="max"?"max":Number(L);return await J.updateSettings((T)=>{T.routing={...C0(T.routing),maxSameAccountWait:C};return},z),`Longest wait on the same account set to ${M(L)}.`}})}return{id:"routing",slot:"routing",title:"Routing",content:{lines:U,actions:j}}}function GX($,Z){if($.limits?.labels)return[...$.limits.labels];let J=$.quota?.scope??"all",X=[];for(let z of Z.rows)for(let G of H6(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function BX($,Z){let J=$.quota?.scope??"all",X=new Map;for(let z of Z.rows)for(let G of H6(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,s3(G));return(z)=>X.get(z)??z}function QX($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=C0(Z.settings.killswitch),B=G.enabled===!0,W=C0(G.accounts),Q=GX($,Z),Y=BX($,Z),V=B?"on":"off",H=Z.rows.map((q)=>{let{account:F,name:U}=U6(q,$),j=C0(W[q.id]),K=Q.filter((N)=>typeof j[N]==="number");return{id:q.id,label:U,group:`Floors · killswitch ${V}`,status:K.length===0?"no floors":K.map((N)=>`${Y(N)} ≥${j[N]}%`).join(" · "),account:F,actions:[{id:"floors",label:"Set floors",knobs:Q.map((N)=>({kind:"number",id:N,label:`Minimum % left for ${Y(N)}`,min:0,max:100,...typeof j[N]==="number"?{value:j[N]}:{}})),run:async({values:N})=>{return await J.updateSettings((D)=>{let O=C0(D.killswitch),M=C0(O.accounts),P=C0(M[q.id]);for(let L of Q){let C=N[L];if(typeof C==="number")P[L]=C;else if(C===null)delete P[L]}if(Object.keys(P).length>0)M[q.id]=P;else delete M[q.id];if(Object.keys(M).length>0)O.accounts=M;else delete O.accounts;D.killswitch=O;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${V}`],items:H,actions:[{id:"killswitch",label:B?"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:R2,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:q})=>{let F=q.enabled===!0;return await J.updateSettings((U)=>{U.killswitch={...C0(U.killswitch),enabled:F};return},z),`Killswitch ${F?"on":"off"}.`}}]}}}async function t3($){let Z=await eJ($);return[$X($,Z),ZX($,Z),zX($,Z),QX($,Z)]}var WX=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),i1=["accounts","quota","routing","limits"];function e3($,Z){let{sessionId:J}=$,X=$.notify.bind($);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X(Z(String(z))):X(Z(String(z)),G)})}function YX($,Z){switch($.kind){case"choice":{let J=Z??$.value;if(typeof J==="string"&&$.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${$.label}.`}}case"toggle":{let J=Z??$.value;return typeof J==="boolean"?{value:J}:{problem:`${$.label} must be on or off.`}}case"number":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${$.label} needs a number.`};if($.min!==void 0&&X<$.min)return{problem:`${$.label} must be at least ${$.min}.`};if($.max!==void 0&&X>$.max)return{problem:`${$.label} must be at most ${$.max}.`};return{value:X}}case"text":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${$.label} must be text.`}}}}function VX($,Z){let J={};for(let X of $){let z=Z&&Object.hasOwn(Z,X.id)?Z[X.id]:void 0,G=YX(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function HX($,Z){let J=$.find((z)=>z.id===Z.sectionId);if(!J)return;return(Z.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===Z.itemId)?.actions)?.find((z)=>z.id===Z.actionId)}function G2($){let Z=$.logger??o("commands"),J=s1($.redaction),X={logger:Z,redact:J},z=$.now??Date.now,G=$.extras??[],B=$.replace??{},W=i1.filter((q)=>!B[q]);for(let q of i1)if(B[q]&&$[q]!==void 0)throw Error(`the ${q} section is replaced; its built-in options cannot also be given`);let Q=$.store;if(W.length>0&&!Q)throw Error(`a store is required for the built-in ${W.join(", ")} section${W.length>1?"s":""}`);let Y=new Set;for(let q of G){if(WX.has(q.id)||Y.has(q.id))throw Error(`extra section id ${q.id} is taken`);Y.add(q.id)}async function V(q,F,U,j){try{return{id:q,slot:F,title:U.title,content:await U.build(j)}}catch(K){return Z.warn("command menu section failed to build",{command:$.command,section:q,error:J(K instanceof Error?K.message:String(K))}),{id:q,slot:F,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function H(q){let F=Q&&W.length>0?await t3({store:Q,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],U=[];for(let j of i1){let K=B[j];if(K)U.push(await V(j,j,K,q));else{let N=F.find((D)=>D.slot===j);if(N)U.push(N)}}if($.cache)U.push(await V("cache","cache",$.cache,q));if($.diagnostics)U.push(await V("diagnostics","diagnostics",$.diagnostics,q));for(let j of G)U.push(await V(j.id,"extra",j,q));return U}return{command:$.command,async open(q){let F=e3(q,J);return p3($.command,$.title,await H(F),X)},async apply(q,F){let U=e3(F,J),j=async(M)=>l3($.command,$.title,await H(U),M,X),K=q.command===$.command?HX(await H(U),q):void 0;if(!K)return j({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=a1(K);if(N&&q.confirmed!==!0)return j({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let D=VX(K.knobs??[],q.values);if("problem"in D)return j({ok:!1,code:"invalid-input",text:D.problem});let O;try{let M=await K.run({values:D.values,...q.itemId!==void 0?{itemId:q.itemId}:{},invocation:U});O=typeof M==="string"?{ok:!0,text:M}:{ok:M.ok,text:M.text,...M.ok?{}:{code:M.code??"refused"}}}catch(M){let P=Q4(M);Z.warn("command menu action failed",{command:$.command,section:q.sectionId,action:q.actionId,code:P.code,error:J(M instanceof Error?M.message:String(M))}),O={ok:!1,...P}}return j(O)}}}function UX($){return $===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($)}function qX($){if($===null||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.command!=="string"||typeof Z.sectionId!=="string"||typeof Z.actionId!=="string")return;if(Z.itemId!==void 0&&typeof Z.itemId!=="string")return;if(Z.sessionId!==void 0&&typeof Z.sessionId!=="string")return;if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return;let J={};if(Z.values!==void 0){if(Z.values===null||typeof Z.values!=="object"||Array.isArray(Z.values))return;for(let[X,z]of Object.entries(Z.values)){if(!UX(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:Z.command,sectionId:Z.sectionId,actionId:Z.actionId,...typeof Z.itemId==="string"?{itemId:Z.itemId}:{},...Z.values!==void 0?{values:J}:{},...Z.confirmed===!0?{confirmed:!0}:{},...typeof Z.sessionId==="string"?{sessionId:Z.sessionId}:{}}}function R($,Z){return $.namespace===Z.namespace&&$.accountId===Z.accountId&&$.incarnation===Z.incarnation}function $5($,Z){if($.kind!==Z.kind)return!1;if($.kind==="model")return Z.kind==="model"&&$.model===Z.model;if($.kind==="family")return Z.kind==="family"&&$.family===Z.family;return!0}function jX($){return{requestId:$.requestId,originalUrl:$.originalUrl,requestStartedAt:$.clockNow,saw429:!1,tried:[],excludedForRequest:[],retains:[],retainedAttempts:[],excludedAttempts:[],switchedAttempts:[],switches:0}}function q6($,Z,J){return $.excludedForRequest.some((X)=>R(X.account,Z)&&$5(X.scope,J))}function I2($,Z){switch(Z.type){case"response":{let J=$.tried.some((X)=>R(X.account,Z.account)&&$5(X.scope,Z.scope))?$.tried:[...$.tried,{account:{...Z.account},scope:{...Z.scope}}];return{...$,tried:J,saw429:$.saw429||Z.status===429,...Z.kind==="payment-balance"?{sawPaymentBalance:!0}:{},lastStatus:Z.status}}case"retain":{if(Z.cause==="credential-recovery"||$.retainedAttempts.includes(Z.attemptId))return $;let J=$.retains.find((X)=>R(X.account,Z.account));return{...$,retainedAttempts:[...$.retainedAttempts,Z.attemptId],retains:[...$.retains.filter((X)=>!R(X.account,Z.account)),{account:{...Z.account},count:(J?.count??0)+1,startedAt:J?.startedAt??Z.clockNow,lastRetainedAt:Z.clockNow}]}}case"exclude":if($.excludedAttempts.includes(Z.attemptId))return $;return{...$,excludedAttempts:[...$.excludedAttempts,Z.attemptId],excludedForRequest:q6($,Z.account,Z.scope)?$.excludedForRequest:[...$.excludedForRequest,{account:{...Z.account},scope:{...Z.scope}}]};case"switch":return $.switchedAttempts.includes(Z.attemptId)?$:{...$,switchedAttempts:[...$.switchedAttempts,Z.attemptId],switches:$.switches+1};case"blocked":return $.blockedSince===void 0?{...$,blockedSince:Z.clockNow}:$;case"selected":{let{blockedSince:J,...X}=$;return X}}}var r1=Object.freeze({refundHybridToken:!0,cancelDiscardedBody:!0,addMark:!1,addCooldown:!1,penalizeHealth:!1,chargeSwitch:!1});function B2($){return $!==void 0&&Number.isFinite($)&&$>=0?$:300000}function j6(){let $=new Map;return{get size(){return $.size},recordAccepted(Z){if(!R(Z.accountKey,Z.currentAccountKey)||!Number.isFinite(Z.lastAcceptedAt))return!1;let J=$.get(Z.sessionId);if(J&&J.lastAcceptedAt>Z.lastAcceptedAt)return!1;let X=typeof Z.ttlMs==="number"?[Z.ttlMs]:Z.ttlMs,z=X?.length?Math.max(...X.map(B2)):B2(void 0);if($.set(Z.sessionId,Object.freeze({accountKey:Object.freeze({...Z.accountKey}),lastAcceptedAt:Z.lastAcceptedAt,ttlMs:z})),$.size>256){let G,B=Number.POSITIVE_INFINITY;for(let[W,Q]of $)if(Q.lastAcceptedAt<B)G=W,B=Q.lastAcceptedAt;if(G!==void 0)$.delete(G)}return!0},get(Z){return $.get(Z)},forgetSession(Z){$.delete(Z)}}}function F6($,Z,J){switch($.kind){case"pool":return!0;case"family":return J(Z)===$.family;case"model":return $.model===Z}}var W4=3621000;function h0($){return $===0||$===15||$==="max"?$:15}function Y4($){let Z=h0($.maxSameAccountWait),J=$.activity;if(Z===0||!J||!R(J.accountKey,$.accountKey)||!Number.isFinite(J.lastAcceptedAt))return;let X=B2(J.ttlMs),z=J.lastAcceptedAt+X;if(X===0||!Number.isFinite(z))return;return{cacheExpiresAt:z,maxWaitMs:Z==="max"?Number.POSITIVE_INFINITY:900000}}import{createHash as FX}from"node:crypto";function o1($,Z){let J=FX("sha256").update($).digest().readUInt32BE(0);return 1000*(Math.max(1,Math.ceil(Z/1000))+J%21)}function K6($,Z){if(!Number.isFinite($.maxAgeMs)||$.maxAgeMs<0)return;let J;for(let X of $.candidates){if(!R(X.account,X.readingAccount)||X.identity!==void 0&&X.readingIdentity!==void 0&&X.identity!==X.readingIdentity)continue;let z=X.windows.filter((Q)=>Q.blockedBy&&F6(Q.scope,$.effectiveModel,$.familyOf));if(!z.length)continue;let G=z.map((Q)=>{let Y=Q.reset,V=Y?.observedAt??Y?.checkedAt;return Y&&V!==void 0&&Number.isFinite(V)&&Z-V<=$.maxAgeMs&&Number.isFinite(Y.at)&&Y.at>Z?Y.at:void 0});if(G.some((Q)=>Q===void 0))continue;let B=Math.max(...G);if(J&&J.resetAt<=B)continue;let W=z.some((Q)=>Q.blockedBy!=="exhausted"&&Q.reset?.at===B);J={account:X.account,resetAt:B,checkpoint:{accountKey:{...X.account},decidedAt:Z,blockers:W?[]:z.flatMap((Q)=>Q.blockedBy==="exhausted"&&Q.reset?[{window:Q.window,resetAt:Q.reset.at}]:[])}}}return J}function Z5($,Z){return $.source==="pool"&&$.reason==="quota"&&Z.terminalMetadata==="setting-capped-fresh"}function J5($,Z){return Z5($,Z)&&h0($.scan?.maxSameAccountWait)===0}function X5($,Z,J,X){if(!Z5(X,Z))return;let z=X.scan,G=h0(z?.maxSameAccountWait),B=z&&K6(z,$.now),W=B?B.resetAt-$.now:300000,Q=z?.activity,Y=z?.accountKey??$.attempted,V=Q&&Y&&R(Q.accountKey,Y)?B2(Q.ttlMs)||300000:300000,H=Math.min(W,G==="max"?V:900000),q=G===0||$.host==="pi"&&$.wake?.kind==="terminal",F=q?B?W:void 0:H,U=Z.refusals.quota[$.host],j={action:"refuse",reason:"quota",family:$.host==="pi"?"pi-final":q?"json-412":U.family,messageKey:X.messageKey??U.messageKey,retryable:$.host!=="pi"&&!q,hostRetry:$.host==="pi"||q?"veto":"leave",history:J,...F===void 0?{}:{retryAfterMs:F},...B?{resetAt:B.resetAt}:{}};if(!B||q||$.host==="opencode1")return j;let K={delayMs:H,retryAfterMs:H,resetAt:B.resetAt,target:$.now+H,checkpoint:B.checkpoint,waitKind:"terminal",reason:"terminal-quota",retryable:!0,hostRetry:"leave",history:J};if($.host==="pi")return{...K,action:"wait-then-reselect"};if($.hostPhase!=="retry")return j;if($.remainingRetries!==void 0&&$.remainingRetries<1)return{action:"pass",reason:"host-retries-exhausted",retryable:!0,hostRetry:"leave",history:J};if($.remainingRetries===void 0||H>W4)return j;return{...K,action:"hold",account:B.account}}function t1($,Z,J){return{accountKey:{...$},decidedAt:Z,blockers:J.filter((X)=>X.confirmed&&Number.isFinite(X.resetAt)).map((X)=>({window:X.window,resetAt:X.resetAt}))}}function z5($,Z,J,X){let{checkpoint:z,target:G}=$;if(!R(Z,z.accountKey)||!Number.isFinite(G)||!Number.isFinite(z.decidedAt)||G<z.decidedAt||!Number.isFinite(X)||X<G)return[];let B=(W)=>{let Q=W.resetAt;return W.confirmed&&Q!==void 0&&Number.isFinite(Q)&&Q<=G&&z.blockers.some((Y)=>Y.window===W.window&&Number.isFinite(Y.resetAt)&&Q<=Y.resetAt)};return J.filter((W)=>B(W)&&J.filter((Q)=>Q.confirmed&&Q.window===W.window).every(B)).map((W)=>W.window)}function N6($,Z){return $!==void 0&&Number.isFinite($)&&$>Z}function b2($,Z){return Z.execution==="engine"&&$.phase==="after-limit"?"veto":"leave"}function k0($,Z,J,X,z){let G=z&&X5($,Z,J,z);if(G)return G;let B=Z.refusals[X][$.host];return{action:"refuse",reason:X,family:z?.family??B.family,messageKey:z?.messageKey??B.messageKey,retryable:z?.retryable??B.retryable,hostRetry:z?.hostRetry??B.hostRetry,history:J,...z?.retryAfterMs===void 0?{}:{retryAfterMs:z.retryAfterMs},...z?.resetAt===void 0?{}:{resetAt:z.resetAt}}}function KX($,Z,J,X,z){let G=$.hold;if(Z.shortLimit.holdBound==="disabled"||$.host==="opencode2"&&($.hostPhase!=="retry"||$.remainingRetries===void 0||!($.remainingRetries>=1))||!X?.admitted||!G||G.maxWaitMs<=0||Number.isNaN(G.maxWaitMs)||!Number.isFinite(G.cacheExpiresAt)||G.maxDelayMs!==void 0&&(!Number.isFinite(G.maxDelayMs)||G.maxDelayMs<0)||!z.length||z.some((Y)=>!N6(Y.resetAt,$.now)))return;let B=Math.max(...z.map((Y)=>Y.resetAt)),W=Z.shortLimit.jitter==="session-sha256"?o1($.sessionId,B-$.now):B-$.now,Q=$.now+W;if(!Number.isFinite(Q)||Q>Math.min(G.cacheExpiresAt,$.now+G.maxWaitMs)||$.host==="opencode2"&&W>W4||G.maxDelayMs!==void 0&&W>G.maxDelayMs)return;return{action:"hold",account:X.account,delayMs:W,retryAfterMs:W,target:Q,checkpoint:t1(X.account,$.now,z),reason:"confirmed-limit",retryable:!0,hostRetry:$.phase==="pre-send"?"leave":b2($,Z),history:J}}function NX($,Z,J,X){let z=Z.poolWaiting;if(z.kind==="off"||!X.length)return;J=I2(J,{type:"blocked",clockNow:$.clockNow});let B=X.map((F)=>{let U=F.blockers.filter((j)=>!(j.kind==="soft"&&X.length===1&&z.singleEligibleSoftExemption));if(U.some((j)=>!N6(j.until,$.now)))return;return U.length?{candidate:F,time:Math.max(...U.map((j)=>j.until))}:void 0}).filter((F)=>F!==void 0).reduce((F,U)=>!F||U.time<F.time?U:F,void 0),W=B?B.time-$.now:X.some((F)=>F.blockers.some((U)=>U.kind!=="soft"))?z.hardFallbackMs:void 0,Q=$.poolWaitBudgetMs??z.budgetMs,Y=$.clockNow-(J.blockedSince??$.clockNow);if(Q>0&&(Y>=Q||W!==void 0&&W>Q))return k0($,Z,J,"quota",$.terminal);let V=z.requestDeadlineMs-($.clockNow-J.requestStartedAt);if(V<=0)return k0($,Z,J,"incomplete");if(W===void 0)return k0($,Z,J,"quota",$.terminal);let H=Math.min(W,V,Q>0?Q-Y:Number.POSITIVE_INFINITY),q=B?.candidate??X[0];if(!q)return;return{action:"wait-then-reselect",delayMs:H,target:$.now+H,checkpoint:t1(q.account,$.now,q.confirmedBlockers??[]),reason:"pool-blocked",retryable:!0,hostRetry:b2($,Z),history:J}}function e1($,Z){let J=$.history,X=(C,T=$.phase==="pre-send"?!0:$.failureRetryable??!0,A="leave")=>({action:"pass",reason:C,retryable:T,hostRetry:A,history:J});if($.phase==="after-limit"&&$.host==="opencode2"&&(!$.delivery.owned||!$.delivery.attributable))return X("not-owned");let z=$.status??$.signal?.status;if($.phase==="after-limit"&&$.attempted)J=I2(J,{type:"response",account:$.attempted,scope:$.requestScope,status:z,kind:Z.terminalStatusHistory?.paymentBalance&&$.signalApplicable!==!1&&$.signal&&R($.signal.account,$.attempted)?$.signal.kind:void 0});if($.phase==="after-limit"&&!$.delivery.replayable)return X("unsafe-output",!1,"veto");let G=$.candidates.filter((C)=>C.admitted),B=G.filter((C)=>!q6(J,C.account,$.requestScope)),W=B.find((C)=>$.attempted&&R(C.account,$.attempted)),Q=$.signalApplicable!==!1&&$.signal&&$.attempted&&R($.signal.account,$.attempted)?$.signal:void 0;if(Z.requestExclusion==="on"&&Q?.kind==="model-unavailable"&&W)return{action:"exclude-for-request",account:W.account,scope:$.requestScope,effects:r1,reason:"model-unavailable",retryable:!0,hostRetry:b2($,Z),history:J};if(G.length&&!B.length)return k0($,Z,J,"model-unavailable");if($.host==="opencode2"&&$.hostPhase==="retry"&&Z.execution==="host"&&$.remainingRetries!==void 0&&$.remainingRetries<1)return $.terminal&&($.terminal.retryable===!1||J5($.terminal,Z))?k0($,Z,J,$.terminal.reason,$.terminal):X("host-retries-exhausted");if($.wake&&$.phase==="pre-send"){let C=$.wake,T=B.find((c)=>R(c.account,C.checkpoint.accountKey)),A=T?.confirmedBlockers??(T&&Q&&R(Q.account,T.account)?Q.windows:[]),x=T?z5(C,T.account,A,$.now):[],I=$.hold,f=C.kind==="terminal"||I!==void 0&&Number.isFinite(I.cacheExpiresAt)&&$.now<=I.cacheExpiresAt&&C.target<=I.cacheExpiresAt&&I.maxWaitMs>0&&C.target-C.checkpoint.decidedAt<=I.maxWaitMs;if(T&&Number.isFinite(C.target)&&C.target>=C.checkpoint.decidedAt&&$.now>=C.target&&f&&T.blockers.every((c)=>c.until!==void 0&&Number.isFinite(c.until)&&c.until<=$.now)&&(T.ready||A.some((c)=>c.confirmed))&&A.filter((c)=>c.confirmed).every((c)=>x.includes(c.window)))return{action:"retain",account:T.account,liftedWindows:x,reason:"wait-elapsed",retryable:!0,hostRetry:"leave",history:I2(J,{type:"selected"})}}if($.credentialRecovery&&W)return{action:"retain",account:W.account,reason:"credential-recovery",...$.credentialRecovery.retryMs===void 0?{}:{retryMs:$.credentialRecovery.retryMs},retryable:!0,hostRetry:b2($,Z),history:J};let Y=Z.unconfirmedRetainLimit,V=$.unconfirmedRetainCount,H=z===429&&Y!==void 0&&V!==void 0,q=Z.advance[$.host];if($.phase==="after-limit"&&Z.terminalStatusHistory?.paymentBalance&&(Q?.kind==="payment-cap"||z===402&&Q?.kind!=="payment-balance"))return X("unhandled-failure");if($.phase==="after-limit"&&!Q&&!H&&!$.terminal&&(q.attributedLimitOnly||z===void 0||!q.statuses.includes(z)))return X("unhandled-failure");let F=B.find((C)=>$.selection&&R(C.account,$.selection.account)&&C.placementEligible),U=F&&(F.ready||Z.poolWaiting.kind==="earliest"&&Z.poolWaiting.singleEligibleSoftExemption&&B.length===1&&F.blockers.length>0&&F.blockers.every((C)=>C.kind==="soft")),j=U&&(!$.attempted||!R(F.account,$.attempted))?F:void 0,K=(C,T="ready-alternative")=>({action:"reroute",account:C.account,pin:$.selection?.pin??"preserve",reason:T,retryable:!0,hostRetry:b2($,Z),history:I2(J,{type:"selected"})}),N=$.phase==="pre-send"?W??B.find((C)=>$.selection&&R(C.account,$.selection.account)):W,D=(N?.confirmedBlockers??($.phase==="after-limit"?Q?.windows:void 0)??[]).filter((C)=>C.confirmed);if(D.length){if(Z.shortLimit.preference==="ready-alternative-first"&&j)return K(j);let C=KX($,Z,J,N,D);if(C)return C}let O=Z.unknown[$.host],M=$.phase==="after-limit"&&!D.length&&(z===429||Q?.kind==="rate-limit"||Q?.kind==="quota-exhausted"||Q?.kind==="capacity"),P=H&&V>=Y;if(M&&W&&(O.affinity==="always"||$.affinity==="sticky")){if(H&&P){if(j)return K(j,"unconfirmed-retry-limit")}else if(H||O.action==="retain"){let C=[...$.retryHintsMs??[],Q?.retryAfterMs].filter((T)=>T!==void 0&&Number.isFinite(T)&&(H||T>=0));return{action:"retain",account:W.account,reason:"unconfirmed-limit",...H?{retryMs:Math.min(60000,...C.map((T)=>Math.max(0,T))),incrementUnconfirmedRetain:!0}:O.hint==="minimum"?{retryMs:Math.min(O.defaultMs,...C)}:{},retryable:!0,hostRetry:b2($,Z),history:J}}else if(O.action==="pass")return X("unconfirmed-limit")}if(j)return K(j);if($.phase==="pre-send"&&U)return K(F);if($.host==="opencode2"&&$.hostPhase==="request"&&Z.markedPool.requestEscape==="ignore-timed-marks-if-all-marked"&&F&&B.every((C)=>!C.ready)&&B.every((C)=>C.blockers.length>0&&C.blockers.every((T)=>T.kind==="hard")))return K(F);let L=NX($,Z,J,B);if(L)return L;if($.phase==="pre-send"&&!B.length)return k0($,Z,J,$.terminal?.reason??"auth",$.terminal);if($.host==="opencode2"&&$.hostPhase==="retry"&&!$.terminal){if(Z.markedPool.retryExhaustion==="host-delay")return X("host-delay");if(Z.markedPool.retryExhaustion==="same-host-delay"&&W)return{action:"retain",account:W.account,reason:"host-delay",retryable:!0,hostRetry:"leave",history:J}}if(Z.terminalPolicy==="status-history"&&Z.terminalStatusHistory&&$.host!=="opencode2"&&!$.terminal){let C=$.phase==="pre-send"&&B.length>0&&B.every((x)=>!x.ready),T=B.filter((x)=>x.placementEligible),A=$.phase==="pre-send"&&Z.terminalStatusHistory.paymentBalance&&T.length>0&&T.every((x)=>!x.ready&&x.blockers.length>0&&x.blockers.every((I)=>I.cause==="payment-balance"&&N6(I.until,$.now)));if(A||C||z===401&&J.saw429||Z.terminalStatusHistory.paymentBalance&&J.saw429&&J.sawPaymentBalance){let x=(A?T:B).flatMap((I)=>I.blockers.map((f)=>f.until)).filter((I)=>N6(I,$.now));return k0($,Z,J,"quota",{source:"pool",reason:"quota",...A?Z.terminalStatusHistory.paymentBalance:{},retryAfterMs:x.length?Math.max(Z.terminalStatusHistory.minRetryMs,Math.min(...x)-$.now):Z.terminalStatusHistory.defaultRetryMs})}return X("original-response")}if($.terminal)return k0($,Z,J,$.terminal.reason,$.terminal);if(Q?.kind==="auth"||Q?.kind==="account-access")return k0($,Z,J,"auth");if(Q||z===429||B.some((C)=>C.blockers.length))return k0($,Z,J,"quota");return X("no-override")}function k2($){if(!Number.isFinite($))return"unknown";let Z=Math.ceil(Math.max(0,$)/1000);if(Z<60)return`${Z}s`;let J=Math.ceil(Z/60),X=Math.floor(J/1440);if(X>=100)return"over 99 days";let z=Math.floor(J/60)%24,G=J%60;if(X>0)return`${X}d ${z}h ${G}m`;if(z>0)return`${z}h ${G}m`;return`${G}m`}var x2=({resetAt:$,now:Z})=>k2($-Z);var Z9=Symbol.for("@cortexkit/common-auth/limits-envelope-error");class H4 extends Error{[Z9]="conflict";constructor(){super("Conflicting limits envelope writers");this.name="LimitsEnvelopeConflictError"}}class U4 extends Error{[Z9]="unsupported";constructor(){super("Invalid or unsupported limits namespace schema");this.name="LimitsEnvelopeUnsupportedError"}}function J9($){let Z=$&&typeof $==="object"&&Reflect.get($,Z9);return Z==="conflict"||Z==="unsupported"?Z:void 0}function m0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}var Q2=($)=>Number.isSafeInteger($)&&$>=0,$9=($)=>typeof $==="number"&&Number.isFinite($),G5=($)=>$===void 0||$==="rate-limit"||$==="payment-balance",V4=($,Z)=>Array.isArray($)&&$.every(Z);function Q5($,Z){return m0($)&&$.namespace===Z&&typeof $.accountId==="string"&&typeof $.incarnation==="string"}function B5($,Z){if(!m0($)||!m0($.scope))return!1;let J=$.scope;return Q5($.account,Z)&&typeof $.window==="string"&&(J.kind==="pool"||J.kind==="family"&&typeof J.family==="string"||J.kind==="model"&&typeof J.model==="string")}function DX($,Z){return $.namespace===Z&&typeof $.generation==="string"&&Q2($.revision)&&Q2($.lowWatermark)&&V4($.marks,(J)=>m0(J)&&B5(J.key,Z)&&["latest-evidence","max-until","overwrite"].includes(J.mergeLaw)&&V4(J.entries,(X)=>m0(X)&&G5(X.cause)&&$9(X.until)&&$9(X.evidenceAt)&&Q2(X.baseRevision)&&Q2(X.committedRevision)))&&V4($.tombstones,(J)=>m0(J)&&B5(J.key,Z)&&Q2(J.revision)&&G5(J.cause))&&V4($.operationIds,(J)=>m0(J)&&typeof J.producerId==="string"&&typeof J.operationId==="string"&&Q2(J.revision))&&V4($.access,(J)=>m0(J)&&Q5(J.account,Z)&&$9(J.eligibilityStateUpdatedAt)&&Q2(J.committedRevision))}class q4{namespace;logger;replaced=!1;terminal;constructor($,Z){this.namespace=$,this.logger=Z}assertWritable(){if(this.terminal)throw this.terminal}decode($){if(this.assertWritable(),$===void 0)return{};let Z;if(!m0($))Z="malformed";else if($.schemaVersion!==1)throw this.terminal=new U4,this.terminal;else if(typeof $.namespace==="string"&&$.namespace!==this.namespace)Z="foreign-namespace";else if(!DX($,this.namespace))Z="malformed";if(!Z)return{snapshot:$};if(this.replaced)throw this.terminal=new H4,this.terminal;return{replacement:Z}}didCommit($){if(!$||this.replaced)return!1;this.replaced=!0;try{this.logger?.warn(`limits envelope replaced: ${$}`)}catch{}return!0}}var PX=[/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],MX=new RegExp(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","stream disconnected before completion","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"].join("|"),"i");function y2($){return PX.some((Z)=>Z.test($))||MX.test($)}class D6 extends Error{messageKey;code="unsafe-wording";constructor($){super(`Unsafe refusal template: ${$}`);this.messageKey=$,this.name="UnsafeWordingError"}}function X9($){let Z=new Map(Object.entries($.refusals??{})),J=new Map(Object.entries($.retryable??{}));for(let[X,z]of Z)for(let G of[void 0,"45s","2m","1h 30m","99d 23h 59m","over 99 days"])for(let B of[[],["this account"]]){let W=Object.freeze({labels:Object.freeze(B),reset:G}),Q;try{Q=z(W)}catch{throw new D6(X)}if(typeof Q!=="string"||y2(Q))throw new D6(X)}return Object.freeze({formatReset:$.formatReset,render:(X,z,G)=>(G?Z:J).get(X)?.(z)})}var CX=/[^\s@]+@[^\s@]+\.[^\s@]+/;function z9($){return CX.test($)}function G9($){return z9($)||y2($)?"this account":$}class B9 extends Error{code="ECONNRESET";syscall="sticky-routing";isRetryable=!0;constructor($){super($,{cause:{code:"ECONNRESET",syscall:"sticky-routing"}});this.name="ClaudeIncompleteError"}}function P6($,Z=0){if($===void 0||!Number.isFinite($)||$<0)return;let J=$-Q9(Z);return J>=0?Math.ceil(J/1000):void 0}function Q9($){return Number.isFinite($)&&$>=0?$:0}function Y5($){return $.resetAt!==void 0&&Number.isFinite($.resetAt)?$.resetAt:void 0}function TX($){return $===void 0?"The reset is unknown.":`Reset at ${$}.`}function V5($,Z,J,X){let z=!X&&J!==void 0?` Retry in ${k2(J*1000)}.`:"";return`${$==="pi-final"?"The request cannot continue.":"No account is available."}${z} ${TX(Z)}`}function H5($,Z,J){let X=Y5($),z=X===void 0?void 0:x2({resetAt:X,now:Z}),G=P6($.retryAfterMs,$.noticeDelayMs);return V5($.family,z,G,J)}function LX($,Z){let J=$.now+Q9($.noticeDelayMs??0),X=()=>H5($,J,Z);try{let z=Y5($),G=z===void 0?void 0:($.messages?.formatReset??x2)({resetAt:z,now:J}),B=P6($.retryAfterMs,$.noticeDelayMs),W=Object.freeze({labels:Object.freeze($.labelPolicy==="relogin"?($.parameters?.labels??[]).map(G9):[]),reset:G,retryIn:!Z&&B!==void 0?k2(B*1000):void 0}),Q=$.messages?.render($.messageKey,W,Z);return typeof Q==="string"?Q:V5($.family,G,B,Z)}catch{return X()}}function W5($,Z){switch($){case"openai-429":return JSON.stringify({error:{message:Z,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}});case"claude-429":return JSON.stringify({type:"error",error:{type:"rate_limit_error",message:Z}});case"json-412":return JSON.stringify({error:{code:412,status:"FAILED_PRECONDITION",message:Z}});case"claustrum-429":return JSON.stringify({error:"claustrum-auth: accounts-rate-limited"});case"claustrum-402":return JSON.stringify({error:"claustrum-auth: insufficient balance"});default:return Z}}function W9($){let Z=$.family==="json-412"||$.family==="pi-final",J={family:$.family,disposition:"refuse",retryable:!Z,hostRetry:Z||$.host==="opencode2"?"veto":"leave"},X=W5($.family,LX($,Z));if(Z&&(y2(X)||z9(X))){let B=$.now+Q9($.noticeDelayMs??0);X=W5($.family,H5($,B,!0))}if($.family==="claude-econnreset")return{...J,kind:"throw",error:new B9(X)};if($.family==="pi-final")return{...J,kind:"text",body:X};let z=new Headers($.family==="json-412"?$.extraHeaders:void 0);z.set("content-type","application/json"),z.delete("retry-after");let G=P6($.retryAfterMs,$.noticeDelayMs);if(G!==void 0)z.set("retry-after",String(G));return{...J,kind:"http",status:$.family==="json-412"?412:$.family==="claustrum-402"?402:429,headers:z,body:X}}function w0($,Z){return R($.account,Z.account)&&($.identity===void 0||Z.identity===void 0||$.identity===Z.identity)}function Y9($,Z){if(!w0($,Z))return Z;return{...Z,identity:Z.identity??$.identity}}function V9($,Z,J){if(!w0($,Z))return"identity-replaced";if(!J($,Z))return"credential-epoch";return}var H9=Object.freeze({kind:"failure-ladder",mergeLaw:"max-until",hintFloorMs:2000,quotaSteps:Object.freeze([60000,300000,1800000,7200000]),byKind:Object.freeze({"rate-limit":30000}),byReason:Object.freeze({"server-error":20000,unknown:60000}),capacity:Object.freeze({baseMs:45000,spreadMs:15000}),defaultMs:60000});function M6($,Z,J,X=0){let z=Z.filter((G)=>G.baseRevision>=X);if($!=="max-until"){let G=z.reduce((B,W)=>{if(!B)return W;if($==="latest-evidence"&&W.evidenceAt!==B.evidenceAt)return W.evidenceAt>B.evidenceAt?W:B;return W.committedRevision>B.committedRevision?W:B},void 0);return G&&J<G.until?[G]:[]}return z.filter((G,B)=>J<G.until&&!z.some((W,Q)=>Q!==B&&W.until>=G.until&&W.baseRevision>=G.baseRevision&&(W.until>G.until||W.baseRevision>G.baseRevision||W.committedRevision>G.committedRevision||W.committedRevision===G.committedRevision&&Q<B))).sort((G,B)=>G.committedRevision-B.committedRevision)}function j4($,Z){if($.eligibilityStateUpdatedAt!==Z.eligibilityStateUpdatedAt)return $.eligibilityStateUpdatedAt>Z.eligibilityStateUpdatedAt?$:Z;return $.committedRevision>Z.committedRevision?$:Z}var q5=1024;function U9($){return $==="rate-limit"||$==="payment-balance"?$:void 0}function C6($,Z){return U9($.cause)===void 0||$.cause===Z}function j5($){return JSON.stringify([p($.key),U9($.cause)])}function T0($,Z){return{schemaVersion:1,namespace:$,generation:Z,revision:0,lowWatermark:0,marks:[],tombstones:[],operationIds:[],access:[]}}function OX($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function p($){let Z=$.scope;return JSON.stringify([OX($.account),Z.kind,Z.kind==="model"?Z.model:Z.kind==="family"?Z.family:null,$.window])}function U5($){return JSON.stringify([$.producerId,$.operationId])}function W2($,Z){let J=new Map;for(let Q of $.tombstones){let Y=p(Q.key),V=J.get(Y);if(V)V.push(Q);else J.set(Y,[Q])}let X=$.marks.flatMap((Q)=>{let Y=J.get(p(Q.key)),V=M6(Q.mergeLaw,Y?Q.entries.filter((H)=>!Y.some((q)=>C6(q,H.cause)&&H.baseRevision<q.revision)):Q.entries,Z);return V.length?[{...Q,entries:V}]:[]}),z=$.lowWatermark,G=(Q)=>{let Y=[...Q].sort((H,q)=>H.revision-q.revision),V=Math.max(0,Y.length-q5);for(let H of Y.slice(0,V))z=Math.max(z,H.revision+1);return Y.slice(V)},B=G($.tombstones),W=G($.operationIds);return{...$,revision:Math.max($.revision,z),marks:X,tombstones:B,operationIds:W,lowWatermark:z}}function Y2($,Z,J){let X=W2($,J.now),z=[];for(let G of Z){let B=(K)=>{z.push({producerId:G.producerId,operationId:G.operationId,status:"rejected",reason:K})};if(G.binding.account.namespace!==X.namespace){B("wrong-namespace");continue}if(G.baseRevision<X.lowWatermark){B("below-watermark");continue}if(G.baseRevision>X.revision){B("future-revision");continue}let W=J.bindings.find((K)=>R(K.account,G.binding.account));if(!W){B("unknown-account");continue}let Q=V9(G.binding,W,J.authorizeEpoch);if(Q){B(Q);continue}let Y=X.operationIds.find((K)=>U5(K)===U5(G));if(Y){z.push({...Y,status:"duplicate"});continue}let V=W.account,H=X.revision+1,q=[...X.marks],F=[...X.tombstones],U=[...X.access];if(G.type==="mark"){let K={account:V,scope:G.scope,window:G.window},N=p(K),D=q.find((M)=>p(M.key)===N);if(F.some((M)=>G.baseRevision<M.revision&&C6(M,G.cause)&&p(M.key)===N)){B("cleared");continue}if(D&&D.mergeLaw!==G.mergeLaw){B("merge-law-conflict");continue}let O=M6(G.mergeLaw,[...D?.entries??[],{until:G.until,evidenceAt:G.evidenceAt,baseRevision:G.baseRevision,committedRevision:H,...G.cause==="rate-limit"||G.cause==="payment-balance"?{cause:G.cause}:{}}],J.now);if(q=q.filter((M)=>p(M.key)!==N),O.length)q.push({key:K,mergeLaw:G.mergeLaw,entries:O})}else if(G.type==="clear"){let K=U9(G.cause),N=G.keys.map((M)=>({...M,account:V})).filter((M)=>G.cause===void 0||!q.some((P)=>p(P.key)===p(M)&&P.entries.some((L)=>L.cause!==G.cause))),D=new Set(N.map(p)),O=G.evidenceAt;if(O!==void 0&&q.some((M)=>D.has(p(M.key))&&M.entries.some((P)=>P.evidenceAt>O))){B("newer-evidence");continue}q=q.filter((M)=>!D.has(p(M.key))),F=F.filter((M)=>!D.has(p(M.key))||K!==void 0&&M.cause!==K);for(let M of new Map(N.map((P)=>[p(P),P])).values())F.push({key:M,revision:H,...K===void 0?{}:{cause:K}})}else{let K={account:V,state:G.state,eligibilityStateUpdatedAt:G.eligibilityStateUpdatedAt,committedRevision:H},N=U.find((D)=>R(D.account,V));U=U.filter((D)=>!R(D.account,V)),U.push(N?j4(N,K):K)}let j={producerId:G.producerId,operationId:G.operationId,revision:H};X=W2({...X,revision:H,marks:q,tombstones:F,access:U,operationIds:[...X.operationIds,j]},J.now),z.push({...j,status:"committed"})}return{snapshot:X,outcomes:z}}import{realpathSync as SX}from"node:fs";import{basename as F5,dirname as K5,join as AX,resolve as EX}from"node:path";function F4($){let Z=EX($),J=[F5(Z)],X=K5(Z);for(;;)try{return AX(SX.native(X),...J.reverse())}catch(z){let G=z.code;if(G!=="ENOENT"&&G!=="ENOTDIR")throw z;let B=K5(X);if(B===X)return Z;J.push(F5(X)),X=B}}class L0 extends Error{code;constructor($){super($);this.code=$,this.name="LimitsPersistenceRefusal"}}import{randomUUID as kX}from"node:crypto";import{isDeepStrictEqual as D5}from"node:util";import{AsyncResource as RX}from"node:async_hooks";import{randomUUID as N5}from"node:crypto";import{isDeepStrictEqual as IX}from"node:util";var bX=new RX("common-auth-limits-recovery");class K4{logger;running;listeners=new Set;constructor($){this.logger=$}subscribe=($)=>{return this.listeners.add($),()=>this.listeners.delete($)};schedule($){if(this.running)return;this.running=bX.runInAsyncScope(async()=>{await Promise.resolve();let Z=!1;try{await $(),Z=!0}catch(J){try{this.logger?.warn("limits envelope recovery failed; agreement remains degraded",{error:J instanceof Error?J.message:String(J)})}catch{}}finally{if(this.running=void 0,Z)for(let J of this.listeners)try{J()}catch{}}})}}class V2{seen;missingGeneration;incorporated;remember($,Z){if(this.seen&&this.seen.revision>$.revision)return;if(this.seen=structuredClone($),this.missingGeneration=void 0,Z)this.incorporated=structuredClone(Z)}retained($){let Z=IX($,this.incorporated)?void 0:$;return[this.seen,Z].filter((J)=>J!==void 0&&(J===this.seen||J.revision>0))}lost($,Z){return this.retained(Z).some((J)=>!$||J.generation!==$.generation||$.revision<J.revision||J.tombstones.some((X)=>X.revision>$.lowWatermark&&!$.tombstones.some((z)=>p(z.key)===p(X.key)&&C6(z,X.cause)&&z.revision>=X.revision)))}recover($,Z,J,X){if(!$)this.missingGeneration??=N5();let z=$??T0(J,this.missingGeneration??N5()),G=[...this.retained(Z),z],B=new Map,W=new Map,Q=new Map,Y=new Map,V=0;for(let q of G){V=Math.max(V,q.revision,q.lowWatermark);for(let F of q.marks){let U=p(F.key),j=B.get(U);if(j&&j.mergeLaw!==F.mergeLaw)throw Error("limits-recovery-merge-law-conflict");B.set(U,{...F,entries:[...j?.entries??[],...F.entries]});for(let K of F.entries)V=Math.max(V,K.baseRevision,K.committedRevision)}for(let F of q.tombstones){let U=j5(F),j=W.get(U);if(!j||j.revision<F.revision)W.set(U,F);V=Math.max(V,F.revision)}for(let F of q.operationIds){let U=JSON.stringify([F.producerId,F.operationId]),j=Q.get(U);if(!j||j.revision<F.revision)Q.set(U,F);V=Math.max(V,F.revision)}for(let F of q.access){let{namespace:U,accountId:j,incarnation:K}=F.account,N=JSON.stringify([U,j,K]),D=Y.get(N);Y.set(N,D?j4(D,F):F),V=Math.max(V,F.committedRevision)}}let H=V+1;if(!Number.isSafeInteger(H))throw Error("limits-revision-exhausted");return W2({...z,revision:H,lowWatermark:H,marks:[...B.values()],tombstones:[...W.values()],operationIds:[...Q.values()],access:[...Y.values()]},X)}}function P5($,Z){return Z.flatMap((J)=>J.credentialEpoch===void 0?[]:[{account:{namespace:$,accountId:J.id,incarnation:String(J.credentialEpoch)},credentialEpoch:String(J.credentialEpoch),...J.identity===void 0?{}:{identity:J.identity}}])}async function q9($){let{store:Z,namespace:J}=$;if(!Z.updateLimitsNamespace)throw new L0("limits-unsupported");let X=Z.updateLimitsNamespace.bind(Z),z=kX(),G=new V2,B=new q4(J,$.logger),W=new K4($.logger),Q=$.now??Date.now,Y=async()=>{let F=await Z.read();if(F.status!=="ready"){if(F.status==="error"&&F.kind==="snapshot-contended")throw Error(F.reason);throw new L0("pool-not-ready")}return P5(J,F.rows)},V=async()=>{let F=await Z.readSettings();if(F.status!=="ready")throw new L0("pool-not-ready");return B.decode(F.settings.commonAuthLimits)},H=async(F)=>{B.assertWritable();let U=await Y(),j=await V(),K;for(let N=0;N<3;N++){let D=await Y(),O=await V(),M=D5(U,D)&&D5(j,O);if(K={snapshot:j.snapshot??T0(J,z),bindings:U,authoritative:M},M){if(!j.replacement&&G.lost(j.snapshot,F))return W.schedule(()=>q.commit([],F)),{snapshot:G.recover(j.snapshot,F,J,Q()),bindings:U,authoritative:!1,degradedAgreement:!0};if(j.snapshot)G.remember(j.snapshot);return K}U=D,j=O}return K},q={namespace:J,read:H,subscribe:W.subscribe,async commit(F,U){B.assertWritable();let j,K,N=()=>{if(B.didCommit(K)&&j)G=new V2,G.remember(j.snapshot,U)};try{await X((D,O)=>{let M=P5(J,O),P=B.decode(D),L=P.snapshot;K=P.replacement;let C=!K&&G.lost(L,U),T=Y2(C?G.recover(L,U,J,Q()):L??T0(J,z),F,{now:Q(),bindings:M,authorizeEpoch:(A,x)=>A.credentialEpoch===x.credentialEpoch});return j={...T,bindings:M,authoritative:!0,degradedAgreement:C},T.snapshot},{beforePublish:()=>B.assertWritable(),onPublished:N})}catch(D){if(B.assertWritable(),D instanceof b&&(D.kind==="pending-migration"||D.kind==="load-error"))throw new L0("pool-not-ready");throw D}if(!j)throw Error("Pool limits mutator was not called");return N(),G.remember(j.snapshot,U),j}};return await H(),q}function g2($){if($&&typeof $==="object"){for(let Z of Object.values($))g2(Z);Object.freeze($)}return $}function _0($){return{opencode1:$,opencode2:$,pi:$}}var H2={action:"reselect",affinity:"always",hint:"none",defaultMs:60000},M5={...H2,action:"retain",affinity:"sticky"},T5={family:"local-auth",messageKey:"auth.no-account",retryable:!1,hostRetry:"leave"};function L6($,Z){return{auth:_0(T5),quota:_0($),incomplete:_0(Z),"model-unavailable":_0({family:"json-412",messageKey:"model-unavailable",retryable:!1,hostRetry:"veto"})}}var T6={kind:"off"},L5={requestEscape:"off",retryExhaustion:"terminal"},_5={statuses:[],attributedLimitOnly:!0},C5={family:"json-412",messageKey:"quota.pool-exhausted",retryable:!1,hostRetry:"veto"},O5=g2({unconfirmedRetainLimit:2,evidence:"per-field-overlay",markers:_0({kind:"reset",mergeLaw:"latest-evidence",defaultMs:60000}),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"on",unknown:{opencode1:{...H2,action:"retain",hint:"minimum"},opencode2:H2,pi:{...H2,action:"pass"}},shortLimit:{holdBound:"cache-ttl",preference:"same-account-first",jitter:"session-sha256"},retainBound:"none",poolWaiting:T6,execution:"host",requestExclusion:"off",advance:_0(_5),markedPool:L5,terminalMetadata:"setting-capped-fresh",terminalPolicy:"provided",refusals:L6({family:"claude-429",messageKey:"quota.all-accounts",retryable:!0,hostRetry:"leave"},{family:"claude-econnreset",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),S5=g2({evidence:"typed",markers:_0(H9),readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:_0(H2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:{kind:"earliest",budgetMs:300000,requestDeadlineMs:600000,hardFallbackMs:60000,singleEligibleSoftExemption:!0},execution:"engine",requestExclusion:"on",advance:_0({statuses:[429,503,529],attributedLimitOnly:!1}),markedPool:L5,terminalMetadata:"baseline",terminalPolicy:"pool",refusals:L6(C5,{...C5,messageKey:"incomplete.timeout"})}),o0=g2({evidence:"named-window",markers:{opencode1:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},opencode2:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},pi:T6},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:{opencode1:M5,opencode2:H2,pi:M5},shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:T6,execution:"host",requestExclusion:"off",advance:_0({statuses:[401,403,429],attributedLimitOnly:!1}),markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"same-host-delay"},terminalMetadata:"baseline",terminalPolicy:"provided",refusals:L6({family:"openai-429",messageKey:"quota.no-route",retryable:!0,hostRetry:"leave"},{family:"openai-429",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),A5=g2({evidence:"hints-only",markers:{opencode1:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"},opencode2:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"marker"},pi:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"}},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:_0(H2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:T6,execution:"host",requestExclusion:"off",advance:{opencode1:{statuses:[401,429],attributedLimitOnly:!1},opencode2:_5,pi:{statuses:[401,429],attributedLimitOnly:!1}},markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"host-delay"},terminalMetadata:"baseline",terminalPolicy:"status-history",terminalStatusHistory:{minRetryMs:1000,defaultRetryMs:60000,paymentBalance:{family:"claustrum-402",messageKey:"payment.insufficient-balance"}},refusals:L6({family:"claustrum-429",messageKey:"quota.accounts-rate-limited",retryable:!0,hostRetry:"leave"},{...T5,messageKey:"incomplete.no-account"})}),xX=g2({"confirmed-affinity":O5,"earliest-pool-engine":S5,"window-router":o0,"status-vault-order":A5});import{AsyncResource as yX}from"node:async_hooks";var O6=Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1"),gX="@cortexkit/common-auth/limits-registry/schema-v",_6=1000,E5=5000,U2=new yX("common-auth-limits"),fX={now:()=>Date.now(),setTimeout($,Z){let J=setTimeout($,Z);return J.unref?.(),J},clearTimeout:($)=>clearTimeout($)};function vX(){for(let J of Object.getOwnPropertySymbols(globalThis))if(Symbol.keyFor(J)?.startsWith(gX)&&J!==O6)throw Error("limits-schema-mismatch");let $=Reflect.get(globalThis,O6);if($){if($.schemaVersion!==1||!($.namespaces instanceof Map))throw Error("limits-schema-mismatch");return $}let Z={schemaVersion:1,namespaces:new Map};return Reflect.set(globalThis,O6,Z),Z}function q2($){return JSON.stringify([$.producerId,$.operationId])}class R5{adapter;clock;restrictive;listeners=new Set;owners=0;activity=j6();journal=new Map;failed=new Set;restrictions=new Map;snapshot;recoveryView;bindings=[];lastReloadAt=Number.NEGATIVE_INFINITY;lastActivity=Number.NEGATIVE_INFINITY;lastReadAttempt=Number.NEGATIVE_INFINITY;generation=0;degradedAgreement=!1;abandoned;lastFailure;dirty=!0;live=!1;publicationTimer;reloadTimer;unsubscribe;reading;writing;handoff=Promise.resolve();resolveAbandonment;abandonment=new Promise(($)=>{this.resolveAbandonment=$});constructor($){this.adapter=$.adapter,this.clock=$.clock??fX,this.restrictive=$.isAccessRestrictive}fail($){if(this.abandoned)return;let Z=J9($);if(Z){this.abandoned=Z,this.lastFailure=$,this.live=!1,this.generation++,this.cancelTimers(),this.unsubscribe?.(),this.unsubscribe=void 0,this.journal.clear(),this.failed.clear(),this.restrictions.clear(),this.recoveryView=void 0,this.resolveAbandonment();for(let J of this.listeners)try{J.onAbandon?.(Z)}catch{}return}this.degradedAgreement=!0,this.lastFailure=$}reconcile($){if(this.abandoned)return!1;if($.snapshot.schemaVersion!==1||$.snapshot.namespace!==this.adapter.namespace)throw Error("limits-schema-mismatch");if(!$.authoritative){if($.degradedAgreement&&this.snapshot&&$.snapshot.revision>this.snapshot.revision)this.recoveryView=$;return this.fail(Error("limits-unverifiable-snapshot")),!1}if(this.snapshot&&$.snapshot.generation===this.snapshot.generation&&$.snapshot.revision<this.snapshot.revision)return!1;this.snapshot=$.snapshot,this.recoveryView=void 0,this.bindings=$.bindings.map((Z)=>{let J=this.bindings.find((X)=>R(X.account,Z.account));return J?Y9(J,Z):Z});for(let[Z,J]of this.restrictions){let X=J.command,z=this.bindings.find((B)=>R(B.account,X.binding.account)),G=this.snapshot.access.find((B)=>R(B.account,X.binding.account));if(!z||!w0(z,X.binding)||X.type==="access"&&G&&G.committedRevision>J.revision&&G.eligibilityStateUpdatedAt>=X.eligibilityStateUpdatedAt)this.restrictions.delete(Z)}if($.degradedAgreement)this.fail(Error("limits-envelope-recovered"));return!$.degradedAgreement}touch(){this.lastActivity=this.clock.now(),this.armReload()}cancelTimers(){if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);if(this.reloadTimer!==void 0)this.clock.clearTimeout(this.reloadTimer);this.publicationTimer=this.reloadTimer=void 0}schedulePublish($){if(!this.live)return;if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);U2.runInAsyncScope(()=>{this.publicationTimer=this.clock.setTimeout(()=>{this.publicationTimer=void 0,U2.runInAsyncScope(()=>{this.flush()})},$)})}armReload(){if(!this.live||this.reading||this.reloadTimer!==void 0||this.clock.now()-this.lastActivity>=E5)return;U2.runInAsyncScope(()=>{this.reloadTimer=this.clock.setTimeout(()=>{if(this.reloadTimer=void 0,!this.live||this.clock.now()-this.lastActivity>=E5)return;U2.runInAsyncScope(()=>{this.reload()})},Math.max(0,this.lastReadAttempt+_6-this.clock.now()))})}async start($){if(this.abandoned)throw this.lastFailure;this.adapter=$,this.live=!0;let Z=++this.generation;if(await this.reload(),this.abandoned||!this.snapshot)throw this.lastFailure??Error("limits-hydration-failed");if(this.unsubscribe=$.subscribe?.(()=>{if(!this.live||this.generation!==Z)return;this.dirty=!0,U2.runInAsyncScope(()=>{this.reload()})}),this.journal.size)this.schedulePublish(0)}reload(){if(this.abandoned)return Promise.resolve();if(this.reading)return this.reading;let $=this.clock.now();return this.lastReadAttempt=$,this.reading=U2.runInAsyncScope(async()=>{try{if(this.dirty=!1,this.reconcile(await this.adapter.read(this.snapshot))){if(this.lastReloadAt=$,!this.journal.size&&!this.failed.size&&!this.restrictions.size)this.degradedAgreement=!1,this.lastFailure=void 0}}catch(Z){this.dirty=!0,this.fail(Z)}}).finally(()=>{this.reading=void 0,this.armReload()}),this.reading}provisional(){if(this.abandoned)return T0(this.adapter.namespace,this.snapshot?.generation??"");let $=this.recoveryView?.snapshot??this.snapshot,Z=[...this.journal.values()].map((X)=>X.command).filter((X)=>X.type==="mark"),J=Y2(W2($,this.clock.now()),Z,{now:this.clock.now(),bindings:this.bindings,authorizeEpoch:(X,z)=>X.credentialEpoch===z.credentialEpoch}).snapshot;return{...this.snapshot,marks:J.marks,tombstones:$.tombstones,access:$.access}}enqueue($,Z){if(this.abandoned)return;if($.binding.account.namespace!==this.adapter.namespace)throw Error("wrong-namespace");let J=q2($);if(this.journal.has(J)||this.snapshot.operationIds.some((z)=>q2(z)===J))return;this.journal.set(J,{command:structuredClone($),event:Z}),this.touch();let X=[...this.journal.values()].some((z)=>z.command.type!=="mark");this.schedulePublish(X?0:_6)}flush(){if(this.abandoned)return this.writing??Promise.resolve();if(this.writing)return this.writing;if(!this.journal.size)return Promise.resolve();return this.writing=U2.runInAsyncScope(async()=>{let $=[...this.journal.values()];while($.length&&!this.abandoned){try{let X=await this.adapter.commit($.map((z)=>z.command),this.snapshot);if(this.abandoned)return;if(this.reconcile(X),!X.authoritative)throw Error("limits-unverifiable-commit");for(let z of $){let G=X.outcomes.find((B)=>q2(B)===q2(z.command));if(!G)throw Error("limits-missing-acknowledgement");this.settle(z,G)}}catch(X){if(J9(X)){this.fail(X);return}if(this.abandoned)return;if(X instanceof L0&&X.code==="pool-not-ready")for(let z of $)this.settle(z,{...z.command,status:"rejected",reason:"pool-not-ready"});else{for(let z of $)if(this.journal.has(q2(z.command)))this.failed.add(q2(z.command));this.fail(X);break}}let Z=[...this.journal.values()],J=Z.findLastIndex((X)=>X.command.type!=="mark");$=Z.slice(0,J+1)}}).finally(()=>{if(this.writing=void 0,this.journal.size&&this.live)this.schedulePublish(_6);if(this.degradedAgreement&&this.live)this.armReload()}),this.writing}settle($,Z){let J=$.command,X=q2(J);if(this.journal.delete(X),this.failed.delete(X),Z.status==="rejected"){if(this.fail(Error(Z.reason??"limits-command-rejected")),J.type==="access"&&this.restrictive(J.state)){if(this.restrictions.set(X,{command:J,revision:this.snapshot.revision}),Z.reason==="below-watermark"&&J.baseRevision<this.snapshot.lowWatermark&&($.recoveryRetries??0)<3)this.journal.set(X,{...$,recoveryRetries:($.recoveryRetries??0)+1,command:{...J,baseRevision:this.snapshot.revision}})}for(let z of this.listeners)try{z.onRejected?.(J,Z)}catch{}}else if(Z.revision!==void 0&&(J.type==="mark"||$.event==="success"))for(let z of this.listeners)try{z.onEvent?.({type:J.type==="mark"?"mark":"success",command:J,revision:Z.revision})}catch{}}async beforeDispatch($){if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};this.touch();let Z=()=>[...this.journal.values()].some((z)=>z.command.type!=="mark"&&R(z.command.binding.account,$.account));if(Z())await Promise.race([this.flush(),this.abandonment]);if(this.dirty||this.clock.now()-this.lastReloadAt>=_6)await Promise.race([this.reload(),this.abandonment]);if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};let J=(this.recoveryView?.bindings??this.bindings).find((z)=>R(z.account,$.account)),X=this.provisional();return{snapshot:X,blocked:Z()||!J||!w0(J,$)||[...this.restrictions.values()].some((z)=>R(z.command.binding.account,$.account))||[...this.snapshot.access,...X.access].some((z)=>R(z.account,$.account)&&this.restrictive(z.state))}}async stop(){this.live=!1,this.generation++,this.cancelTimers(),await this.flush(),await this.reading,this.unsubscribe?.(),this.unsubscribe=void 0,this.cancelTimers()}}async function j9($){let Z=vX(),J=Z.namespaces.get($.adapter.namespace);if(!J)J=new R5($),Z.namespaces.set($.adapter.namespace,J);let X=J,z={onAbandon:$.onAbandon,onEvent:$.onEvent,onRejected:$.onRejected},G=X.owners++===0;if(X.listeners.add(z),G)X.handoff=X.handoff.catch(()=>{}).then(()=>X.start($.adapter));try{await X.handoff}catch(Q){throw X.listeners.delete(z),X.owners--,X.live=!1,X.cancelTimers(),Q}let B=!1,W=()=>{if(B)throw Error("limits-registry-disposed")};return{get abandoned(){return X.abandoned},get snapshot(){return W(),X.provisional()},get lastReloadAt(){return X.lastReloadAt},get degradedAgreement(){return X.degradedAgreement},get lastFailure(){return X.lastFailure},get pendingCommands(){return X.journal.size},activity:X.activity,observe(Q){return W(),{binding:structuredClone(Q),baseRevision:X.snapshot.revision}},enqueue(Q,Y){W(),X.enqueue(Q,Y)},beforeDispatch(Q){return W(),X.beforeDispatch(Q)},flush(){return W(),X.flush()},reload(){return W(),X.reload()},dispose(){if(B)return X.handoff;if(B=!0,X.owners--,!X.owners)X.handoff=X.handoff.then(()=>X.stop()).finally(()=>X.listeners.delete(z));else X.listeners.delete(z);return X.handoff}}}function t0($){let Z=Reflect.get(globalThis,Symbol.for("cortexkit.routing"));if(typeof Z!=="function")return;let J=Z($);return typeof J==="object"&&J!==null?J:void 0}function F9($){try{let J=t0($.sessionId);if(!J||typeof J.accountFor!=="function")return}catch{return}let Z=Y4($);if(!Z||!Number.isFinite($.now))return 0;return Math.floor(Math.max(0,Math.min(Z.maxWaitMs,Z.cacheExpiresAt-$.now))/1000)}function E($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as wX}from"node:fs";import{rm as k5}from"node:fs/promises";import{dirname as uX,join as l5}from"node:path";import{resolveClaustrumConnectionPath as pX}from"@cortexkit/claustrum-client";function I5($,Z){if(!$)return;let J=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function K9($){if(!E($)||typeof $.minor!=="number"||!Number.isSafeInteger($.minor)||typeof $.exponent!=="number"||!Number.isInteger($.exponent))return;let Z=$.minor/10**$.exponent;return Number.isFinite(Z)?Z:void 0}function hX($){let Z=K9($.total),J=K9($.remaining);if(Z===void 0||J===void 0||Z<0||J<0)return;let X=Z-J,z=$.spendable===!1,G=Z>0?X/Z*100:z?100:0;return{limit:Z,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...E($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function mX($,Z){if(!E($))return;let J=K9($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function N9($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&E(Z)&&E(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function b5($,Z){let J=I5($.usage?.primary,Z.fetchedAt);if(!J||!Number.isFinite(Z.fetchedAt))return;let X=I5($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((Y)=>E(Y)&&Y.id==="individual_limit"):void 0,G=E(z)?hX(z):void 0,B=Array.isArray($.spend)?$.spend.find((Y)=>E(Y)&&Y.id==="credits"):void 0,W=mX(B,Z.fetchedAt),Q=E($.savedResets)?$.savedResets.availableCount:void 0;return{primary:J,...W&&{credits:W},...W&&E(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof Q==="number"&&Number.isFinite(Q)&&Q>=0&&{resetCreditsAvailable:Q},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function S6($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var D9="ck auth reclassify --from-registry";function A6($,Z){if(Z===void 0)return"No ChatGPT login in the vault has the `openai-native` category, or the grant is missing. Check `ck auth status` for categories and `ck auth grant` for the grant.";if(Z.grants===0)return`The vault has no grant letting ${$} read OpenAI accounts. Grant it with \`${S6($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${D9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var Q0=o("vault"),d5="openai-auth";var lX={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},c5={opencode:"OpenCode",pi:"Pi"},dX=[{selector:{category:"openai-native"},operation:"read"}];function M9($){return g5(d5,$)}function cX($){return`ChatGPT for ${c5[$]}`}function x6($){return l5(uX($),"openai-auth-vault")}function j2($,Z){return{...v5({stateDir:$,host:Z}),rosterPath:l5($,`${Z}-roster.json`)}}var s5=2000,oU=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],sX={"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-grant-unreached":`Request refused locally: this host is connected to the credential vault, whose grant for it reaches no ChatGPT login, and local accounts are not used while it is connected. Logins without the openai-native category are not reached: run ${D9} to fill empty category sets, then check the CATEGORIES column with ck auth status. 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 tU($,Z){if($!=="vault-no-grant")return sX[$];return`Request refused locally: this host is connected to the credential vault, which has no grant letting it read OpenAI accounts, and local accounts are not used while it is connected. Disconnect this host from the vault, or grant it access with: ${S6(Z)}`}function eU($){let Z=$.snapshot();if(Z===void 0)return"vault-unreachable";if(Z.rows.length===0){let J=$.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function aX($){let Z=b6($);return Z?k6(Z):void 0}class nX{host;name;paths;#Z;#$;#Q=new Map;#W=new Map;#q=new Map;#j;#J;#Y;#z;#F=!1;#K=!1;#V=Promise.withResolvers();#H="unknown";#U;constructor($){this.#Z=$,this.host=$.host,this.name=M9($.host),this.paths=j2($.stateDir,$.host),this.#$=new u5({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:lX,pluginId:d5,connect:()=>this.#C(),isCustodyActive:()=>this.#L(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:aX,insula:{provider:"codex",normalize:b5},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onDiscovery:(Z)=>this.#_(Z),onError:(Z)=>this.#X("vault roster refresh failed",Z),logger:{...Q0,warn:(Z,J)=>{if(Z!=="skipped insula provider poll")Q0.warn(Z,J)}}})}#N(){return(this.#Z.connectionFile??pX)()}#D(){return{connectionFile:this.#N(),projectRoot:this.#Z.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>Q0.debug("vault transport error",{errorClass:$})}}#C(){return(this.#Z.connectScoped?.()??p5(this.#D())).then(($)=>{return this.#j=$.insula!==void 0,$})}#G($,Z,J){let X=this.#q.get($);if(X?.source===Z&&X.reason===J)return;this.#q.set($,{source:Z,reason:J}),Q0.info("vault background quota source changed",{routeId:$,source:Z,reason:J})}#T(){return this.#Z.connectEnrollment?.()??f5(this.#D())}#X($,Z){this.#J=x0(Z),Q0.warn($,{host:this.host,error:this.#J,...Z instanceof y5&&Z.reason?{reason:Z.reason}:{}})}#B(){if(f2())return"host";return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=wX($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#B(),Z=await h5(this.paths,this.name);if($===this.#B()){if(Z!==this.#H)Q0.info("vault authority",{host:this.host,authority:Z});return this.#H=Z,this.#U=$,Z}return"unreadable"}enrolled(){return f2()||this.#U!==this.#B()||this.#H!=="local"}async#L(){if(this.#U!==this.#B())await this.authority();return this.enrolled()}start(){if(this.#F||this.#K)return;this.#F=!0,this.#$.start()}#_($){if(this.#z===$)return;this.#z=$,$.finally(()=>{if(this.#z===$)this.#z=void 0;this.#V.resolve()}).catch(()=>{})}#P(){return this.#$.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(!["vault","host"].includes(await this.authority()))return;let $=this.#z;if($)await $.catch(()=>{return});if(this.snapshot()||!["vault","host"].includes(await this.authority()))return;await(this.#z??this.#P()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let $=this.#z;if($)await $.catch(()=>{return});let Z=await this.#P();return this.#J=void 0,Z}catch($){return this.#X("vault roster refresh failed",$),this.#$.snapshot()}}snapshot(){return this.#$.snapshot()}watchState(){return this.#$.watchState()}keptReceiptState(){return this.#$.keptReceiptState()}grantReach(){return this.#$.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap(($)=>$.accountIdentity!==void 0?[$.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let $=new Map((this.snapshot()?.rows??[]).map((Z)=>[Z.routeId,Z]));return this.#$.routingRows().map((Z)=>{let J=$.get(Z.id)?.accountIdentity;return{id:Z.id,credentialId:$.get(Z.id)?.credentialId,kind:Z.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...Z.quota!==void 0?{quota:Z.quota}:{}}})}owns($){return(this.snapshot()?.rows??[]).some((Z)=>Z.routeId===$)}async send($,Z,J){let X=!1;try{return await this.#$.send($,(z)=>{return X=!0,Z(z.accessToken,z)},{site:J.site,...J.signal?{signal:J.signal}:{}})}catch(z){if(X)throw z;this.#X("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#$.authorize($,Z.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure($,Z){if(Z!==401)return;try{await this.#$.reportFailure($,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot($,Z,J,X){let z=E6(Z,(this.#Z.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#$.recordQuota($,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}reportUsage($,Z,J){try{let X;if("headers"in Z){let z={};if(Z.headers.forEach((G,B)=>{if(B.startsWith("x-codex-"))z[B]=G}),Object.keys(z).length===0)return;X={headers:z}}else X={frame:Z.frame};this.#$.reportUsage({routeId:$,credentialId:J.credentialId,reading:{provider:"codex",observedAtMs:(this.#Z.now??Date.now)(),...X,...J.accountIdentity?{account:J.accountIdentity}:{}}})}catch{}}pollQuota($,Z=!0){let J=this.#W.get($);if(J)return J;let X=this.#O($,Z).finally(()=>{this.#W.delete($)});return this.#W.set($,X),X}async#O($,Z){if(Z){await this.authority(),await this.#$.refreshInsulaQuota();let J=(await I6(this.paths.rosterPath))?.rows.find((W)=>W.routeId===$),X,z=await this.#$.pollInsulaQuotaForRoute($,async()=>{this.#G($,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#M($,Z);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let W=E6(N9(z,this.routes().find((Y)=>Y.id===$)?.quota),z.primary.checkedAt,!0);if(!W)return this.#G($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#$.recordAccountQuota($,J.accountIdentity,W))return this.#G($,"insula",null),{ok:!0};return this.#G($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#$.lookupInsulaQuotaForRoute($),B=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G($,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#M($,Z)}async#M($,Z){let J,X=this.#Z.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,B)=>{try{let W=Z?void 0:await this.#$.cachedInsulaQuota(B);if(W!==void 0){let Y=E6(N9(W,this.routes().find((V)=>V.id===$)?.quota),W.primary.checkedAt,!0);if(!Y)throw Error("unusable insula reading");return await this.#$.recordQuota($,Y,B),new Response(null,{status:200})}let Q=await N4({accessToken:G,fetchImpl:X,now:this.#Z.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:$,logger:Q0});return await this.recordSnapshot($,Q,!0,B),J=void 0,new Response(null,{status:200})}catch(W){J=x0(W);let Q=W?.status;if(typeof Q==="number")return new Response(null,{status:Q});throw W}},{site:"quota"}).catch((G)=>{J=x0(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading($){let Z=this.#Q.get($);if(Z)return Z;let J=this.pollQuota($,!1).catch((X)=>{Q0.warn("vault quota poll failed",{routeId:$,error:x0(X)})}).finally(()=>{this.#Q.delete($)});return this.#Q.set($,J),J}async pollStale($){let Z=(this.#Z.now??Date.now)(),J=[];for(let X of this.routes()){let z=iX(X.quota);if(z!==void 0&&Z-z<$)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder($){let Z=await this.authority();if(Z!=="vault"&&Z!=="host")throw Error("Vault order can only be changed in vault mode.");return this.#$.reorder($)}async decline($){await this.#$.decline($),Q0.info("vault account declined",{routeId:$})}async accept($){await this.#$.accept($),Q0.info("vault account accepted",{routeId:$})}async status(){let $=await this.authority(),Z;try{Z=$==="host"?{state:"idle"}:await R6(this.paths,this.name)}catch(X){this.#X("vault enrollment state unreadable",X),Z={state:"blocked",proposedName:this.name,code:X instanceof x5?X.kind:"unreadable-state"}}let J=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:J!==void 0,accounts:J?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){if(await this.authority()==="host")throw new u("vault-host",P9);let $=await this.#T().catch((Z)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${x0(Z)}. Is the vault running?`)});try{let Z=new m5({client:$,paths:this.paths,proposedName:this.name,displayName:cX(this.host),requestedGrants:dX,...this.#Z.now?{now:this.#Z.now}:{}}),J=await Z.status();if(J.state==="denied"||J.state==="blocked")await Z.resetTerminal();let X=await Z.reconcile();if(Q0.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{$.close()}}waitForApproval($={}){return this.#Y??=(async()=>{let Z=$.sleep??((G)=>new Promise((B)=>setTimeout(B,G))),J=$.pollIntervalMs??2000,X=Date.now()+($.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if($.onPending?.(z),Date.now()>=X)return z;await Z(J),z=await this.connectStep()}return z})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){if(await this.authority()==="host")throw new u("vault-host",P9);await k5(this.paths.tokenPath,{force:!0}),await k5(this.paths.statePath,{force:!0}),await this.#Z.afterDisconnect?.(),await this.authority(),this.#J=void 0,Q0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())w5({mode:"custody",auth:$,provider:"openai"})}close(){this.#K=!0,this.#V.resolve(),this.#$.close()}async dispose(){this.close(),await this.#$.dispose()}}function iX($){if(!$)return;let Z=b0($).limits.map((J)=>J.checkedAt);return Z.length>0?Math.max(...Z):void 0}function y6($,Z){if(Z.state!=="pending")return[];if(!Z.requestId)return[`The vault did not take the enrollment request yet${Z.retryCode?` (${Z.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${Z.requestId} for ${$} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${Z.requestId}`,...Z.requestedGrantsStatus==="sent"?[]:[`Then grant OpenAI access to the name you approved with --name (defaults to ${$}):`,` ${S6($)}`]]}function a5($,Z,J){let X=`${c5[$]} (${J.state==="approved"?J.approvedName??Z:Z})`;switch(J.state){case"approved":return`${X}: connected to the Claustrum vault.`;case"idle":return`${X}: not connected to the Claustrum vault.`;case"pending":return J.requestId?`${X}: waiting for approval of request ${J.requestId}.`:`${X}: enrollment request not taken yet${J.retryCode?` (${J.retryCode})`:""}.`;case"denied":return`${X}: the vault denied the enrollment request.`;case"blocked":return`${X}: enrollment stopped (${J.code}).`;case"unavailable":return`${X}: the vault is unavailable (${J.code}).`;case"busy":return`${X}: another process is enrolling right now.`}}function C9($,Z){if((Z.state==="blocked"||Z.state==="unavailable")&&Z.code==="unknown_method")return{ok:!1,text:'Enrollment stopped (unknown_method). This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), then run Connect again.'};switch(Z.state){case"approved":{let J=Z.approvedName??$.name,X=$.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${J}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?`. ${A6(J,$.grantReach())}`:"."}`}}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 (${Z.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...y6($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
|
|
2
|
+
`)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var T9="/backend-api/wham/rate-limit-reset-credits",rX=`https://chatgpt.com${T9}`,e5=`${T9}/consume`,oX=`https://chatgpt.com${e5}`,tX=300000,eX=60000,$z=15000,Zz=60000;function v2($){return{configPath:$.configPath,statePath:$.statePath}}class W0 extends Error{kind;cooldownUntil;constructor($,Z,J){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=J}}class F2 extends Error{kind;status;constructor($,Z,J){super(Z);this.name="ResetCreditError",this.kind=$,this.status=J}}function $Z($,Z,J){return{authorization:`Bearer ${$}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function f6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function ZZ($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function v6($){if(!f6($)||typeof $.redeemRequestId!=="string"||$.redeemRequestId.length===0||typeof $.creditId!=="string"||$.creditId.length===0||typeof $.startedAt!=="number"||!Number.isFinite($.startedAt)||$.chatgptAccountId!==void 0&&(typeof $.chatgptAccountId!=="string"||$.chatgptAccountId.length===0))return;return{redeemRequestId:$.redeemRequestId,creditId:$.creditId,startedAt:$.startedAt,...typeof $.chatgptAccountId==="string"?{chatgptAccountId:$.chatgptAccountId}:{},...JZ($.rejectedStatus)?{rejectedStatus:$.rejectedStatus}:{},...typeof $.unknownAnswers==="number"&&Number.isSafeInteger($.unknownAnswers)&&$.unknownAnswers>0?{unknownAnswers:$.unknownAnswers}:{}}}function JZ($){return typeof $==="number"&&$>=400&&$<500&&$!==408&&$!==409&&$!==425&&$!==429}function g6($){return $.kind==="http_error"&&JZ($.status)}function XZ($,Z){return $.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z||$.rejectedStatus!==void 0}function Jz($,Z){if($.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z)throw new W0("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function zZ($){return Boolean($&&Object.hasOwn($,"inFlight"))}function GZ($,Z){return Z-$.startedAt<tX}function h2($,Z){if(!u0(Z))return;return $.reset?.[Z]}function BZ($){if(!$.reset)$.reset=Object.create(null);return $.reset}function QZ($,Z,J){if(!u0(Z))return;let X=BZ($),z=X[Z]??{},G=z.lastOutcome;delete z.inFlight,z.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[Z]=z}function WZ($,Z){let J=ZZ($),X=v6($?.inFlight);if(zZ($)&&!X)return{kind:"corrupt",beforeState:J};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:J,cooldownUntil:$.cooldownUntil};if(X&&GZ(X,Z))return{kind:"claim",beforeState:J,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:J,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:J}}async function Xz($,Z){if(!u0(Z))return{kind:"fresh",beforeState:void 0};let J=await $.loadAccountsFn(v2($));return WZ(J?h2(J,Z):void 0,$.now())}async function zz($,Z){let J;if(await $.mutateAccountsFn((X)=>{let z=$.now(),G=h2(X,Z);if(J=WZ(G,z),J.kind==="corrupt")QZ(X,Z,z);return X},v2($)),!J)throw Error("corrupt reset state mutation did not run");return J}async function Gz($,Z,J,X){if(!u0(Z))return{kind:"fresh",beforeState:void 0};let z;if(await $.mutateAccountsFn((G)=>{let B=$.now(),W=h2(G,Z),Q=ZZ(W),Y=v6(W?.inFlight);if(zZ(W)&&!Y)return QZ(G,Z,B),z={kind:"corrupt",beforeState:Q},G;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>B)return z={kind:"cooldown",beforeState:Q,cooldownUntil:W.cooldownUntil},G;if(Y&&GZ(Y,B))return z={kind:"claim",beforeState:Q,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}},G;if(Y&&!XZ(Y,X))return z={kind:"expired_unreconciled",beforeState:Q,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}},G;let V=h6(J);if(!V)return z={kind:"fresh",beforeState:Q},G;let H={redeemRequestId:$.randomUUID(),creditId:V.id,startedAt:B,...X===void 0?{}:{chatgptAccountId:X}},q=BZ(G);return q[Z]={...W,inFlight:H},z={kind:"claim",beforeState:Q,claim:{inFlight:H,selectedCredit:V}},G},v2($)),!z)throw Error("reset claim mutation did not run");return z}async function Bz($,Z,J,X,z){if(!u0(Z))return;if(!O9(X.kind))return Qz($,Z,J,X,z);await $.mutateAccountsFn((G)=>{let B=h2(G,Z),W=v6(B?.inFlight);if(!B||!W||W.redeemRequestId!==J.redeemRequestId||W.creditId!==J.creditId)return G;let Q=$.now();if(delete B.inFlight,B.lastOutcome={code:X.kind,at:Q},X.kind==="reset"||X.kind==="already_redeemed")B.cooldownUntil=Q+Zz;else delete B.cooldownUntil;return G},v2($));return}function n5($,Z){let J=v6($?.inFlight);return J&&J.redeemRequestId===Z.redeemRequestId&&J.creditId===Z.creditId?J:void 0}async function Qz($,Z,J,X,z){let G=g6(X)?X.status:void 0;if(!(J.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===J.rejectedStatus){let Q=await $.loadAccountsFn(v2($));return n5(Q?h2(Q,Z):void 0,J)}let W;return await $.mutateAccountsFn((Q)=>{W=void 0;let Y=h2(Q,Z),V=n5(Y,J);if(!Y||!V)return Q;let H={...V};if(H.chatgptAccountId===void 0&&z!==void 0)H.chatgptAccountId=z;if(G===void 0)delete H.rejectedStatus,H.unknownAnswers=(V.unknownAnswers??0)+1;else if((V.unknownAnswers??0)===(J.unknownAnswers??0))H.rejectedStatus=G;return Y.inFlight=H,W=H,Q},v2($)),W}function D4($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let J=Date.parse($.resetsAt);return!Number.isFinite(J)||J>Z}function L9($,Z,J){if(!(Z||D4($.primary,J)||D4($.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function i5($,Z){let J=$[Z];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function Wz($){if(!f6($))return;let Z=i5($,"granted_at"),J=i5($,"reset_type");if(typeof $.id!=="string"||typeof $.status!=="string"||typeof $.expires_at!=="string"||Number.isNaN(Date.parse($.expires_at))||typeof $.is_supported_by_plan!=="boolean"||Z===null||J===null)return;return{id:$.id,status:$.status,...Z===void 0?{}:{grantedAt:Z},expiresAt:$.expires_at,...J===void 0?{}:{resetType:J},isSupportedByPlan:$.is_supported_by_plan}}async function _9($,Z,J){let X;try{X=await $(rX,{method:"GET",headers:$Z(Z,T9,J),signal:AbortSignal.timeout($z)})}catch{throw new F2("http_error","reset credit list request failed")}if(!X.ok)throw new F2("http_error",`reset credit list request failed: ${X.status}`,X.status);let z;try{z=await X.json()}catch{throw new F2("invalid_response","reset credit list response was not valid JSON",X.status)}if(!f6(z))throw new F2("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((B)=>{let W=Wz(B);return W===void 0?[]:[W]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function h6($){return[...$].filter(YZ).sort((Z,J)=>Date.parse(Z.expiresAt)-Date.parse(J.expiresAt))[0]}function YZ($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function VZ($){return $.filter(YZ).length}function O9($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function Yz($,Z,J,X,z){let G;try{G=await $(oX,{method:"POST",headers:{...$Z(Z,e5,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:X}),signal:AbortSignal.timeout(eX)})}catch(Y){return{kind:"ambiguous",raw:Y}}let B;try{B=await G.text()}catch(Y){return G.ok?{kind:"ambiguous",raw:Y}:{kind:"http_error",raw:Y,status:G.status}}let W=B,Q=!1;try{W=JSON.parse(B),Q=!0}catch{}if(!G.ok)return{kind:"http_error",raw:W,status:G.status};if(!Q||!f6(W)||!O9(W.code))return{kind:"ambiguous",raw:W};return{kind:W.code,raw:W}}function r5($){if($.kind==="cooldown")throw new W0("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function o5(){throw new W0("expired_unreconciled","the previous reset attempt outcome is unknown")}function t5($,Z){return{target:$,selectedCredit:void 0,beforeState:Z,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function Vz($){if($.kind==="reset"||$.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if($.kind==="nothing_to_reset"||$.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(g6($))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 Hz($,Z){if($)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(Z)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 HZ($,Z){if(!u0(Z.accountKey))throw new W0("invalid_account_key","the reset account key is reserved");let J=await $.resolveTarget(Z.accountKey);if(J.chatgptAccountId!==Z.expectedChatgptAccountId)throw new W0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=J.chatgptAccountId,z=J.accountKey==="main"?void 0:X,G=await Xz($,Z.accountKey);if(G.kind==="corrupt"){if(G=await zz($,Z.accountKey),G.kind==="corrupt")return t5(J,G.beforeState)}if(G.kind==="cooldown")r5(G);let B;if(G.kind==="claim")B=G.claim;else if(G.kind==="expired_unreconciled"&&(Z.retry||!XZ(G.claim.inFlight,X))){if(!Z.retry)o5();B=G.claim}else{if(Z.retry)throw new W0("retry_without_inflight","there is no active reset credit redemption to retry");let[q,F]=await Promise.all([$.fetchUsage(J),_9($.fetchImpl,J.accessToken,z)]),U=L9(q,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!U.ok)throw new W0("not_exhausted",U.reason);if(!h6(F.credits))throw new W0("no_eligible_credit","no eligible reset credit was returned");let j=await Gz($,Z.accountKey,F.credits,X);if(j.kind==="corrupt")return t5(J,j.beforeState);if(j.kind==="cooldown")r5(j);if(j.kind==="expired_unreconciled")o5();if(j.kind!=="claim")throw new W0("no_eligible_credit","no eligible reset credit was available while claiming");B=j.claim}Jz(B.inFlight,X);let W=await Yz($.fetchImpl,J.accessToken,z,B.inFlight.creditId,B.inFlight.redeemRequestId),Q,Y=!1;try{Q=await Bz($,Z.accountKey,B.inFlight,W,X)}catch{Y=!0}let V=Y&&O9(W.kind),H=g6(W)&&!Y&&Q?.rejectedStatus!==void 0;return{target:J,selectedCredit:B.selectedCredit,beforeState:G.beforeState,outcome:W,retrySafety:V?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":g6(W)&&!H?Hz(Y,Q):Vz(W),...H?{refused:!0}:{},...V?{finalizeStateWriteFailed:!0}:{}}}async function UZ($){let Z=[];for(let J of $)try{Z.push(...await J.run())}catch(X){Z.push({code:"doctor-check-failed",message:`Check ${J.id} failed: ${X instanceof Error?X.message:String(X)}`})}return{findings:Z}}function qZ($,Z){let J=[$];if(Z.findings.length===0)return J.push("No problems found."),J;for(let X of Z.findings){let z=X.repair?" (repair available)":"";J.push(`- ${X.message}${z}`)}return J}async function jZ($,Z){let J={applied:[],declined:[],failed:[]};for(let X of Z.findings){let z=X.repair;if(!z)continue;if(!await $.confirm(`Apply repair: ${z.label}?`)){J.declined.push(X);continue}try{await z.apply(),J.applied.push(X)}catch(G){J.failed.push({finding:X,error:G}),$.print(`Repair failed: ${z.label}: ${G instanceof Error?G.message:String(G)}`)}}return J}function S9($){let Z=$.title??"Auth doctor";return{id:"doctor",label:$.label??"Auth doctor",hint:"check accounts and offer repairs",async run(J){let X=await UZ($.checks);for(let B of qZ(Z,X))J.print(B);let z=X.findings.filter((B)=>B.repair);if(z.length===0){if(X.findings.length>0)J.print("No repairs are available.");return}let G=await jZ(J,X);J.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as Uz}from"node:child_process";function KZ($,Z=process.platform,J=Uz){try{if(Z==="win32"){let z=`Start-Process '${$.replaceAll("'","''")}'`,G=J("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(z,"utf16le").toString("base64")],{stdio:"ignore",windowsHide:!0});return G.on("error",()=>{}),G.unref(),G.pid!==void 0}let X=J(Z==="darwin"?"open":"xdg-open",[$],{stdio:"ignore"});return X.on("error",()=>{}),X.unref(),X.pid!==void 0}catch{return!1}}function FZ($,Z){if($.print(""),$.print("Open this URL in your browser and complete sign-in:"),$.print(""),$.print(Z.url),$.print(""),Z.instructions)$.print(Z.instructions),$.print("")}async function m6($,Z){let J=new AbortController,X=await $.begin({headless:!1,signal:J.signal});X.completion.catch(()=>{}),FZ(Z,X);let z=!1;try{z=await($.openBrowser??KZ)(X.url)!==!1}catch{z=!1}if(!z)J.abort(),Z.print("Could not open a browser. Switching to device authorization."),Z.print(""),X=await $.begin({headless:!0}),FZ(Z,X);return X.completion}var k={hide:"\x1B[?25l",show:"\x1B[?25h",up:($=1)=>`\x1B[${$}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:($,Z)=>`\x1B[${$};${Z}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function A9($){let Z=$.toString(),J=[];for(let X=0;X<Z.length;){let z=Z[X];if(z==="\x1B"){let G=Z.slice(X,X+3),B=G[1]==="["||G[1]==="O"?G[2]:void 0;if(B&&"ABCD".includes(B)){let Q={A:"up",B:"down",C:"right",D:"left"}[B];if(Q)J.push(Q);X+=3}else if(X+1===Z.length){if(X===0)J.push("escape-start");X+=1}else if((Z[X+1]==="["||Z[X+1]==="O")&&X+2>=Z.length)break;else X+=1;continue}if(z==="\r"||z===`
|
|
3
|
+
`)J.push("enter");else if(z==="\x03")J.push("escape");else if(z&&z>=" ")J.push("char");X+=1}return J}var NZ=`${String.fromCharCode(27)}\\[[0-9;]*m`,qz=new RegExp(NZ,"g"),jz=new RegExp(`^${NZ}`);function DZ($){return $.replace(qz,"")}function K2($,Z){if(Z<=0)return"";if(DZ($).length<=Z)return $;let J=Z>=3?"...":".".repeat(Z),X=Math.max(0,Z-J.length),z="",G=0,B=0;while(G<$.length&&B<X){if($[G]==="\x1B"){let W=$.slice(G).match(jz);if(W){z+=W[0],G+=W[0].length;continue}}z+=$[G],G+=1,B+=1}return z.includes("\x1B[")?`${z}${k.reset}${J}`:z+J}function E9(){return{input:process.stdin,output:process.stdout,signals:process}}function N2($){return $.input.isTTY===!0}function R9($,Z=""){$.output.write(`${Z}
|
|
4
4
|
`)}var Fz=50;function Kz($){if($==="red")return k.red;if($==="cyan")return k.cyan;return""}async function m2($,Z,J){if(!N2($))throw Error("Interactive select requires a TTY terminal");if(Z.length===0)throw Error("No menu items provided");let{input:X,output:z,signals:G}=$,B=0,W=null,Q=!1,Y=0,V=()=>{let H=z.columns??80,q=z.rows??24,F=Y;if(J.clearScreen)z.write(k.clearScreen+k.moveTo(1,1));else if(F>0)z.write(k.up(F));let U=0,j=(L)=>{z.write(`${k.clearLine}${L}
|
|
5
|
-
`),U+=1},K=J.lines??[],N=1+(J.subtitle?3:0)+K.length+(K.length?1:0),D=Math.max(1,Math.min(Z.length,q-N-2-1)),O=Math.max(0,Math.min(B-Math.floor(D/2),Math.max(0,Z.length-D))),M=Z.slice(O,O+D);if(j(`${k.dim}┌ ${k.reset}${K2(J.message,Math.max(1,H-4))}`),J.subtitle)j(`${k.dim}│${k.reset}`),j(`${k.cyan}◆${k.reset} ${K2(J.subtitle,Math.max(1,H-4))}`),j("");for(let L of K)j(`${k.cyan}│${k.reset} ${K2(L,Math.max(1,H-4))}`);if(K.length)j(`${k.cyan}│${k.reset}`);for(let L=0;L<M.length;L++){let C=M[L];if(!C)continue;let T=O+L===B,A=Kz(C.color),x=A?`${T?"":k.dim}${A}${C.label}${k.reset}`:T?C.label:`${k.dim}${C.label}${k.reset}`;if(C.hint)x+=` ${k.dim}${C.hint}${k.reset}`;x=K2(x,Math.max(1,H-8)),j(T?`${k.cyan}│${k.reset} ${k.green}●${k.reset} ${x}`:`${k.cyan}│${k.reset} ${k.dim}○${k.reset} ${x}`)}let P=M.length<Z.length?` (${O+1}-${O+M.length}/${Z.length})`:"";j(`${k.cyan}│${k.reset} ${k.dim}${K2(`Up/Down to select | Enter: confirm | Esc: back${P}`,Math.max(1,H-6))}${k.reset}`),j(`${k.cyan}└${k.reset}`);for(let L=U;L<F;L++)j("");Y=U};return new Promise((H)=>{let q=X.isRaw??!1,F=()=>{if(Q)return;if(Q=!0,W)clearTimeout(W);X.removeListener("data",K);try{X.setRawMode(q),X.pause(),z.write(k.show)}catch{}G?.removeListener("SIGINT",j),G?.removeListener("SIGTERM",j)},U=(N)=>{F(),H(N)},j=()=>U(null),K=(N)=>{for(let D of A9(N)){if(Q)break;if(W)clearTimeout(W),W=null;switch(D){case"up":B=(B-1+Z.length)%Z.length,V();break;case"down":B=(B+1)%Z.length,V();break;case"enter":U(Z[B]?.value??null);break;case"escape":U(null);break;case"escape-start":W=setTimeout(()=>U(null),Fz);break;default:break}}};G?.once("SIGINT",j),G?.once("SIGTERM",j);try{X.setRawMode(!0)}catch{F(),H(null);return}X.resume(),z.write(k.hide),V(),X.on("data",K)})}async function I9($,Z,J=!1){if(!N2($))return!1;return await m2($,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Z})??!1}function DZ($){let Z=N2($);return{terminal:$,interactive:Z,print:(J)=>R9($,J),confirm:(J,X)=>I9($,J,X),select:async(J,X)=>Z&&J.length>0?m2($,J,X):null}}function Nz($,Z){if($.print(Z.title),Z.subtitle)$.print(Z.subtitle);for(let J of Z.status??[])$.print(` ${J}`);$.print(""),$.print("Actions:");for(let J of Z.actions)$.print(J.hint?` - ${J.label} (${J.hint})`:` - ${J.label}`);return $.print(""),$.print("This menu needs an interactive terminal to choose an action; nothing was changed."),{status:"not-interactive"}}async function P4($){let Z=$.terminal??E9(),J=DZ(Z);if(!J.interactive)return Nz(J,$);if($.actions.length===0)return J.print("No actions are available."),{status:"cancelled"};let X=await m2(Z,$.actions.map((z)=>({label:z.label,value:z,color:z.destructive?"red":"cyan",...z.hint?{hint:z.hint}:{}})),{message:$.title,subtitle:$.subtitle??"Select an account action",...$.status?{lines:$.status}:{},clearScreen:!0});if(!X)return{status:"cancelled"};if(X.destructive&&!await J.confirm(X.confirm??`${X.label}?`))return J.print("Cancelled; nothing was changed."),{status:"declined",action:X.id};try{return await X.run(J),{status:"ran",action:X.id}}catch(z){return J.print(`${X.label} failed: ${z instanceof Error?z.message:String(z)}`),{status:"failed",action:X.id,error:z}}}var MZ="disabled from the auth menu",PZ=8;async function y0($){let Z=await $.read();if(Z.status==="ready")return{rows:Z.rows};if(Z.status==="pending-migration")return{rows:[],problem:"The account store has not been migrated yet."};return{rows:[],problem:`The account store could not be read (${Z.file}: ${Z.reason}).`}}async function Dz($){let{rows:Z}=await y0($);return Z.some((J)=>J.credential!==void 0)}function x9($){let Z=[];if($.label)Z.push($.label);if($.invalid)Z.push(`invalid ${$.invalid}`);else if(!$.enabled)Z.push($.disabledReason?`disabled: ${$.disabledReason}`:"disabled");else Z.push("enabled");if(!$.credential&&!$.invalid)Z.push("no credential");return Z.join(", ")}function Pz($){if($.problem)return[$.problem];if($.rows.length===0)return["No accounts yet."];let Z=$.rows.slice(0,PZ).map((X)=>`${X.id}: ${x9(X)}`),J=$.rows.length-PZ;if(J>0)Z.push(`... and ${J} more`);return Z}function Mz($){return $ instanceof Error?$.message:String($)}async function y9($,Z,J){if(Z.length===0)return $.print("There are no accounts."),null;return $.select(Z.map((X)=>({label:X.id,value:X,hint:x9(X)})),{message:J})}function Cz($,Z){let J=new Set(Z.map((X)=>X.id));if($.id&&!J.has($.id))return $.id;for(let X=1;;X++){let z=`account-${X}`;if(!J.has(z))return z}}function CZ($,Z=Date.now()){let J=r0($.quota)?b0($.quota):void 0,X=m6(J,{now:Z,form:"full"});return(X.length>0?X:[I0(J,{now:Z})]).map((z)=>` ${z}`)}function TZ($){return{id:"add-account",label:"Add account",hint:"sign in to another account",async run(Z){let J=$.login;if(!J)throw Error("No login is configured");let X=await h6(J,Z),{rows:z}=await y0($.store),G=($.newAccountId??Cz)(X,z),B=await $.store.add({id:G,credential:X.credential,...X.identity!==void 0?{identity:X.identity}:{},...X.label!==void 0?{label:X.label}:{}},$.extraLocks?{extraLocks:$.extraLocks}:{});if(B.outcome==="rotated")Z.print(`That sign-in is already account ${B.id}; its credential was updated.`);else if(B.outcome==="added-disabled")Z.print(`Added account ${B.id}, disabled: another enabled account is the same provider account.`);else if(B.outcome==="completed")Z.print(`Finished adding account ${B.id}.`);else Z.print(`Added account ${B.id}.`)}}}function LZ($){return{id:"reauthenticate",label:"Re-authenticate account",hint:"sign an account in again",async run(Z){let J=$.login;if(!J)throw Error("No login is configured");let{rows:X}=await y0($.store),z=await y9(Z,X,"Re-authenticate which account?");if(!z)return;let G=await h6(J,Z);if(G.identity!==void 0&&z.identity!==void 0&&G.identity!==z.identity){Z.print(`That sign-in is a different account from ${z.id}; nothing was changed. Use Add account to add it.`);return}let B=G.identity??z.identity;await $.store.replace(z.id,G.credential,B!==void 0?{identity:B}:{},$.extraLocks?{extraLocks:$.extraLocks}:{}),Z.print(`Updated the sign-in of account ${z.id}.`)}}}function _Z($){return{...$.protect?{protect:$.protect}:{},...$.extraLocks?{extraLocks:$.extraLocks}:{}}}function OZ($){return $ instanceof b&&$.kind==="row-protected"?$.message:void 0}function SZ($){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run(Z){let{rows:J}=await y0($.store),X=await y9(Z,J,"Remove which account?");if(!X)return;if(!await Z.confirm(`Remove account ${X.id}?`)){Z.print("Cancelled; nothing was changed.");return}try{await $.store.remove(X.id,_Z($))}catch(z){let G=OZ(z);if(G===void 0)throw z;Z.print(`Account ${X.id} was kept: ${G}`);return}Z.print(`Removed account ${X.id}.`)}}}function b9($){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run(Z){let{rows:J}=await y0($.store),X=await y9(Z,J,"Enable or disable which account?");if(!X)return;let z=$.extraLocks?{extraLocks:$.extraLocks}:{};if(X.enabled){await $.store.disable(X.id,$.disableReason??MZ,z),Z.print(`Disabled account ${X.id}.`);return}try{await $.store.enable(X.id,z)}catch(G){if(G instanceof b&&G.kind==="duplicate-identity"){Z.print(`Account ${X.id} stays disabled: another enabled account is the same provider account.`);return}throw G}Z.print(`Enabled account ${X.id}.`)}}}function AZ($){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}if(J.rows.length===0)Z.print("No accounts yet.");for(let X of J.rows)Z.print(`${X.id}: ${x9(X)}`)}}}function k9($){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}let X=new Map,z=$.pollQuota;if(z)for(let B of J.rows){if(B.invalid||!B.credential||B.credentialEpoch===void 0){X.set(B.id,"no usable credential");continue}try{let W=await z(B);await $.store.recordQuota(B.id,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},W)}catch(W){X.set(B.id,Mz(W))}}let G=await y0($.store);if(G.rows.length===0)Z.print("No accounts yet.");for(let B of G.rows){Z.print(`${B.id}:`);let W=X.get(B.id);if(W)Z.print(` quota check failed: ${W}`);for(let Q of CZ(B,($.now??Date.now)()))Z.print(Q)}}}}function EZ($){return{id:"delete-all",label:"Delete all accounts",destructive:!0,confirm:"Delete every account? Accounts the plugin keeps are not deleted.",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}let X=[],z=[];for(let G of J.rows)try{await $.store.remove(G.id,_Z($)),X.push(G.id)}catch(B){let W=OZ(B);if(W===void 0)throw B;z.push(`${G.id} (${W})`)}if(Z.print(`Deleted ${X.length} account(s).`),z.length>0)Z.print(`Kept: ${z.join(", ")}.`)}}}async function g9($){return RZ($,f2()||await $.custody?.()===!0)}function RZ($,Z){let J=$.doctor?.length?[S9({checks:$.doctor})]:[],X=[...$.extraActions??[]];if(Z)return[AZ($),b9($),k9($),...J,...X];return[...$.login?[TZ($),LZ($)]:[],SZ($),b9($),k9($),...J,...X,EZ($)]}async function Tz($){let Z=f2(),J=Z||await $.custody?.()===!0,X=RZ($,J),[z,G]=await Promise.all([y0($.store),$.status?.()??[]]);return P4({title:$.title,subtitle:J?"Accounts come from the vault; select an action":"Select an account action",status:[...G,...Z?[w6]:[],...Pz(z)],actions:X,...$.terminal?{terminal:$.terminal}:{}})}function IZ(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function bZ($){return $!==void 0}function Lz($){return async(Z)=>{if(!bZ(Z))return $.login();if(!await $.hasCredential())return $.login(Z);return await $.openMenu(Z),IZ()}}function Y0($){return $.authority!=="local"}async function e($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function u6($){let Z;try{return await Promise.race([Promise.resolve().then(()=>$.refresh()).then(()=>{return},(J)=>J instanceof Error?J.message:String(J)),new Promise((J)=>{Z=setTimeout(()=>J("Vault roster refresh did not finish within the roster wait budget."),c5)})])}finally{clearTimeout(Z)}}function V0($){if($.email)return $.email;if($.credentialId==="chatgpt:openai"&&(!$.label||$.label===$.credentialId))return"main";return $.label||$.routeId}function kZ($,Z){let J=b0(r0($.quota)?$.quota:void 0),X=m6(J,{now:Z});return(X.length>0?X:[I0(J,{now:Z})]).map((z)=>` ${z}`)}var M4="Accounts are managed in the vault with ck. Disconnect to use local accounts.",D2="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function xZ($){let Z=[...$.label?[$.label]:[],$.invalid?`invalid ${$.invalid}`:$.enabled?"enabled":`disabled${$.disabledReason?`: ${$.disabledReason}`:""}`];return`${$.id}: ${Z.join(", ")}`}async function _z($,Z){let J=await u6(Z),X=await e(Z),{status:z}=X,G=Y0(X)?void 0:await $.store.read(),B=await g9($),W=new Set(["check-quotas",...($.extraActions??[]).map((V)=>V.id)]),Q=B.filter((V)=>!Y0(X)||W.has(V.id)).map((V)=>({...V,run:async(H)=>{if(!W.has(V.id)&&Y0(await e(Z))){H.print(D2);return}await Z.authority(),await V.run(H)}})),Y=Q.find((V)=>V.id==="check-quotas");if(Y)Y.run=async(V)=>{await u6(Z);let H=await e(Z),q=Y0(H)?void 0:await $.store.read();if(!q)V.print(M4);else if(q.status!=="ready")V.print("The local account store could not be read.");else for(let j of q.rows){V.print(xZ(j));try{if($.pollQuota&&j.credentialEpoch!==void 0){let D=await $.pollQuota(j);await $.store.recordQuota(j.id,{credentialEpoch:j.credentialEpoch,...j.identity!==void 0?{identity:j.identity}:{}},D)}}catch(D){V.print(` quota check failed: ${D instanceof Error?D.message:String(D)}`)}let K=await $.store.read(),N=K.status==="ready"?K.rows.find((D)=>D.id===j.id):void 0;for(let D of kZ(N??j,($.now??Date.now)()))V.print(D)}let F=H.routes;for(let j of Z.snapshot()?.rows??[]){if(V.print(`Vault ${V0(j)}: ${j.enabled?j.state:"declined"}`),!F.has(j.routeId)){V.print(" quota check skipped: account is not enabled and active");continue}let K=await Z.pollQuota(j.routeId);if(!K.ok)V.print(` quota check failed: ${K.error??"vault unavailable"}`);let N=Z.snapshot()?.rows.find((D)=>D.routeId===j.routeId);for(let D of kZ({quota:N?.quota},($.now??Date.now)()))V.print(D)}let U=await Z.status();if(U.lastError)V.print(`Claustrum vault unreachable: ${U.lastError}`)};return P4({title:$.title,subtitle:"Select an account action",status:[...await $.status?.()??[],...J?[`Last error: ${J}`]:[],...z.lastError?[`Claustrum vault unreachable: ${z.lastError}`]:[],...z.accounts.map((V)=>`Vault ${V0(V)}: ${V.enabled?`enabled (${V.state})`:"declined"}`),...!G?[M4]:G.status==="ready"?G.rows.map((V)=>xZ(V)):["The local account store could not be read."]],actions:Q,...$.terminal?{terminal:$.terminal}:{}})}function yZ($){return R($)?{...$}:{}}function f9($,Z){let J=r0(Z)?gZ(Z.credits):void 0;return J?`${$} · prepaid ${J}`:$}function vZ($,Z){return{...$,sections:$.sections.map((J)=>J.id!=="quota"?J:{...J,items:J.items.map((X)=>X.detail===void 0?X:{...X,detail:f9(X.detail,Z.get(X.id))})})}}function p6($,Z,J,X){let z=J.confirm?.irreversible?{irreversible:!0,confirm:J.confirm.message}:{...J.confirm?{confirm:J.confirm.message}:{}};return{id:J.id,label:J.label,...J.description?{description:J.description}:{},...J.group?{group:J.group}:{},knobs:J.knobs,...z,run:async({values:G,invocation:B})=>{let W=await $.apply({command:$.command,sectionId:Z,...X?{itemId:X}:{},actionId:J.id,values:G,confirmed:!0},B);return{ok:W.ok,text:W.text,...W.code?{code:W.code}:{}}}}}function v9($,Z){return new Proxy($,{get(J,X){if(X==="read")return async()=>{let G=await J.read();if(G.status!=="ready")return G;let B={...G,rows:G.rows.map((Y)=>({...Y,label:Y.label??Y.id}))};if(!Z)return B;let W=await e(Z);if(!Y0(W))return B;let Q=[...W.status.accounts.map((Y)=>({id:Y.routeId,label:V0(Y),type:"oauth",enabled:Y.enabled,identity:Y.accountIdentity,quota:Y.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:Q}};if(X==="readSettings")return async()=>{let G=await J.readSettings();if(G.status==="error"||!Z)return G;let B=await e(Z),W=yZ(G.settings.killswitch);if(!Y0(B)||!G.settings.killswitch)return G;let Q=yZ(W.accounts);for(let Y of B.status.accounts)Q[Y.routeId]=C4({version:1,accounts:[],...G.settings},Y.routeId);return{...G,settings:{...G.settings,killswitch:{...W,accounts:Q}}}};let z=Reflect.get(J,X);return typeof z==="function"?z.bind(J):z}})}function h9($,Z,J={}){let X=G2($),z=(Y)=>G2({command:$.command,title:$.title,store:v9($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:{...$.routing,formerMainId:Y??"",vaultOrder:async()=>{let V=await e(Z);if(!Y0(V))return;return{rows:V.status.accounts.map((H)=>({id:H.routeId,label:V0(H)})),reorder:async(H)=>{if(!Y0(await e(Z)))throw new u("vault-local-action",D2);return Z.reorder(H)}}}},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),G=async(Y,V)=>{let H=await e(Z),q=Y0(H),F=fZ(H.status.accounts.map((T)=>({id:T.routeId,credentialId:T.credentialId}))),U=q?z(F):X,K=(await U.open(V)).menu.sections.find((T)=>T.id===Y);if(!K)throw new u("unavailable","The account menu is unavailable.");if(!q)return{lines:K.lines,items:K.items.map((T)=>({...T,actions:T.actions.map((A)=>p6(U,Y,A,T.id))})),actions:K.actions.map((T)=>p6(U,Y,T))};let N=new Map(H.status.accounts.map((T)=>[T.routeId,T])),D=($.now??Date.now)(),O=(T)=>({id:"check",label:T?"Check this account":"Check now",group:"Actions",run:async()=>{let x=[...(await e(Z)).routes].filter((I)=>!T||I===T);if(T&&x.length===0)throw new u("unavailable","This vault account cannot be checked right now.");for(let I of x){let f=await Z.pollQuota(I);if(!f.ok)throw new u("quota-check-failed",`${I}: ${f.error??"vault unavailable"}`)}return`Checked quota for ${x.length} account${x.length===1?"":"s"}.`}});if(Y==="quota"){let T=(A,x)=>I0(b0(A.quota,$.quota?.scope),{now:D,form:x});return{lines:H.status.accounts.filter((A)=>!H.routes.has(A.routeId)).map((A)=>`${V0(A)} (${A.enabled?A.state:"disabled"}): ${f9(T(A,"compact"),A.quota)}`),items:H.status.accounts.filter((A)=>H.routes.has(A.routeId)).map((A)=>({id:A.routeId,label:V0(A),group:"Accounts",status:T(A,"compact"),detail:f9(T(A,"full"),A.quota),actions:[O(A.routeId)]})),actions:H.routes.size>0?[O()]:[]}}let M=K.items.map((T)=>{let A=N.get(T.id),x=A&&Y==="accounts"?`Vault · ${A.credentialType==="oauth"?"login":"API key"} · ${A.state} · ${A.enabled?"enabled":"declined"}`:T.detail;return{id:T.id,label:T.label,detail:x,group:T.group,status:A&&Y==="accounts"?A.enabled?A.state:"disabled":T.status,...T.facts?{facts:T.facts}:{},actions:A&&Y!=="limits"?[]:T.actions.map((I)=>p6(U,Y,I,T.id))}}),P=K.actions.filter((T)=>H.status.accounts.length>0&&(Y==="limits"||Y==="routing"&&(T.id==="mode"||T.id==="order"||T.id==="maxSameAccountWait"))).map((T)=>p6(U,Y,T)),L=K.actions.find((T)=>T.id==="mode")?.knobs.find((T)=>T.id==="mode"),C=Y==="routing"&&F===null&&L?.kind==="choice"&&(L.value==="main-first"||L.value==="fallback-first");return{lines:Y==="accounts"?[...H.status.discovered?[`${H.status.accounts.length} vault account${H.status.accounts.length===1?"":"s"}`,`${H.routes.size} can route`]:["Connected · waiting for the vault's first answer"],M4]:[...K.lines,...C?["No default vault account, so this mode orders like Ordered"]:[]],items:M,actions:P}},B=G2({...$,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(Y)=>G("accounts",Y)},quota:{title:"Quota",build:(Y)=>G("quota",Y)},routing:{title:"Routing",build:(Y)=>G("routing",Y)},limits:{title:"Limits",build:(Y)=>G("limits",Y)}},extras:$.extras?.map((Y)=>Y.id!=="reset"?Y:{...Y,build:async(V)=>{let H=await e(Z);if(Y0(H))return{lines:[M4]};return Y.build(V)}})}),W=async()=>{if(!Y0(await e(Z)))return{menu:X,error:void 0};let Y=J.refresh===!1?void 0:await u6(Z);return{menu:B,error:Y}},Q=async(Y,V)=>{let H=await Y.menu.open(V);if(Y.error)H.menu.sections.find((F)=>F.id==="vault")?.lines.push(`Last error: ${Y.error}`);return H};return{command:$.command,open:async(Y)=>Q(await W(),Y),apply:async(Y,V)=>{let H=await W(),{menu:q}=H;if(q===B&&(Y.sectionId==="accounts"||Y.sectionId==="reset"||Y.sectionId==="quota"&&(await e(Z)).routes.size===0||Y.sectionId==="limits"&&Y.itemId!==void 0&&!(await e(Z)).status.accounts.some((F)=>F.routeId===Y.itemId)))return{...await Q(H,V),ok:!1,code:"vault-local-action",text:D2};if(J.refuseApply)return{...await Q(H,V),ok:!1,...J.refuseApply};return q.apply(Y,V)}}}var L4="openai",pZ="OpenAI accounts",e0="main",lZ="that account is already your main account, so it was not added again",U0=o("commands"),dZ=new Set(["__proto__","constructor","prototype"]);function Oz($,Z){let J={version:1,accounts:[],killswitch:$},X=R($.accounts)?Object.keys($.accounts):[],z={};for(let W of new Set([e0,...Z,...X])){if(dZ.has(W))continue;let Q=C4(J,W===e0?void 0:W);z[W]={primary:Q.primary,secondary:Q.secondary}}let G=C4(J,void 0),B={...$};return delete B.main,B.accounts=z,B.defaults={primary:G.primary,secondary:G.secondary},B.schema=_4,B}function Sz($,Z){let J=R($.accounts)?{...$.accounts}:{};for(let z of new Set([e0,...Z])){if(dZ.has(z)||Object.hasOwn(J,z))continue;J[z]={primary:T4.primary,secondary:T4.secondary}}let X=R($.defaults)?$.defaults:{primary:T4.primary,secondary:T4.secondary};return{...$,accounts:J,defaults:X,schema:_4}}function hZ($,Z){let J=!1;if(R($.cachekeep))$.cacheKeep={...$.cachekeep,...R($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,J=!0;let X=$.killswitch;if(R(X)&&X.schema!==_4)$.killswitch=Oz(X,Z),J=!0;return J}async function mZ($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((J)=>J.id):[]}function u9($){let Z=async()=>{let X=await $.readSettings();if(X.status==="error")return X;let z=structuredClone(X.settings);return hZ(z,await mZ($)),{...X,settings:z}},J=async(X,z)=>{let G=await mZ($);return $.updateSettings(async(B)=>{hZ(B,G);let W=await X(B)??B;if(R(W.killswitch)&&W.killswitch.schema!==_4)W.killswitch=Sz(W.killswitch,G);return W},z)};return new Proxy($,{get(X,z){if(z==="readSettings")return Z;if(z==="updateSettings")return J;let G=Reflect.get(X,z,X);return typeof G==="function"?G.bind(X):G}})}function Az($,Z){let J=(Q,Y)=>Z.rowLocks?Z.rowLocks(Q):Y,X=(Q,Y)=>{let V=J(Q,Y?.extraLocks);return{...Y??{},...V?{extraLocks:V}:{}}},z=(Q,Y,V,H)=>$.replace(Q,Y,V,X(Q,H)),W={add:async(Q,Y)=>{let V=await $.read(),q=(V.status==="ready"?V.rows:[]).filter((K)=>K.type==="oauth"&&!K.invalid),F=Q.identity?q.find((K)=>K.identity===Q.identity):void 0;if(F?.id===e0)throw new u("main-account",lZ);let U=F??q.find((K)=>K.id===Q.id&&K.id!==e0);if(!U||Q.credential.type!=="oauth")return $.add(Q,Y);let j=await z(U.id,Q.credential,Q.identity!==void 0?{identity:Q.identity}:{},Y?.extraLocks?{extraLocks:Y.extraLocks}:void 0);return U0.info("account signed in again",{id:U.id}),{id:j.id,outcome:"rotated",credential:j.credential,credentialEpoch:j.credentialEpoch}},replace:z,enable:(Q,Y)=>$.enable(Q,X(Q,Y)),disable:(Q,Y,V)=>$.disable(Q,Y,X(Q,V)),remove:(Q,Y)=>$.remove(Q,X(Q,Y))};return new Proxy($,{get(Q,Y){if(Object.hasOwn(W,Y))return W[Y];let V=Reflect.get(Q,Y,Q);return typeof V==="function"?V.bind(Q):V}})}async function Gj($,Z,J){await u9($).updateSettings((X)=>{J(X);return},Z?{extraLocks:Z}:{})}var Ez=["version","accounts","commonAuthPool"];function Bj($,Z){return async(J)=>{let X;if(await u9($).updateSettings((z)=>{let G={...z,version:1,accounts:[]},B=J(G)??G;X=B;let W={...B};for(let Q of Ez)delete W[Q];return W},Z?{extraLocks:Z}:{}),!X)throw Error("the settings write did not run");return X}}var Rz="migration";function wZ($){let Z=["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.",$.length>0?"These processes still hold the move back:":"No running process holds the move back."],J={command:L4,title:pZ,sections:[{id:Rz,slot:"extra",title:"Accounts are moving",lines:Z,items:$.map((X,z)=>({id:`blocker-${z}`,label:X.pid==="unknown"?"processes that could not be read":`pid ${X.pid}`,detail:`version ${X.version}`,actions:[]})),actions:[]}]};return w9(J)}var Iz=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function bz($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(Iz.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function m9($,Z,J){if(Array.isArray($))return $.map((z,G)=>m9(z,`${Z}[${G}]`,J));if(!R($))return $;let X={};for(let[z,G]of Object.entries($)){if(bz(z)){J.push(`${Z}.${z}`);continue}X[z]=m9(G,`${Z}.${z}`,J)}return X}function w9($){let Z=[],J=m9($,"menu",Z);if(Z.length>0)U0.warn("credential-shaped field stripped before RPC",{fields:Z});return J}function kz($){return{id:$.id,credential:{type:"oauth",refresh:$.refresh,...$.access!==void 0?{access:$.access}:{},...$.expires!==void 0?{expires:$.expires}:{}},...$.accountId!==void 0?{identity:$.accountId}:{},...$.label!==void 0?{label:$.label}:{}}}function xz($,Z){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 X=typeof J.label==="string"&&J.label.trim().length>0?J.label.trim():void 0,z=J.headless===!0,G=await $.begin({...X!==void 0?{label:X}:{},headless:z}),B=z?`Open this verification URL:
|
|
5
|
+
`),U+=1},K=J.lines??[],N=1+(J.subtitle?3:0)+K.length+(K.length?1:0),D=Math.max(1,Math.min(Z.length,q-N-2-1)),O=Math.max(0,Math.min(B-Math.floor(D/2),Math.max(0,Z.length-D))),M=Z.slice(O,O+D);if(j(`${k.dim}┌ ${k.reset}${K2(J.message,Math.max(1,H-4))}`),J.subtitle)j(`${k.dim}│${k.reset}`),j(`${k.cyan}◆${k.reset} ${K2(J.subtitle,Math.max(1,H-4))}`),j("");for(let L of K)j(`${k.cyan}│${k.reset} ${K2(L,Math.max(1,H-4))}`);if(K.length)j(`${k.cyan}│${k.reset}`);for(let L=0;L<M.length;L++){let C=M[L];if(!C)continue;let T=O+L===B,A=Kz(C.color),x=A?`${T?"":k.dim}${A}${C.label}${k.reset}`:T?C.label:`${k.dim}${C.label}${k.reset}`;if(C.hint)x+=` ${k.dim}${C.hint}${k.reset}`;x=K2(x,Math.max(1,H-8)),j(T?`${k.cyan}│${k.reset} ${k.green}●${k.reset} ${x}`:`${k.cyan}│${k.reset} ${k.dim}○${k.reset} ${x}`)}let P=M.length<Z.length?` (${O+1}-${O+M.length}/${Z.length})`:"";j(`${k.cyan}│${k.reset} ${k.dim}${K2(`Up/Down to select | Enter: confirm | Esc: back${P}`,Math.max(1,H-6))}${k.reset}`),j(`${k.cyan}└${k.reset}`);for(let L=U;L<F;L++)j("");Y=U};return new Promise((H)=>{let q=X.isRaw??!1,F=()=>{if(Q)return;if(Q=!0,W)clearTimeout(W);X.removeListener("data",K);try{X.setRawMode(q),X.pause(),z.write(k.show)}catch{}G?.removeListener("SIGINT",j),G?.removeListener("SIGTERM",j)},U=(N)=>{F(),H(N)},j=()=>U(null),K=(N)=>{for(let D of A9(N)){if(Q)break;if(W)clearTimeout(W),W=null;switch(D){case"up":B=(B-1+Z.length)%Z.length,V();break;case"down":B=(B+1)%Z.length,V();break;case"enter":U(Z[B]?.value??null);break;case"escape":U(null);break;case"escape-start":W=setTimeout(()=>U(null),Fz);break;default:break}}};G?.once("SIGINT",j),G?.once("SIGTERM",j);try{X.setRawMode(!0)}catch{F(),H(null);return}X.resume(),z.write(k.hide),V(),X.on("data",K)})}async function I9($,Z,J=!1){if(!N2($))return!1;return await m2($,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Z})??!1}function PZ($){let Z=N2($);return{terminal:$,interactive:Z,print:(J)=>R9($,J),confirm:(J,X)=>I9($,J,X),select:async(J,X)=>Z&&J.length>0?m2($,J,X):null}}function Nz($,Z){if($.print(Z.title),Z.subtitle)$.print(Z.subtitle);for(let J of Z.status??[])$.print(` ${J}`);$.print(""),$.print("Actions:");for(let J of Z.actions)$.print(J.hint?` - ${J.label} (${J.hint})`:` - ${J.label}`);return $.print(""),$.print("This menu needs an interactive terminal to choose an action; nothing was changed."),{status:"not-interactive"}}async function P4($){let Z=$.terminal??E9(),J=PZ(Z);if(!J.interactive)return Nz(J,$);if($.actions.length===0)return J.print("No actions are available."),{status:"cancelled"};let X=await m2(Z,$.actions.map((z)=>({label:z.label,value:z,color:z.destructive?"red":"cyan",...z.hint?{hint:z.hint}:{}})),{message:$.title,subtitle:$.subtitle??"Select an account action",...$.status?{lines:$.status}:{},clearScreen:!0});if(!X)return{status:"cancelled"};if(X.destructive&&!await J.confirm(X.confirm??`${X.label}?`))return J.print("Cancelled; nothing was changed."),{status:"declined",action:X.id};try{return await X.run(J),{status:"ran",action:X.id}}catch(z){return J.print(`${X.label} failed: ${z instanceof Error?z.message:String(z)}`),{status:"failed",action:X.id,error:z}}}var CZ="disabled from the auth menu",MZ=8;async function y0($){let Z=await $.read();if(Z.status==="ready")return{rows:Z.rows};if(Z.status==="pending-migration")return{rows:[],problem:"The account store has not been migrated yet."};return{rows:[],problem:`The account store could not be read (${Z.file}: ${Z.reason}).`}}async function Dz($){let{rows:Z}=await y0($);return Z.some((J)=>J.credential!==void 0)}function x9($){let Z=[];if($.label)Z.push($.label);if($.invalid)Z.push(`invalid ${$.invalid}`);else if(!$.enabled)Z.push($.disabledReason?`disabled: ${$.disabledReason}`:"disabled");else Z.push("enabled");if(!$.credential&&!$.invalid)Z.push("no credential");return Z.join(", ")}function Pz($){if($.problem)return[$.problem];if($.rows.length===0)return["No accounts yet."];let Z=$.rows.slice(0,MZ).map((X)=>`${X.id}: ${x9(X)}`),J=$.rows.length-MZ;if(J>0)Z.push(`... and ${J} more`);return Z}function Mz($){return $ instanceof Error?$.message:String($)}async function y9($,Z,J){if(Z.length===0)return $.print("There are no accounts."),null;return $.select(Z.map((X)=>({label:X.id,value:X,hint:x9(X)})),{message:J})}function Cz($,Z){let J=new Set(Z.map((X)=>X.id));if($.id&&!J.has($.id))return $.id;for(let X=1;;X++){let z=`account-${X}`;if(!J.has(z))return z}}function TZ($,Z=Date.now()){let J=r0($.quota)?b0($.quota):void 0,X=w6(J,{now:Z,form:"full"});return(X.length>0?X:[I0(J,{now:Z})]).map((z)=>` ${z}`)}function LZ($){return{id:"add-account",label:"Add account",hint:"sign in to another account",async run(Z){let J=$.login;if(!J)throw Error("No login is configured");let X=await m6(J,Z),{rows:z}=await y0($.store),G=($.newAccountId??Cz)(X,z),B=await $.store.add({id:G,credential:X.credential,...X.identity!==void 0?{identity:X.identity}:{},...X.label!==void 0?{label:X.label}:{}},$.extraLocks?{extraLocks:$.extraLocks}:{});if(B.outcome==="rotated")Z.print(`That sign-in is already account ${B.id}; its credential was updated.`);else if(B.outcome==="added-disabled")Z.print(`Added account ${B.id}, disabled: another enabled account is the same provider account.`);else if(B.outcome==="completed")Z.print(`Finished adding account ${B.id}.`);else Z.print(`Added account ${B.id}.`)}}}function _Z($){return{id:"reauthenticate",label:"Re-authenticate account",hint:"sign an account in again",async run(Z){let J=$.login;if(!J)throw Error("No login is configured");let{rows:X}=await y0($.store),z=await y9(Z,X,"Re-authenticate which account?");if(!z)return;let G=await m6(J,Z);if(G.identity!==void 0&&z.identity!==void 0&&G.identity!==z.identity){Z.print(`That sign-in is a different account from ${z.id}; nothing was changed. Use Add account to add it.`);return}let B=G.identity??z.identity;await $.store.replace(z.id,G.credential,B!==void 0?{identity:B}:{},$.extraLocks?{extraLocks:$.extraLocks}:{}),Z.print(`Updated the sign-in of account ${z.id}.`)}}}function OZ($){return{...$.protect?{protect:$.protect}:{},...$.extraLocks?{extraLocks:$.extraLocks}:{}}}function SZ($){return $ instanceof b&&$.kind==="row-protected"?$.message:void 0}function AZ($){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run(Z){let{rows:J}=await y0($.store),X=await y9(Z,J,"Remove which account?");if(!X)return;if(!await Z.confirm(`Remove account ${X.id}?`)){Z.print("Cancelled; nothing was changed.");return}try{await $.store.remove(X.id,OZ($))}catch(z){let G=SZ(z);if(G===void 0)throw z;Z.print(`Account ${X.id} was kept: ${G}`);return}Z.print(`Removed account ${X.id}.`)}}}function b9($){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run(Z){let{rows:J}=await y0($.store),X=await y9(Z,J,"Enable or disable which account?");if(!X)return;let z=$.extraLocks?{extraLocks:$.extraLocks}:{};if(X.enabled){await $.store.disable(X.id,$.disableReason??CZ,z),Z.print(`Disabled account ${X.id}.`);return}try{await $.store.enable(X.id,z)}catch(G){if(G instanceof b&&G.kind==="duplicate-identity"){Z.print(`Account ${X.id} stays disabled: another enabled account is the same provider account.`);return}throw G}Z.print(`Enabled account ${X.id}.`)}}}function EZ($){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}if(J.rows.length===0)Z.print("No accounts yet.");for(let X of J.rows)Z.print(`${X.id}: ${x9(X)}`)}}}function k9($){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}let X=new Map,z=$.pollQuota;if(z)for(let B of J.rows){if(B.invalid||!B.credential||B.credentialEpoch===void 0){X.set(B.id,"no usable credential");continue}try{let W=await z(B);await $.store.recordQuota(B.id,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},W)}catch(W){X.set(B.id,Mz(W))}}let G=await y0($.store);if(G.rows.length===0)Z.print("No accounts yet.");for(let B of G.rows){Z.print(`${B.id}:`);let W=X.get(B.id);if(W)Z.print(` quota check failed: ${W}`);for(let Q of TZ(B,($.now??Date.now)()))Z.print(Q)}}}}function RZ($){return{id:"delete-all",label:"Delete all accounts",destructive:!0,confirm:"Delete every account? Accounts the plugin keeps are not deleted.",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}let X=[],z=[];for(let G of J.rows)try{await $.store.remove(G.id,OZ($)),X.push(G.id)}catch(B){let W=SZ(B);if(W===void 0)throw B;z.push(`${G.id} (${W})`)}if(Z.print(`Deleted ${X.length} account(s).`),z.length>0)Z.print(`Kept: ${z.join(", ")}.`)}}}async function g9($){return IZ($,f2()||await $.custody?.()===!0)}function IZ($,Z){let J=$.doctor?.length?[S9({checks:$.doctor})]:[],X=[...$.extraActions??[]];if(Z)return[EZ($),b9($),k9($),...J,...X];return[...$.login?[LZ($),_Z($)]:[],AZ($),b9($),k9($),...J,...X,RZ($)]}async function Tz($){let Z=f2(),J=Z||await $.custody?.()===!0,X=IZ($,J),[z,G]=await Promise.all([y0($.store),$.status?.()??[]]);return P4({title:$.title,subtitle:J?"Accounts come from the vault; select an action":"Select an account action",status:[...G,...Z?[u6]:[],...Pz(z)],actions:X,...$.terminal?{terminal:$.terminal}:{}})}function bZ(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function kZ($){return $!==void 0}function Lz($){return async(Z)=>{if(!kZ(Z))return $.login();if(!await $.hasCredential())return $.login(Z);return await $.openMenu(Z),bZ()}}function Y0($){return $.authority!=="local"}async function e($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function p6($){let Z;try{return await Promise.race([Promise.resolve().then(()=>$.refresh()).then(()=>{return},(J)=>J instanceof Error?J.message:String(J)),new Promise((J)=>{Z=setTimeout(()=>J("Vault roster refresh did not finish within the roster wait budget."),s5)})])}finally{clearTimeout(Z)}}function V0($){if($.email)return $.email;if($.credentialId==="chatgpt:openai"&&(!$.label||$.label===$.credentialId))return"main";return $.label||$.routeId}function xZ($,Z){let J=b0(r0($.quota)?$.quota:void 0),X=w6(J,{now:Z});return(X.length>0?X:[I0(J,{now:Z})]).map((z)=>` ${z}`)}var M4="Accounts are managed in the vault with ck. Disconnect to use local accounts.",D2="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function yZ($){let Z=[...$.label?[$.label]:[],$.invalid?`invalid ${$.invalid}`:$.enabled?"enabled":`disabled${$.disabledReason?`: ${$.disabledReason}`:""}`];return`${$.id}: ${Z.join(", ")}`}async function _z($,Z){let J=await p6(Z),X=await e(Z),{status:z}=X,G=Y0(X)?void 0:await $.store.read(),B=await g9($),W=new Set(["check-quotas",...($.extraActions??[]).map((V)=>V.id)]),Q=B.filter((V)=>!Y0(X)||W.has(V.id)).map((V)=>({...V,run:async(H)=>{if(!W.has(V.id)&&Y0(await e(Z))){H.print(D2);return}await Z.authority(),await V.run(H)}})),Y=Q.find((V)=>V.id==="check-quotas");if(Y)Y.run=async(V)=>{await p6(Z);let H=await e(Z),q=Y0(H)?void 0:await $.store.read();if(!q)V.print(M4);else if(q.status!=="ready")V.print("The local account store could not be read.");else for(let j of q.rows){V.print(yZ(j));try{if($.pollQuota&&j.credentialEpoch!==void 0){let D=await $.pollQuota(j);await $.store.recordQuota(j.id,{credentialEpoch:j.credentialEpoch,...j.identity!==void 0?{identity:j.identity}:{}},D)}}catch(D){V.print(` quota check failed: ${D instanceof Error?D.message:String(D)}`)}let K=await $.store.read(),N=K.status==="ready"?K.rows.find((D)=>D.id===j.id):void 0;for(let D of xZ(N??j,($.now??Date.now)()))V.print(D)}let F=H.routes;for(let j of Z.snapshot()?.rows??[]){if(V.print(`Vault ${V0(j)}: ${j.enabled?j.state:"declined"}`),!F.has(j.routeId)){V.print(" quota check skipped: account is not enabled and active");continue}let K=await Z.pollQuota(j.routeId);if(!K.ok)V.print(` quota check failed: ${K.error??"vault unavailable"}`);let N=Z.snapshot()?.rows.find((D)=>D.routeId===j.routeId);for(let D of xZ({quota:N?.quota},($.now??Date.now)()))V.print(D)}let U=await Z.status();if(U.lastError)V.print(`Claustrum vault unreachable: ${U.lastError}`)};return P4({title:$.title,subtitle:"Select an account action",status:[...await $.status?.()??[],...J?[`Last error: ${J}`]:[],...z.lastError?[`Claustrum vault unreachable: ${z.lastError}`]:[],...z.accounts.map((V)=>`Vault ${V0(V)}: ${V.enabled?`enabled (${V.state})`:"declined"}`),...!G?[M4]:G.status==="ready"?G.rows.map((V)=>yZ(V)):["The local account store could not be read."]],actions:Q,...$.terminal?{terminal:$.terminal}:{}})}function gZ($){return E($)?{...$}:{}}function f9($,Z){let J=r0(Z)?fZ(Z.credits):void 0;return J?`${$} · prepaid ${J}`:$}function hZ($,Z){return{...$,sections:$.sections.map((J)=>J.id!=="quota"?J:{...J,items:J.items.map((X)=>X.detail===void 0?X:{...X,detail:f9(X.detail,Z.get(X.id))})})}}function l6($,Z,J,X){let z=J.confirm?.irreversible?{irreversible:!0,confirm:J.confirm.message}:{...J.confirm?{confirm:J.confirm.message}:{}};return{id:J.id,label:J.label,...J.description?{description:J.description}:{},...J.group?{group:J.group}:{},knobs:J.knobs,...z,run:async({values:G,invocation:B})=>{let W=await $.apply({command:$.command,sectionId:Z,...X?{itemId:X}:{},actionId:J.id,values:G,confirmed:!0},B);return{ok:W.ok,text:W.text,...W.code?{code:W.code}:{}}}}}function v9($,Z){return new Proxy($,{get(J,X){if(X==="read")return async()=>{let G=await J.read();if(G.status!=="ready")return G;let B={...G,rows:G.rows.map((Y)=>({...Y,label:Y.label??Y.id}))};if(!Z)return B;let W=await e(Z);if(!Y0(W))return B;let Q=[...W.status.accounts.map((Y)=>({id:Y.routeId,label:V0(Y),type:"oauth",enabled:Y.enabled,identity:Y.accountIdentity,quota:Y.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:Q}};if(X==="readSettings")return async()=>{let G=await J.readSettings();if(G.status==="error"||!Z)return G;let B=await e(Z),W=gZ(G.settings.killswitch);if(!Y0(B)||!G.settings.killswitch)return G;let Q=gZ(W.accounts);for(let Y of B.status.accounts)Q[Y.routeId]=C4({version:1,accounts:[],...G.settings},Y.routeId);return{...G,settings:{...G.settings,killswitch:{...W,accounts:Q}}}};let z=Reflect.get(J,X);return typeof z==="function"?z.bind(J):z}})}function h9($,Z,J={}){let X=G2($),z=(Y)=>G2({command:$.command,title:$.title,store:v9($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:{...$.routing,formerMainId:Y??"",vaultOrder:async()=>{let V=await e(Z);if(!Y0(V))return;return{rows:V.status.accounts.map((H)=>({id:H.routeId,label:V0(H)})),reorder:async(H)=>{if(!Y0(await e(Z)))throw new u("vault-local-action",D2);return Z.reorder(H)}}}},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),G=async(Y,V)=>{let H=await e(Z),q=Y0(H),F=vZ(H.status.accounts.map((T)=>({id:T.routeId,credentialId:T.credentialId}))),U=q?z(F):X,K=(await U.open(V)).menu.sections.find((T)=>T.id===Y);if(!K)throw new u("unavailable","The account menu is unavailable.");if(!q)return{lines:K.lines,items:K.items.map((T)=>({...T,actions:T.actions.map((A)=>l6(U,Y,A,T.id))})),actions:K.actions.map((T)=>l6(U,Y,T))};let N=new Map(H.status.accounts.map((T)=>[T.routeId,T])),D=($.now??Date.now)(),O=(T)=>({id:"check",label:T?"Check this account":"Check now",group:"Actions",run:async()=>{let x=[...(await e(Z)).routes].filter((I)=>!T||I===T);if(T&&x.length===0)throw new u("unavailable","This vault account cannot be checked right now.");for(let I of x){let f=await Z.pollQuota(I);if(!f.ok)throw new u("quota-check-failed",`${I}: ${f.error??"vault unavailable"}`)}return`Checked quota for ${x.length} account${x.length===1?"":"s"}.`}});if(Y==="quota"){let T=(A,x)=>I0(b0(A.quota,$.quota?.scope),{now:D,form:x});return{lines:H.status.accounts.filter((A)=>!H.routes.has(A.routeId)).map((A)=>`${V0(A)} (${A.enabled?A.state:"disabled"}): ${f9(T(A,"compact"),A.quota)}`),items:H.status.accounts.filter((A)=>H.routes.has(A.routeId)).map((A)=>({id:A.routeId,label:V0(A),group:"Accounts",status:T(A,"compact"),detail:f9(T(A,"full"),A.quota),actions:[O(A.routeId)]})),actions:H.routes.size>0?[O()]:[]}}let M=K.items.map((T)=>{let A=N.get(T.id),x=A&&Y==="accounts"?`Vault · ${A.credentialType==="oauth"?"login":"API key"} · ${A.state} · ${A.enabled?"enabled":"declined"}`:T.detail;return{id:T.id,label:T.label,detail:x,group:T.group,status:A&&Y==="accounts"?A.enabled?A.state:"disabled":T.status,...T.facts?{facts:T.facts}:{},actions:A&&Y!=="limits"?[]:T.actions.map((I)=>l6(U,Y,I,T.id))}}),P=K.actions.filter((T)=>H.status.accounts.length>0&&(Y==="limits"||Y==="routing"&&(T.id==="mode"||T.id==="order"||T.id==="maxSameAccountWait"))).map((T)=>l6(U,Y,T)),L=K.actions.find((T)=>T.id==="mode")?.knobs.find((T)=>T.id==="mode"),C=Y==="routing"&&F===null&&L?.kind==="choice"&&(L.value==="main-first"||L.value==="fallback-first");return{lines:Y==="accounts"?[...H.status.discovered?[`${H.status.accounts.length} vault account${H.status.accounts.length===1?"":"s"}`,`${H.routes.size} can route`]:["Connected · waiting for the vault's first answer"],M4]:[...K.lines,...C?["No default vault account, so this mode orders like Ordered"]:[]],items:M,actions:P}},B=G2({...$,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(Y)=>G("accounts",Y)},quota:{title:"Quota",build:(Y)=>G("quota",Y)},routing:{title:"Routing",build:(Y)=>G("routing",Y)},limits:{title:"Limits",build:(Y)=>G("limits",Y)}},extras:$.extras?.map((Y)=>Y.id!=="reset"?Y:{...Y,build:async(V)=>{let H=await e(Z);if(Y0(H))return{lines:[M4]};return Y.build(V)}})}),W=async()=>{if(!Y0(await e(Z)))return{menu:X,error:void 0};let Y=J.refresh===!1?void 0:await p6(Z);return{menu:B,error:Y}},Q=async(Y,V)=>{let H=await Y.menu.open(V);if(Y.error)H.menu.sections.find((F)=>F.id==="vault")?.lines.push(`Last error: ${Y.error}`);return H};return{command:$.command,open:async(Y)=>Q(await W(),Y),apply:async(Y,V)=>{let H=await W(),{menu:q}=H;if(q===B&&(Y.sectionId==="accounts"||Y.sectionId==="reset"||Y.sectionId==="quota"&&(await e(Z)).routes.size===0||Y.sectionId==="limits"&&Y.itemId!==void 0&&!(await e(Z)).status.accounts.some((F)=>F.routeId===Y.itemId)))return{...await Q(H,V),ok:!1,code:"vault-local-action",text:D2};if(J.refuseApply)return{...await Q(H,V),ok:!1,...J.refuseApply};return q.apply(Y,V)}}}var L4="openai",lZ="OpenAI accounts",e0="main",dZ="that account is already your main account, so it was not added again",U0=o("commands"),cZ=new Set(["__proto__","constructor","prototype"]);function Oz($,Z){let J={version:1,accounts:[],killswitch:$},X=E($.accounts)?Object.keys($.accounts):[],z={};for(let W of new Set([e0,...Z,...X])){if(cZ.has(W))continue;let Q=C4(J,W===e0?void 0:W);z[W]={primary:Q.primary,secondary:Q.secondary}}let G=C4(J,void 0),B={...$};return delete B.main,B.accounts=z,B.defaults={primary:G.primary,secondary:G.secondary},B.schema=_4,B}function Sz($,Z){let J=E($.accounts)?{...$.accounts}:{};for(let z of new Set([e0,...Z])){if(cZ.has(z)||Object.hasOwn(J,z))continue;J[z]={primary:T4.primary,secondary:T4.secondary}}let X=E($.defaults)?$.defaults:{primary:T4.primary,secondary:T4.secondary};return{...$,accounts:J,defaults:X,schema:_4}}function mZ($,Z){let J=!1;if(E($.cachekeep))$.cacheKeep={...$.cachekeep,...E($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,J=!0;let X=$.killswitch;if(E(X)&&X.schema!==_4)$.killswitch=Oz(X,Z),J=!0;return J}async function wZ($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((J)=>J.id):[]}function u9($){let Z=async()=>{let X=await $.readSettings();if(X.status==="error")return X;let z=structuredClone(X.settings);return mZ(z,await wZ($)),{...X,settings:z}},J=async(X,z)=>{let G=await wZ($);return $.updateSettings(async(B)=>{mZ(B,G);let W=await X(B)??B;if(E(W.killswitch)&&W.killswitch.schema!==_4)W.killswitch=Sz(W.killswitch,G);return W},z)};return new Proxy($,{get(X,z){if(z==="readSettings")return Z;if(z==="updateSettings")return J;let G=Reflect.get(X,z,X);return typeof G==="function"?G.bind(X):G}})}function Az($,Z){let J=(Q,Y)=>Z.rowLocks?Z.rowLocks(Q):Y,X=(Q,Y)=>{let V=J(Q,Y?.extraLocks);return{...Y??{},...V?{extraLocks:V}:{}}},z=(Q,Y,V,H)=>$.replace(Q,Y,V,X(Q,H)),W={add:async(Q,Y)=>{let V=await $.read(),q=(V.status==="ready"?V.rows:[]).filter((K)=>K.type==="oauth"&&!K.invalid),F=Q.identity?q.find((K)=>K.identity===Q.identity):void 0;if(F?.id===e0)throw new u("main-account",dZ);let U=F??q.find((K)=>K.id===Q.id&&K.id!==e0);if(!U||Q.credential.type!=="oauth")return $.add(Q,Y);let j=await z(U.id,Q.credential,Q.identity!==void 0?{identity:Q.identity}:{},Y?.extraLocks?{extraLocks:Y.extraLocks}:void 0);return U0.info("account signed in again",{id:U.id}),{id:j.id,outcome:"rotated",credential:j.credential,credentialEpoch:j.credentialEpoch}},replace:z,enable:(Q,Y)=>$.enable(Q,X(Q,Y)),disable:(Q,Y,V)=>$.disable(Q,Y,X(Q,V)),remove:(Q,Y)=>$.remove(Q,X(Q,Y))};return new Proxy($,{get(Q,Y){if(Object.hasOwn(W,Y))return W[Y];let V=Reflect.get(Q,Y,Q);return typeof V==="function"?V.bind(Q):V}})}async function Bj($,Z,J){await u9($).updateSettings((X)=>{J(X);return},Z?{extraLocks:Z}:{})}var Ez=["version","accounts","commonAuthPool"];function Qj($,Z){return async(J)=>{let X;if(await u9($).updateSettings((z)=>{let G={...z,version:1,accounts:[]},B=J(G)??G;X=B;let W={...B};for(let Q of Ez)delete W[Q];return W},Z?{extraLocks:Z}:{}),!X)throw Error("the settings write did not run");return X}}var Rz="migration";function uZ($){let Z=["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.",$.length>0?"These processes still hold the move back:":"No running process holds the move back."],J={command:L4,title:lZ,sections:[{id:Rz,slot:"extra",title:"Accounts are moving",lines:Z,items:$.map((X,z)=>({id:`blocker-${z}`,label:X.pid==="unknown"?"processes that could not be read":`pid ${X.pid}`,detail:`version ${X.version}`,actions:[]})),actions:[]}]};return w9(J)}var Iz=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function bz($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(Iz.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function m9($,Z,J){if(Array.isArray($))return $.map((z,G)=>m9(z,`${Z}[${G}]`,J));if(!E($))return $;let X={};for(let[z,G]of Object.entries($)){if(bz(z)){J.push(`${Z}.${z}`);continue}X[z]=m9(G,`${Z}.${z}`,J)}return X}function w9($){let Z=[],J=m9($,"menu",Z);if(Z.length>0)U0.warn("credential-shaped field stripped before RPC",{fields:Z});return J}function kz($){return{id:$.id,credential:{type:"oauth",refresh:$.refresh,...$.access!==void 0?{access:$.access}:{},...$.expires!==void 0?{expires:$.expires}:{}},...$.accountId!==void 0?{identity:$.accountId}:{},...$.label!==void 0?{label:$.label}:{}}}function xz($,Z){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 X=typeof J.label==="string"&&J.label.trim().length>0?J.label.trim():void 0,z=J.headless===!0,G=await $.begin({...X!==void 0?{label:X}:{},headless:z}),B=z?`Open this verification URL:
|
|
6
6
|
|
|
7
7
|
${G.url}
|
|
8
8
|
|
|
@@ -14,10 +14,10 @@ ${G.url}
|
|
|
14
14
|
|
|
15
15
|
${G.instructions}
|
|
16
16
|
|
|
17
|
-
The account is added when you finish.`,W=G.completion.then(async(Q)=>{if(Z&&await Z.authority()!=="local")throw new u("vault-local-action",D2);let Y=await $.mainIdentity?.();if(Q.id===e0||Q.accountId&&Y&&Q.accountId===Y)throw U0.warn("account add rejected (main identity)",{id:Q.id}),new u("main-account",
|
|
18
|
-
`)}}}]}}}}async function
|
|
17
|
+
The account is added when you finish.`,W=G.completion.then(async(Q)=>{if(Z&&await Z.authority()!=="local")throw new u("vault-local-action",D2);let Y=await $.mainIdentity?.();if(Q.id===e0||Q.accountId&&Y&&Q.accountId===Y)throw U0.warn("account add rejected (main identity)",{id:Q.id}),new u("main-account",dZ);return U0.info("account added",{id:Q.id}),kz(Q)});return{status:"pending",message:B,completion:W}}}}function Wj($){return{id:"session",title:"This session",build:async(Z)=>{let J=Z.sessionId;if(!J)return{lines:["No current session"]};let X=await $.getPin?.(J);return{lines:[X?`Pinned to ${X}`:"No sticky pin"],actions:$.clearPin?[{id:"clear-pin",label:"Clear this session's pin",description:"The next request may still choose the same account.",run:async({invocation:z})=>{if(!z.sessionId)return"No current session.";return await $.clearPin?.(z.sessionId),U0.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 Yj($){let{vault:Z}=$;return{id:"vault",title:"Vault",build:async()=>{let J=await Z.status(),X=J.enrollment.state==="approved"?J.enrollment.approvedName??J.name:J.name,z=await Z.authority(),G=z==="host",B=z!=="local",W=Z.routes().length;return{lines:[G?u6:B?J.discovered?`Connected · ${J.accounts.length} account${J.accounts.length===1?"":"s"}`:"Connected · waiting for the vault's first answer":J.enrollment.state==="idle"?"Not connected":`Enrollment ${J.enrollment.state}`,...!G?[a5(J.host,J.name,J.enrollment),...y6(J.name,J.enrollment)]:[],...B&&J.discovered?[J.accounts.length===0?A6(X,Z.grantReach()):`The vault serves ${J.accounts.length} OpenAI account${J.accounts.length===1?"":"s"}; ${W} can route now.`]:[],...B&&Z.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."]:[],...J.lastError?[`Last error: ${J.lastError}`]:[]],items:J.accounts.map((Q)=>({id:Q.routeId,label:V0(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 Z.decline(Q.routeId),await $.changed?.(),`${V0(Q)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await Z.accept(Q.routeId),await $.changed?.(),`${V0(Q)} is enabled on this host.`}}]})),actions:G?[]:B?[{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()=>{let Q=(await Z.status().catch(()=>{return}))?.enrollment,Y=Q?.state==="approved"?Q.approvedName??Z.name:Z.name,V=Q&&Q.state!=="blocked"?`Run \`ck auth enroll revoke --name ${Y}\` to revoke it in the vault too.`:"Run ck auth enroll list to find this host's enrollment name, then ck auth enroll revoke --name <name>.";return await Z.disconnect(),await $.changed?.(),`Disconnected: ${Y} no longer reads from the vault. ${V}`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:Q})=>{let Y=await Z.connectStep();if(Y.state!=="pending"&&Y.state!=="busy")return await $.changed?.(),C9(Z,Y);return Z.waitForApproval($.wait).then(async(V)=>{await $.changed?.();let H=C9(Z,V);Q.notify(H.text,H.ok?"info":"warning")}).catch((V)=>{Q.notify(`Connecting to the vault failed: ${V instanceof Error?V.message:String(V)}`,"error")}),{ok:!0,text:[...y6(Z.name,Y),"Waiting for the approval; you are told here when it lands."].join(`
|
|
18
|
+
`)}}}]}}}}async function pZ($,Z,J){if(!u0(Z))return H0(Z,"invalid_account_key","That account cannot take a reset credit.");let X;try{let z=(await $.loadAccounts({configPath:$.configPath,statePath:$.statePath}))?.reset?.[Z];if(J||z&&Object.hasOwn(z,"inFlight"))X=(await $.resolveResetTarget(Z)).chatgptAccountId;else{let B=await aZ(Z,$);if(!B.eligible)return H0(Z,"not_eligible",nZ(B));X=B.chatgptAccountId}if(!X)return H0(Z,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");U0.info("reset redemption decision",{accountKey:Z,retry:J});let G=await HZ({configPath:$.configPath,statePath:$.statePath,mutateAccountsFn:$.mutateAccounts,loadAccountsFn:$.loadAccounts,now:$.now,randomUUID:$.randomUUID,fetchImpl:$.fetchImpl,resolveTarget:$.resolveResetTarget,fetchUsage:(B)=>N4({accessToken:B.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>$.quotaManager.isRateLimited(B)},{accountKey:Z,expectedChatgptAccountId:X,retry:J});return U0.info("reset redemption outcome",{accountKey:Z,code:G.outcome.kind}),iZ(G,$,X)}catch(z){let G=mz(Z,z,X);return U0.info("reset redemption outcome",{accountKey:Z,code:G.code}),G}}function Vj($){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await $.accountKeys()).map((Z)=>({id:Z,group:"Accounts",label:Z===e0?"Main account":Z,actions:[{id:"preview",label:"Preview",description:"Fetch the account's current quota and reset credits before spending a credit.",run:async()=>{let J=await aZ(Z,$);return{ok:J.eligible,text:`${hz(J)}
|
|
19
19
|
|
|
20
|
-
${
|
|
20
|
+
${nZ(J)}`}}},{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:J,text:X}=await pZ($,Z,!1);return{ok:J,text:X}}},{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:J,text:X}=await pZ($,Z,!0);return{ok:J,text:X}}}]}))})}}var yz=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],gz=["primary","secondary"];function Hj($){let Z=new Set($.unavailableSections),J=(Y)=>({title:Y,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),X=[...$.extras??[]];if(Z.has("reset")){let Y={id:"reset",...J("Reset credits")},V=X.findIndex((H)=>H.id==="reset");if(V<0)X.unshift(Y);else X[V]=Y}let z={command:L4,title:lZ,store:v9(u9(Az($.store,{...$.rowLocks?{rowLocks:$.rowLocks}:{}}))),...$.extraLocks?{extraLocks:$.extraLocks}:{},accounts:{...$.login?{login:xz($.login,$.vault)}:{},...$.protect?{protect:$.protect}:{},...$.describeIdentity?{describeIdentity:$.describeIdentity}:{}},quota:$.quotaCheck?{check:$.quotaCheck}:{},routing:{orderedVariants:yz,formerMainId:e0,sameAccountWait:!0},limits:{labels:gz},...Z.has("cache")?{cache:J("Cache")}:$.cache?{cache:$.cache}:{},...Z.has("diagnostics")?{diagnostics:J("Diagnostics")}:$.diagnostics?{diagnostics:$.diagnostics}:{},extras:X,...$.logger?{logger:$.logger}:{},...$.now?{now:$.now}:{}},G=$.vault?h9(z,$.vault,{refresh:!$.readOnly,...$.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):G2(z),B=$.vault?h9(z,$.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,W=(Y)=>{let{sessionId:V}=Y,H=Y.notify.bind(Y);return{...V!==void 0?{sessionId:V}:{},notify:H}},Q=async(Y)=>{if($.vault&&await $.vault.authority()!=="local")return Y;let V=await $.store.read().catch(()=>{return});if(V?.status!=="ready")return Y;return{...Y,menu:hZ(Y.menu,new Map(V.rows.map((H)=>[H.id,H.quota])))}};return{command:L4,async open(Y){let V=W(Y),H=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(H&&!H.migrated)return{command:L4,menu:uZ(H.blockers)};let q=await G.open(V);return Q({...q,menu:w9(q.menu)})},async apply(Y,V){let H=W(V),q=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(q&&!q.migrated)return{command:L4,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:uZ(q.blockers)};if($.readOnly&&$.vault)return G.apply(Y,H);if($.readOnly||$.allowAction&&!$.allowAction(Y)||Z.has(Y.sectionId)){if(B)return B.apply(Y,H);return{...await G.open(H),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let F=await G.apply(Y,H);if(F.ok)await $.afterApply?.();return Q({...F,menu:w9(F.menu)})}}}function sZ($){let Z=[$.primary?.usedPercent,$.secondary?.usedPercent].filter((J)=>J!==void 0);return Z.length>0?Math.max(...Z):void 0}function fz($,Z){let J=[$.primary,$.secondary].filter((z)=>z!==void 0),X=J.filter((z)=>D4(z,Z));return(X.length>0?X:J).sort((z,G)=>G.usedPercent-z.usedPercent)[0]?.resetsAt}function vz($,Z){if(!$)return!1;let J=[$.primary,$.secondary].filter((X)=>X!==void 0);if(J.length===0)return!1;return J.every((X)=>!D4(X,Z))}async function aZ($,Z){let J;try{J=await Z.resolveResetTarget($);let X=J.accountKey==="main"?void 0:J.chatgptAccountId,[z,G]=await Promise.all([N4({accessToken:J.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:J.chatgptAccountId}),_9(Z.fetchImpl,J.accessToken,X)]),B=h6(G.credits),W=VZ(G.credits),Q=G.availableCount??z.resetCreditsAvailable??(W>0?W:void 0),Y=z.resetCreditsApplicable,V=L9(z,Z.quotaManager.isRateLimited($),Z.now()),H;if(!J.chatgptAccountId)H="stable ChatGPT account identity unavailable";else if(!V.ok)H=V.reason;else if(!B)H="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:sZ(z),resetTime:fz(z,Z.now()),availableCount:Q,applicableAvailableCount:Y,eligible:H===void 0,reason:H,selectedCreditId:B?.id,selectedCreditExpiresAt:B?.expiresAt}}catch(X){if(X?.status===401)await J?.onAuthFailure?.(401);return U0.warn("reset preview row failed",{accountKey:$,error:X?.message??String(X)}),{accountKey:$,label:$==="main"?"Main account":$,eligible:!1,reason:X?.message??String(X)}}}function hz($){let Z=$.usedPercent===void 0?"quota unavailable":`${$.usedPercent}% used`,J=$.availableCount===void 0?"credits unavailable":`${$.applicableAvailableCount===void 0?"?":$.applicableAvailableCount}/${$.availableCount} applicable/available`,X=$.eligible?`eligible · credit ${$.selectedCreditId} expires ${$.selectedCreditExpiresAt}`:$.reason;return`${Z}; ${J}; ${X}`}function nZ($){let Z=["## Confirm reset credit","",`Account: **${$.label}** (\`${$.accountKey}\`)`,`Current quota: **${$.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${$.availableCount??"unknown"}**`,`Credit expires: **${$.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${$.resetTime??"unavailable"}**`,""];if(($.availableCount??0)>0&&$.applicableAvailableCount===0)Z.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."),Z.push("");if($.eligible&&$.chatgptAccountId)Z.push('Eligible: choose "Spend a reset credit" to redeem one.');else Z.push(`Cannot reset: **${$.reason??"not eligible"}**`);return Z.join(`
|
|
21
21
|
`)}function H0($,Z,J,X={}){if(Object.keys(X).length>0)U0.debug("reset step details",{accountKey:$,code:Z,...X});return{ok:Z==="reset"||Z==="already_redeemed",code:Z,text:J}}function mz($,Z,J){if(Z instanceof W0){let z={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 H0($,Z.kind,`## Reset credit
|
|
22
22
|
|
|
23
23
|
${z[Z.kind]}
|
|
@@ -46,7 +46,7 @@ Code: \`${z}\`
|
|
|
46
46
|
|
|
47
47
|
${H}${q}${V===void 0?"":`
|
|
48
48
|
|
|
49
|
-
Remaining applicable credits: **${V}**`}`,{verifiedFresh:Y,afterUsedPercent:
|
|
49
|
+
Remaining applicable credits: **${V}**`}`,{verifiedFresh:Y,afterUsedPercent:sZ(Q?.quota??{}),remainingCredits:V})}if(z==="ambiguous_local")return H0(X,z,`## Reset credit result
|
|
50
50
|
|
|
51
51
|
Account: **${$.target.label}** (\`${X}\`)
|
|
52
52
|
|
|
@@ -64,13 +64,13 @@ Account: **${$.target.label}** (\`${X}\`)
|
|
|
64
64
|
|
|
65
65
|
Code: \`${z}\`
|
|
66
66
|
|
|
67
|
-
${G[z]??"The server returned a no-op result. No reset was confirmed."}`)}function nZ($,Z){return JSON.stringify(["openai","pool",F4($),F4(Z)])}function rZ($){return JSON.stringify(["openai","vault",F4($)])}function wz($,Z){let J=Z.kind==="vault"?Z.routeId:Z.id,X=Z.kind==="pool"?Z.credentialEpoch:Z.kind==="vault"?Z.addedAt:Z.verifiedIdentity;if(X===void 0||X==="")return;return{namespace:$,accountId:J,incarnation:String(X)}}function qj($,Z){let J=wz($,{kind:"pool",...Z});return J?{account:J,credentialEpoch:J.incarnation,identity:Z.identity}:void 0}function jj($,Z){return{account:{namespace:$,accountId:Z.routeId,incarnation:String(Z.addedAt)},credentialEpoch:String(Z.addedAt),identity:Z.accountIdentity}}function y($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function p9($){return JSON.stringify($.map((Z)=>[y(Z.account),Z.credentialEpoch,Z.identity??null]).sort((Z,J)=>JSON.stringify(Z).localeCompare(JSON.stringify(J))))}var l9=900000;function uz($){return{...o0,shortLimit:{...o0.shortLimit,holdBound:"cache-ttl",preference:"same-account-first",jitter:"none"},advance:{...o0.advance,opencode1:{...o0.advance.opencode1,statuses:$?.length?[...$]:[401,403,429]},pi:{...o0.advance.pi,statuses:$?.length?[...$]:[401,403,429]}},terminalMetadata:"setting-capped-fresh"}}function $2($,Z){return Number.isFinite($)&&$<=Z&&Z-$<=l9}function l6($){if(!$)return;let Z=Date.parse($);return Number.isFinite(Z)?Z:void 0}function pz($,Z){return["primary","secondary"].flatMap((J)=>{let X=$?.[J];if(!X||!$2(X.checkedAt,Z)||!Number.isFinite(X.usedPercent)||!(X.usedPercent>=100))return[];return[{window:J,confirmed:!0,confirmedByReading:!0,resetAt:l6(X.resetsAt),observedAt:X.checkedAt,provenance:"reading"}]})}function lz($,Z,J,X){let z=$.window==="primary"||$.window==="secondary",G=z?J?.[$.window]:void 0,B=G&&$2(G.checkedAt,X),W=$.window==="usage_limit_reached",Q=W&&$.resetAt!==void 0&&Number.isFinite($.resetAt)&&$.resetAt>0;return[{window:z?$.window:W?"usage":$.window,confirmed:z||W,confirmedByReading:!1,resetAt:z?B?l6(G.resetsAt):void 0:Q?$.resetAt:void 0,observedAt:z&&B?G.checkedAt:Z,provenance:z&&B?"reading":Q?"provider":"unproven"}]}function Pj($){let Z=$.body;if(typeof Z==="string")try{Z=JSON.parse(Z)}catch{Z=void 0}let J=R(Z)?Z:{},X=J.type==="response.failed"&&R(J.response)?J.response:void 0,z=R(X?.error)?X.error:R(J.error)?J.error:J,G=R(X?.failed)?X.failed.rate_limit_reached_type:void 0,B=typeof z.type==="string"?z.type:void 0,W=typeof z.code==="string"?z.code:void 0,Q=typeof G==="string"?G:X?W??B:B??W,Y=$.status??(typeof J.status==="number"?J.status:typeof J.status_code==="number"?J.status_code:void 0);if(Q!=="usage_limit_reached"&&!X&&Y!==429)return;if(X&&!Q)return;if(X&&Q!=="primary"&&Q!=="secondary"&&Q!=="usage_limit_reached"&&Q!=="rate_limit_exceeded")return;let{resets_at:V,resets_in_seconds:H}=z,q=typeof V==="number"&&Number.isFinite(V)&&V>0?V*1000:typeof H==="number"&&Number.isFinite(H)&&H>0?$.now+H*1000:void 0,U=X||B==="usage_limit_reached"?lz({window:Q??"rate_limit",resetAt:X?void 0:q},$.now,$.reading,$.now):[{window:Q??"rate_limit",confirmed:!1,confirmedByReading:!1,observedAt:$.now,provenance:"unproven"}],j=$.headers?.get("retry-after"),K=j?.trim()?Number(j):NaN;return{account:$.account,kind:U.some((N)=>N.confirmed)?"quota-exhausted":"rate-limit",reason:Q??"rate_limit",status:Y,scope:{kind:"pool"},windows:U,observedAt:$.now,...Number.isFinite(K)&&K>=0?{retryAfterMs:K*1000,retryAfterSource:"retry-after"}:{}}}function Mj($,Z,J){let X=new Map(pz(Z,J).map((z)=>[z.window,z]));for(let z of $?.windows??[]){if(!z.confirmed)continue;let G=X.get(z.window);if(!G||(z.resetAt??1/0)>=(G.resetAt??1/0))X.set(z.window,z)}return[...X.values()]}function tZ($,Z,J){if(Z===401||Z===403||!$.admitted)return!0;let X=$.confirmedBlockers?.filter((G)=>G.confirmed)??[],z=Math.max(...X.map((G)=>G.resetAt??NaN));return!Number.isFinite(z)||$.blockers.some((G)=>G.kind==="hard"&&(G.until??0)>J&&(G.until??0)>z)}function Cj($){if(tZ($.candidate,$.status,$.now))return;let Z=Y4({activity:$.activity,accountKey:$.candidate.account,maxSameAccountWait:$.maxSameAccountWait});return Z?{...Z,...$.maxDelayMs===void 0?{}:{maxDelayMs:$.maxDelayMs}}:void 0}function dz($){return!($.host!=="opencode2"&&$.mode==="ordered"&&$.status!==void 0&&!oZ({version:1,accounts:[],fallbackOn:$.fallbackOn}).includes($.status))}function eZ($,Z){if($.phase==="after-limit"&&!dz({...Z,host:$.host,status:$.status}))return;let J=$.candidates.find((z)=>$.attempted&&E(z.account,$.attempted)),X=!J||tZ(J,$.status,$.now);return(Z.decide??e1)({...$,hold:X?void 0:$.hold},uz(Z.fallbackOn))}function Oj($){let Z=$7($.reading,$.parsed.window,$.now,60000,$.parsed.resetAt),J=$.parsed.resetAt!==void 0&&Number.isFinite($.parsed.resetAt)&&$.parsed.resetAt>$.now,X=$.parsed.window==="primary"||$.parsed.window==="secondary"?$.reading?.[$.parsed.window]:void 0,z=!J&&X&&X.resetsAt&&Date.parse(X.resetsAt)===Z&&$2(X.checkedAt,$.now),G=J?$.resetSource==="retry-after"?"unproven":"provider":z?"reading":"unproven";return{command:{type:"mark",binding:$.binding,baseRevision:$.baseRevision,producerId:$.producerId,operationId:$.operationId,scope:{kind:"pool"},window:"account",cause:"rate-limit",until:Z,evidenceAt:$.evidenceAt,mergeLaw:"max-until"},provenance:{accountKey:$.binding.account,expiry:Z,branch:G,observedAt:z?X.checkedAt:$.observedAt,evidenceAt:$.evidenceAt}}}var d9=o("quota"),Z7="the account holds a tombstone from the removed vault custody, not a credential";function cz($){return $?.status===401}async function kj($,Z={}){let J=$.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let X=[],z=$.logger??d9,G=(U)=>{X.push(U);let j={pid:process.pid,accountId:U.account,status:U.ok?"ok":"error",...U.error?{error:U.error}:{}};if(U.ok)z.debug("quota refresh succeeded",j);else z.warn("quota refresh failed",j)},B=$.skipFresherThanMs,W=!1,Q;if(B!==void 0)try{Q=await $.readSidebarState()}catch{}let Y=new Map(Q?.fallbacks.map((U)=>[U.id,U])??[]),V=(...U)=>B!==void 0&&U.some((j)=>typeof j==="number"&&Number.isFinite(j)&&j<=$.now()&&$.now()-j<B),H=await $.loadAccounts($.paths).catch(()=>{return}),q=H?.mainAccountId??$.storageMainAccountId,F;if(!Z.accountKey||Z.accountKey==="main")try{let U=await $.getAuth();if(G7(U)){if(F=B7(H),!F)G({account:"main",ok:!1,error:O4(U)?Z7:"main account row is missing from the account pool"})}else if(U.type==="oauth"){let j=Q&&q!==void 0&&Q.main.mainAccountId===q?Q.main.quota:void 0;if(V($.quotaManager.peekMainForPolicy(q)?.checkedAt,j?.primary?.checkedAt,j?.secondary?.checkedAt,j?.checkedAt))G({account:"main",ok:!0});else{if(!U.access||(U.expires??0)<$.now()){let N=await $.refreshMainWithLease();U={...U,access:N.access,expires:N.expires}}if(U.access)if($.respectBackoff&&$.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let N=await J({accessToken:U.access,fetchImpl:$.fetchImpl,now:$.now,accountId:q,accountKey:"main"});$.quotaManager.setMain(U.access,{quota:N,refreshAfter:$.now()+300000,checkedAt:$.now()},q,!0),W=!0,G({account:"main",ok:!0})}else if(!X.some((N)=>N.account==="main"))G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(U){G({account:"main",ok:!1,error:x0(U)})}if(H)for(let U of H.accounts){let j=F!==void 0&&U===F;if(!j&&Z.accountKey&&(Z.accountKey==="main"||U.id!==Z.accountKey))continue;if(!j&&$.isOAuthAccountFn(U)&&z7(H,U)){if(Z.accountKey)G({account:U.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let K=j?U.accountId??q:void 0,N=(D,O,M)=>{if(j)$.quotaManager.setMain(O,D,K,!0);else $.quotaManager.setFallback(U.id,D,O,!0,M)};if(U.enabled===!1||!$.isOAuthAccountFn(U)){if(Z.accountKey)G({account:U.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let D=Y.get(U.id),O=U.accountId,M=j?Q&&K!==void 0&&Q.main.mainAccountId===K?Q.main.quota:void 0:D&&O!==void 0&&D.accountId===O?D.quota:void 0;if(V(j?$.quotaManager.peekMainForPolicy(K)?.checkedAt:$.quotaManager.peekFallbackForPolicy(U.id,O)?.checkedAt,M?.primary?.checkedAt,M?.secondary?.checkedAt,M?.checkedAt)){G({account:U.id,ok:!0});continue}if($.respectBackoff&&(j?$.quotaManager.isBackedOff():$.quotaManager.isFallbackBackedOff(U.id,U.access))){G({account:U.id,ok:!0});continue}let P=U.lastRefreshError;if(J7(P,U.refresh,$.now())){G({account:U.id,ok:!1,error:X7(P,$.now()),permanent:!0});continue}if(O4(U)){G({account:U.id,ok:!1,error:Z7});continue}let L;try{L=j?await $.fallbackManager.refreshAccount(U,H,{asPoolMain:!0}):await $.fallbackManager.refreshAccount(U,H)}catch(T){d9.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:U.id,error:x0(T)}),L=U}if(!L.access||(L.expires??0)<$.now()){G({account:U.id,ok:!1,error:"no usable access token"});continue}let C;try{C=await J({accessToken:L.access,fetchImpl:$.fetchImpl,now:$.now,accountId:L.accountId,accountKey:U.id})}catch(T){if(!cz(T))throw T;if(d9.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:U.id}),L=await $.fallbackManager.refreshAccount(U,H,j?{force:!0,asPoolMain:!0}:{force:!0}),!L.access){G({account:U.id,ok:!1,error:"no usable access token after forced refresh"});continue}C=await J({accessToken:L.access,fetchImpl:$.fetchImpl,now:$.now,accountId:L.accountId,accountKey:U.id})}N({quota:C,refreshAfter:$.now()+300000,checkedAt:$.now()},L.access,L.accountId),W=!0,G({account:U.id,ok:!0})}catch(D){G({account:U.id,ok:!1,error:x0(D)})}}if(Z.accountKey&&Z.accountKey!=="main"&&!X.some((U)=>U.account===Z.accountKey))X.push({account:Z.accountKey,ok:!1,error:"account not found"});if(B===void 0||W){let U=await $.loadAccounts($.paths);await $.writeSidebarState($.quotaManager,U)}return X}function sz($){try{let Z=JSON.parse($)?.model;if(typeof Z!=="string")return!1;let J=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/.exec(Z);if(!J)return!1;let X=Number(J[1]),z=Number(J[2]??0);return X>5||X===5&&z>=6}catch{return!1}}function gj($,Z=300000){return sz($)?1800000:Z}function fj($,Z,J,X){if(!J||X.kind==="synthetic")return!1;if(X.aborted)return!1;return(X.kind==="http"?X.completed&&!X.failed:X.kind==="ws"?X.event==="response.completed":X.kind==="pi"?X.stop==="stop":X.status>=200&&X.status<300)&&$.recordAccepted({sessionId:Z.sessionId,accountKey:Z.accountKey,currentAccountKey:J,lastAcceptedAt:Z.dispatchedAt,ttlMs:Z.ttlMs})}var Y7=["cost-cap","count-cap","outside-hours","session-ended","unsupported"];function A4($){return Y7.some((Z)=>Z===$)}var Q7=new Set;function V7($,Z=new Set){if(typeof $!=="object"||$===null)return`${typeof $}:${String($)}`;if(Z.has($))return"cycle";return Z.add($),`${Array.isArray($)?"array":"object"}:{${Object.entries(Object.getOwnPropertyDescriptors($)).sort(([J],[X])=>J.localeCompare(X)).map(([J,X])=>`${J}:${"value"in X?V7(X.value,Z):"accessor"}`).join(",")}}`}function S4($,Z){let J="unreadable";try{J=V7(Z)}catch{}try{let X=`${$}:${J}`;if(!Q7.has(X))Q7.add(X),console.warn(`[common-auth] Ignoring invalid session ${$} policy`)}catch{}return null}function c9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function az($){if(typeof $.then!=="function")return!1;return Promise.resolve($).catch(()=>{}),!0}function W7($,Z){return Reflect.ownKeys($).every((J)=>typeof J==="string"&&Z.includes(J))}function s9($){let Z;try{let J=t0($);if(!J)return null;let X=J.cache;if(typeof X!=="function")return null;if(Z=X.call(J),Z===null)return null;if(!c9(Z)||az(Z))return S4("cache",Z);let{ttl:z,keep_warm:G,hours:B}=Z;if(!W7(Z,["ttl","keep_warm","hours"])||z!==void 0&&z!=="none"&&z!=="short"&&z!=="long"||G!==void 0&&G!=="off"&&G!=="hours"&&G!=="always"&&G!=="auto"||z==="none"&&G!==void 0&&G!=="off"||G!=="hours"&&"hours"in Z)return S4("cache",Z);let W={...z!==void 0?{ttl:z}:{},...G!==void 0?{keep_warm:G}:{}};if(G==="hours"){if(!c9(B)||!W7(B,["from","to","tz"]))return S4("cache",Z);let{from:Q,to:Y,tz:V}=B,H=/^(?:[01]\d|2[0-3]):[0-5]\d$/;if(typeof Q!=="string"||!H.test(Q)||typeof Y!=="string"||!H.test(Y)||Q===Y||typeof V!=="string"||V.length===0)return S4("cache",Z);new Intl.DateTimeFormat("en",{timeZone:V}),W.hours={from:Q,to:Y,tz:V}}return W}catch{return S4("cache",Z)}}function H7($,Z){let J=t0($);if(!J)return;let X=J.report;if(typeof X!=="function")return;let z=X.call(J,Z);if(c9(z)&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}function d6($,Z){try{let{at:J,ttlMs:X,source:z}=Z;if(!Number.isSafeInteger(J)||J<0||X!=="implicit"&&(typeof X!=="number"||!Number.isFinite(X)||X<0)||z!=="response"&&z!=="warm")return;H7($,{kind:"cache_touch",at:J,ttl_ms:X,source:z})}catch{}}function a9($,Z){try{let{at:J,reason:X}=Z;if(!Number.isSafeInteger(J)||J<0||typeof X!=="string")return;H7($,{kind:"cache_warm_stopped",at:J,reason:X})}catch{}}function Z2($){return typeof $==="object"&&$!==null}function p0($){return typeof $==="string"&&$.length>0}function iz($){if(!Z2($)||Array.isArray($))return;let{ttlMs:Z,implicit:J,warming:X}=$,z={};if(!(Z!==void 0&&J!==void 0)){if(typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>0)z.ttl_ms=Z;else if(J===!0)z.implicit=!0}if(Z2(X)&&!Array.isArray(X)){let{on:G,stopReason:B}=X;if(typeof G==="boolean")z.warming={on:G,...!G&&A4(B)?{stop_reason:B}:{}}}return Object.keys(z).length>0?z:void 0}function U7($){if(!Z2($)||Array.isArray($))return;let Z={};for(let[X,z]of[["input","input"],["output","output"],["cacheRead","cache_read"],["cacheWrite","cache_write"],["cacheWrite5m","cache_write_5m"],["cacheWrite1h","cache_write_1h"],["reasoning","reasoning"]]){let G=$[X];if(typeof G==="number"&&Number.isSafeInteger(G)&&G>=0)Z[z]=G}let J=$.reasoningIncludedInOutput;if(typeof J==="boolean")Z.reasoning_included_in_output=J;return Object.keys(Z).length>0?Z:void 0}function nz($,Z){if(!Z2($))return;let{account_id:J,credential_id:X}=$;if(typeof J!=="string")return;if(X!==void 0&&typeof X!=="string")return;let z=Z.find((W)=>W.accountId===J&&(X===void 0||W.credentialId===X));if(!z)return;let G=$.hold,B=Z2(G)?G.retry_after_ms:void 0;if(typeof B==="number"&&Number.isFinite(B)&&B>=0)return{candidate:z,hold:{retry_after_ms:B}};return{candidate:z}}async function q7($){let Z;try{let J=t0($.sessionId);if(!J)return;let X=J.accountFor;if(typeof X!=="function")return;let z=$.deadlineMs??500,G=Number.isNaN(z)?500:Math.min(2000,Math.max(1,z)),B=new Promise((H)=>{Z=setTimeout(()=>H(void 0),G),Z.unref()}),W={provider:$.provider,modelId:$.modelId},Q=$.holdWaitMaxS;if(typeof Q==="number"&&Number.isFinite(Q))W.hold_wait_max_s=Math.max(0,Math.floor(Q));let Y=X.call(J,W,{deadlineMs:G});if(!Z2(Y)||typeof Y.then!=="function")return;let V=await Promise.race([Y,B]);return nz(V,$.candidates)}catch{return}finally{clearTimeout(Z)}}function E4($){try{let Z=t0($.sessionId);if(!Z)return;let J=Z.report;if(typeof J!=="function")return;let X;if("kind"in $)switch($.kind){case"billing":{let{attemptId:G,requestKind:B,credentialId:W,provider:Q,model:Y,outcome:V,accountId:H,providerRequestId:q,providerResponseId:F,userMessageId:U,status:j,attempt:K,chargeBasis:N,usage:D,usageByModel:O,cache:M}=$;if(!p0(G)||!p0(W)||!p0(Q)||!p0(Y)||B!=="primary"&&B!=="title"&&B!=="compaction"&&B!=="generate"&&B!=="keep_warm"&&B!=="prime"||V!=="completed"&&V!=="cut"&&V!=="failed")return;let P=U7(D),L=iz(M),C=[];if(Array.isArray(O))for(let T of O){if(!Z2(T)||Array.isArray(T))continue;let A=T.modelUsed;if(!p0(A))continue;let x=U7(T.usage);if(!x)continue;C.push({model_used:A,usage:x})}X={kind:"billing",attempt_id:G,request_kind:B,credential_id:W,provider:Q,model:Y,outcome:V,...p0(H)?{account_id:H}:{},...p0(q)?{provider_request_id:q}:{},...p0(F)?{provider_response_id:F}:{},...p0(U)?{user_message_id:U}:{},...typeof j==="number"&&Number.isInteger(j)&&j>=0?{status:j}:{},...typeof K==="number"&&Number.isInteger(K)&&K>=1?{attempt:K}:{},...N==="subscription_included"||N==="metered_api"?{charge_basis:N}:{},...P?{usage:P}:{},...C.length>0?{usage_by_model:C}:{},...L?{cache:L}:{}};break}case"turn_notes_supported":{let{model:G,supported:B}=$;if(typeof G!=="string"||G.length===0||typeof B!=="boolean")return;X={kind:"turn_notes_supported",model:G,supported:B};break}case"turn_note_skipped":{let{after_tool_use_id:G,reason:B}=$;if(typeof G!=="string"||G.length===0||B!=="anchor_missing"&&B!=="before_user_message"&&B!=="unsupported_model"&&B!=="not_oauth")return;X={kind:"turn_note_skipped",after_tool_use_id:G,reason:B};break}default:return}else{let G={account_id:$.accountId,...$.credentialId!==void 0?{credential_id:$.credentialId}:{}};switch($.outcome){case"served":X={...G,outcome:"served",headers:$.headers};break;case"exhausted":{let{window:B,pool:W}=$;if(B!=="5h"&&B!=="7d")return;if(W!==void 0&&(typeof W!=="string"||!/^[a-z0-9._-]{1,64}$/.test(W)))return;X={...G,outcome:"exhausted",window:B,...W?{pool:W}:{},...$.resetsAt!==void 0?{resets_at:$.resetsAt}:{}};break}default:return}}let z=J.call(Z,X);if(Z2(z)&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}catch{}}function j7($){if($.accountKey)return F9({...$,accountKey:$.accountKey});try{let Z=Reflect.get(globalThis,Symbol.for("cortexkit.routing"));return typeof(typeof Z==="function"?Z($.sessionId):void 0)?.accountFor==="function"?0:void 0}catch{return}}function c6(){try{return typeof Reflect.get(globalThis,Symbol.for("cortexkit.routing"))==="function"}catch{return!1}}function rz($){return $&&!["title","compaction","summary"].includes($)?"primary":"auxiliary"}function tj($,Z){if(typeof $!=="string")return;try{let J=JSON.parse($);return typeof J?.model==="string"?{modelId:J.model,kind:rz(Z)}:void 0}catch{return}}async function ej($){let{request:Z,sessionId:J}=$;if(!$.vaultMode||!$.fresh||!J||!Z?.modelId||Z.kind!=="primary"||Z.retry)return;let X=N7({...$.routing,placement:"roster",mainId:null});if(X.kind==="block")return;let z=new Set($.eligibleIds??X.order),G=$.routes.flatMap((W)=>X.order.includes(W.id)&&z.has(W.id)&&W.identity&&W.credentialId?[{accountId:W.identity,credentialId:W.credentialId,id:W.id}]:[]);if(G.length===0)return;return(await q7({sessionId:J,provider:"openai",modelId:Z.modelId,candidates:G,holdWaitMaxS:j7({...$.wait,sessionId:J,now:$.routing.now})}))?.candidate.id}var oz=["x-codex-primary-used-percent","x-codex-primary-window-minutes","x-codex-primary-reset-at","x-codex-secondary-used-percent","x-codex-secondary-window-minutes","x-codex-secondary-reset-at","retry-after","retry-after-ms"],F7=new Set(["usage_limit_reached","insufficient_quota","quota_exceeded"]);function tz($,Z){let J=$.get("retry-after-ms");if(J!==null&&Number.isFinite(Number(J))&&Number(J)>=0)return Z+Number(J);let X=$.get("retry-after");if(X===null)return;let z=Number(X);if(Number.isFinite(z)&&z>=0)return Z+z*1000;let G=Date.parse(X);return Number.isFinite(G)?G:void 0}function i9($,Z,J){if(!$||!Z?.accountIdentity||J.failed||!c6())return;let{status:X,headers:z}=J,G={sessionId:$,accountId:Z.accountIdentity,credentialId:Z.credentialId};if(X===429){let W=R(J.body)?J.body:void 0,Q=R(W?.error)?W.error:W,Y=J.limit?.window,V=typeof Q?.code==="string"?Q.code:void 0,H=Y&&F7.has(Y)?Y:V&&F7.has(V)?V:void 0;if(!H)return;let q=typeof Q?.rate_limit_reached_type==="string"?Q.rate_limit_reached_type:typeof Q?.window==="string"?Q.window:H,F=K7(J.quota),U=q==="primary"||q==="secondary"?q:void 0,j=U?Number(z.get(`x-codex-${U}-window-minutes`)??F?.[U]?.windowMinutes):void 0,K=j===300?"5h":j===10080?"7d":q;if(K!=="5h"&&K!=="7d")return;let N=U?Number(z.get(`x-codex-${U}-reset-at`))*1000:NaN,D=J.limit?.resetAt,O=D!==void 0&&Number.isFinite(D)&&D>0?D:Number.isFinite(N)&&N>0?N:tz(z,J.now??Date.now());E4({...G,outcome:"exhausted",window:K,...O!==void 0?{resetsAt:O}:{}});return}if(X<200||X>=300)return;let B={};for(let W of oz){let Q=z.get(W);if(Q!==null)B[W]=Q}E4({...G,outcome:"served",headers:B})}function ez($){return R($)&&($.type==="error"||$.type==="response.failed"||R($.response)&&$.response.status==="failed")}function $G($){return $.includes('"response.failed"')||$.includes('"type":"error"')||$.includes('"error"')&&/"type"\s*:\s*"error"/.test($)||$.includes('"failed"')&&/"status"\s*:\s*"failed"/.test($)}function $F($,Z,J,X){if(!c6()||!$||!Z.accountIdentity)return J;let z={status:J.status,headers:J.headers,quota:X.quota};if(J.status===429){try{J.clone().json().then((q)=>{i9($,Z,{...z,body:q,limit:X.parseLimit(q),now:X.now?.()})}).catch(()=>{})}catch{}return J}if(!J.ok)return J;if(!J.body)return i9($,Z,z),J;let G=J.headers.get("content-type")?.includes("text/event-stream"),B=new TextDecoder,W="",Q=!1,Y=(q)=>{if(Q)return;if(q.startsWith("event:")&&q.slice(6).trim()==="error")Q=!0;if(!q.startsWith("data:")||!$G(q))return;try{Q||=ez(JSON.parse(q.slice(5)))}catch{}},V=J.body.pipeThrough(new TransformStream({transform(q,F){if(G&&!Q){W+=B.decode(q,{stream:!0});let U=W.indexOf(`
|
|
67
|
+
${G[z]??"The server returned a no-op result. No reset was confirmed."}`)}function rZ($,Z){return JSON.stringify(["openai","pool",F4($),F4(Z)])}function oZ($){return JSON.stringify(["openai","vault",F4($)])}function wz($,Z){let J=Z.kind==="vault"?Z.routeId:Z.id,X=Z.kind==="pool"?Z.credentialEpoch:Z.kind==="vault"?Z.addedAt:Z.verifiedIdentity;if(X===void 0||X==="")return;return{namespace:$,accountId:J,incarnation:String(X)}}function jj($,Z){let J=wz($,{kind:"pool",...Z});return J?{account:J,credentialEpoch:J.incarnation,identity:Z.identity}:void 0}function Fj($,Z){return{account:{namespace:$,accountId:Z.routeId,incarnation:String(Z.addedAt)},credentialEpoch:String(Z.addedAt),identity:Z.accountIdentity}}function y($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function p9($){return JSON.stringify($.map((Z)=>[y(Z.account),Z.credentialEpoch,Z.identity??null]).sort((Z,J)=>JSON.stringify(Z).localeCompare(JSON.stringify(J))))}var l9=900000;function uz($){return{...o0,shortLimit:{...o0.shortLimit,holdBound:"cache-ttl",preference:"same-account-first",jitter:"none"},advance:{...o0.advance,opencode1:{...o0.advance.opencode1,statuses:$?.length?[...$]:[401,403,429]},pi:{...o0.advance.pi,statuses:$?.length?[...$]:[401,403,429]}},terminalMetadata:"setting-capped-fresh"}}function $2($,Z){return Number.isFinite($)&&$<=Z&&Z-$<=l9}function d6($){if(!$)return;let Z=Date.parse($);return Number.isFinite(Z)?Z:void 0}function pz($,Z){return["primary","secondary"].flatMap((J)=>{let X=$?.[J];if(!X||!$2(X.checkedAt,Z)||!Number.isFinite(X.usedPercent)||!(X.usedPercent>=100))return[];return[{window:J,confirmed:!0,confirmedByReading:!0,resetAt:d6(X.resetsAt),observedAt:X.checkedAt,provenance:"reading"}]})}function lz($,Z,J,X){let z=$.window==="primary"||$.window==="secondary",G=z?J?.[$.window]:void 0,B=G&&$2(G.checkedAt,X),W=$.window==="usage_limit_reached",Q=W&&$.resetAt!==void 0&&Number.isFinite($.resetAt)&&$.resetAt>0;return[{window:z?$.window:W?"usage":$.window,confirmed:z||W,confirmedByReading:!1,resetAt:z?B?d6(G.resetsAt):void 0:Q?$.resetAt:void 0,observedAt:z&&B?G.checkedAt:Z,provenance:z&&B?"reading":Q?"provider":"unproven"}]}function Mj($){let Z=$.body;if(typeof Z==="string")try{Z=JSON.parse(Z)}catch{Z=void 0}let J=E(Z)?Z:{},X=J.type==="response.failed"&&E(J.response)?J.response:void 0,z=E(X?.error)?X.error:E(J.error)?J.error:J,G=E(X?.failed)?X.failed.rate_limit_reached_type:void 0,B=typeof z.type==="string"?z.type:void 0,W=typeof z.code==="string"?z.code:void 0,Q=typeof G==="string"?G:X?W??B:B??W,Y=$.status??(typeof J.status==="number"?J.status:typeof J.status_code==="number"?J.status_code:void 0);if(Q!=="usage_limit_reached"&&!X&&Y!==429)return;if(X&&!Q)return;if(X&&Q!=="primary"&&Q!=="secondary"&&Q!=="usage_limit_reached"&&Q!=="rate_limit_exceeded")return;let{resets_at:V,resets_in_seconds:H}=z,q=typeof V==="number"&&Number.isFinite(V)&&V>0?V*1000:typeof H==="number"&&Number.isFinite(H)&&H>0?$.now+H*1000:void 0,U=X||B==="usage_limit_reached"?lz({window:Q??"rate_limit",resetAt:X?void 0:q},$.now,$.reading,$.now):[{window:Q??"rate_limit",confirmed:!1,confirmedByReading:!1,observedAt:$.now,provenance:"unproven"}],j=$.headers?.get("retry-after"),K=j?.trim()?Number(j):NaN;return{account:$.account,kind:U.some((N)=>N.confirmed)?"quota-exhausted":"rate-limit",reason:Q??"rate_limit",status:Y,scope:{kind:"pool"},windows:U,observedAt:$.now,...Number.isFinite(K)&&K>=0?{retryAfterMs:K*1000,retryAfterSource:"retry-after"}:{}}}function Cj($,Z,J){let X=new Map(pz(Z,J).map((z)=>[z.window,z]));for(let z of $?.windows??[]){if(!z.confirmed)continue;let G=X.get(z.window);if(!G||(z.resetAt??1/0)>=(G.resetAt??1/0))X.set(z.window,z)}return[...X.values()]}function eZ($,Z,J){if(Z===401||Z===403||!$.admitted)return!0;let X=$.confirmedBlockers?.filter((G)=>G.confirmed)??[],z=Math.max(...X.map((G)=>G.resetAt??NaN));return!Number.isFinite(z)||$.blockers.some((G)=>G.kind==="hard"&&(G.until??0)>J&&(G.until??0)>z)}function Tj($){if(eZ($.candidate,$.status,$.now))return;let Z=Y4({activity:$.activity,accountKey:$.candidate.account,maxSameAccountWait:$.maxSameAccountWait});return Z?{...Z,...$.maxDelayMs===void 0?{}:{maxDelayMs:$.maxDelayMs}}:void 0}function dz($){return!($.host!=="opencode2"&&$.mode==="ordered"&&$.status!==void 0&&!tZ({version:1,accounts:[],fallbackOn:$.fallbackOn}).includes($.status))}function $7($,Z){if($.phase==="after-limit"&&!dz({...Z,host:$.host,status:$.status}))return;let J=$.candidates.find((z)=>$.attempted&&R(z.account,$.attempted)),X=!J||eZ(J,$.status,$.now);return(Z.decide??e1)({...$,hold:X?void 0:$.hold},uz(Z.fallbackOn))}function Sj($){let Z=Z7($.reading,$.parsed.window,$.now,60000,$.parsed.resetAt),J=$.parsed.resetAt!==void 0&&Number.isFinite($.parsed.resetAt)&&$.parsed.resetAt>$.now,X=$.parsed.window==="primary"||$.parsed.window==="secondary"?$.reading?.[$.parsed.window]:void 0,z=!J&&X&&X.resetsAt&&Date.parse(X.resetsAt)===Z&&$2(X.checkedAt,$.now),G=J?$.resetSource==="retry-after"?"unproven":"provider":z?"reading":"unproven";return{command:{type:"mark",binding:$.binding,baseRevision:$.baseRevision,producerId:$.producerId,operationId:$.operationId,scope:{kind:"pool"},window:"account",cause:"rate-limit",until:Z,evidenceAt:$.evidenceAt,mergeLaw:"max-until"},provenance:{accountKey:$.binding.account,expiry:Z,branch:G,observedAt:z?X.checkedAt:$.observedAt,evidenceAt:$.evidenceAt}}}var d9=o("quota"),J7="the account holds a tombstone from the removed vault custody, not a credential";function cz($){return $?.status===401}async function xj($,Z={}){let J=$.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let X=[],z=$.logger??d9,G=(U)=>{X.push(U);let j={pid:process.pid,accountId:U.account,status:U.ok?"ok":"error",...U.error?{error:U.error}:{}};if(U.ok)z.debug("quota refresh succeeded",j);else z.warn("quota refresh failed",j)},B=$.skipFresherThanMs,W=!1,Q;if(B!==void 0)try{Q=await $.readSidebarState()}catch{}let Y=new Map(Q?.fallbacks.map((U)=>[U.id,U])??[]),V=(...U)=>B!==void 0&&U.some((j)=>typeof j==="number"&&Number.isFinite(j)&&j<=$.now()&&$.now()-j<B),H=await $.loadAccounts($.paths).catch(()=>{return}),q=H?.mainAccountId??$.storageMainAccountId,F;if(!Z.accountKey||Z.accountKey==="main")try{let U=await $.getAuth();if(B7(U)){if(F=Q7(H),!F)G({account:"main",ok:!1,error:O4(U)?J7:"main account row is missing from the account pool"})}else if(U.type==="oauth"){let j=Q&&q!==void 0&&Q.main.mainAccountId===q?Q.main.quota:void 0;if(V($.quotaManager.peekMainForPolicy(q)?.checkedAt,j?.primary?.checkedAt,j?.secondary?.checkedAt,j?.checkedAt))G({account:"main",ok:!0});else{if(!U.access||(U.expires??0)<$.now()){let N=await $.refreshMainWithLease();U={...U,access:N.access,expires:N.expires}}if(U.access)if($.respectBackoff&&$.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let N=await J({accessToken:U.access,fetchImpl:$.fetchImpl,now:$.now,accountId:q,accountKey:"main"});$.quotaManager.setMain(U.access,{quota:N,refreshAfter:$.now()+300000,checkedAt:$.now()},q,!0),W=!0,G({account:"main",ok:!0})}else if(!X.some((N)=>N.account==="main"))G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(U){G({account:"main",ok:!1,error:x0(U)})}if(H)for(let U of H.accounts){let j=F!==void 0&&U===F;if(!j&&Z.accountKey&&(Z.accountKey==="main"||U.id!==Z.accountKey))continue;if(!j&&$.isOAuthAccountFn(U)&&G7(H,U)){if(Z.accountKey)G({account:U.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let K=j?U.accountId??q:void 0,N=(D,O,M)=>{if(j)$.quotaManager.setMain(O,D,K,!0);else $.quotaManager.setFallback(U.id,D,O,!0,M)};if(U.enabled===!1||!$.isOAuthAccountFn(U)){if(Z.accountKey)G({account:U.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let D=Y.get(U.id),O=U.accountId,M=j?Q&&K!==void 0&&Q.main.mainAccountId===K?Q.main.quota:void 0:D&&O!==void 0&&D.accountId===O?D.quota:void 0;if(V(j?$.quotaManager.peekMainForPolicy(K)?.checkedAt:$.quotaManager.peekFallbackForPolicy(U.id,O)?.checkedAt,M?.primary?.checkedAt,M?.secondary?.checkedAt,M?.checkedAt)){G({account:U.id,ok:!0});continue}if($.respectBackoff&&(j?$.quotaManager.isBackedOff():$.quotaManager.isFallbackBackedOff(U.id,U.access))){G({account:U.id,ok:!0});continue}let P=U.lastRefreshError;if(X7(P,U.refresh,$.now())){G({account:U.id,ok:!1,error:z7(P,$.now()),permanent:!0});continue}if(O4(U)){G({account:U.id,ok:!1,error:J7});continue}let L;try{L=j?await $.fallbackManager.refreshAccount(U,H,{asPoolMain:!0}):await $.fallbackManager.refreshAccount(U,H)}catch(T){d9.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:U.id,error:x0(T)}),L=U}if(!L.access||(L.expires??0)<$.now()){G({account:U.id,ok:!1,error:"no usable access token"});continue}let C;try{C=await J({accessToken:L.access,fetchImpl:$.fetchImpl,now:$.now,accountId:L.accountId,accountKey:U.id})}catch(T){if(!cz(T))throw T;if(d9.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:U.id}),L=await $.fallbackManager.refreshAccount(U,H,j?{force:!0,asPoolMain:!0}:{force:!0}),!L.access){G({account:U.id,ok:!1,error:"no usable access token after forced refresh"});continue}C=await J({accessToken:L.access,fetchImpl:$.fetchImpl,now:$.now,accountId:L.accountId,accountKey:U.id})}N({quota:C,refreshAfter:$.now()+300000,checkedAt:$.now()},L.access,L.accountId),W=!0,G({account:U.id,ok:!0})}catch(D){G({account:U.id,ok:!1,error:x0(D)})}}if(Z.accountKey&&Z.accountKey!=="main"&&!X.some((U)=>U.account===Z.accountKey))X.push({account:Z.accountKey,ok:!1,error:"account not found"});if(B===void 0||W){let U=await $.loadAccounts($.paths);await $.writeSidebarState($.quotaManager,U)}return X}function sz($){try{let Z=JSON.parse($)?.model;if(typeof Z!=="string")return!1;let J=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/.exec(Z);if(!J)return!1;let X=Number(J[1]),z=Number(J[2]??0);return X>5||X===5&&z>=6}catch{return!1}}function fj($,Z=300000){return sz($)?1800000:Z}function vj($,Z,J,X){if(!J||X.kind==="synthetic")return!1;if(X.aborted)return!1;return(X.kind==="http"?X.completed&&!X.failed:X.kind==="ws"?X.event==="response.completed":X.kind==="pi"?X.stop==="stop":X.status>=200&&X.status<300)&&$.recordAccepted({sessionId:Z.sessionId,accountKey:Z.accountKey,currentAccountKey:J,lastAcceptedAt:Z.dispatchedAt,ttlMs:Z.ttlMs})}var V7=["cost-cap","count-cap","outside-hours","session-ended","unsupported"];function A4($){return V7.some((Z)=>Z===$)}var W7=new Set;function H7($,Z=new Set){if(typeof $!=="object"||$===null)return`${typeof $}:${String($)}`;if(Z.has($))return"cycle";return Z.add($),`${Array.isArray($)?"array":"object"}:{${Object.entries(Object.getOwnPropertyDescriptors($)).sort(([J],[X])=>J.localeCompare(X)).map(([J,X])=>`${J}:${"value"in X?H7(X.value,Z):"accessor"}`).join(",")}}`}function S4($,Z){let J="unreadable";try{J=H7(Z)}catch{}try{let X=`${$}:${J}`;if(!W7.has(X))W7.add(X),console.warn(`[common-auth] Ignoring invalid session ${$} policy`)}catch{}return null}function c9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function az($){if(typeof $.then!=="function")return!1;return Promise.resolve($).catch(()=>{}),!0}function Y7($,Z){return Reflect.ownKeys($).every((J)=>typeof J==="string"&&Z.includes(J))}function s9($){let Z;try{let J=t0($);if(!J)return null;let X=J.cache;if(typeof X!=="function")return null;if(Z=X.call(J),Z===null)return null;if(!c9(Z)||az(Z))return S4("cache",Z);let{ttl:z,keep_warm:G,hours:B}=Z;if(!Y7(Z,["ttl","keep_warm","hours"])||z!==void 0&&z!=="none"&&z!=="short"&&z!=="long"||G!==void 0&&G!=="off"&&G!=="hours"&&G!=="always"&&G!=="auto"||z==="none"&&G!==void 0&&G!=="off"||G!=="hours"&&"hours"in Z)return S4("cache",Z);let W={...z!==void 0?{ttl:z}:{},...G!==void 0?{keep_warm:G}:{}};if(G==="hours"){if(!c9(B)||!Y7(B,["from","to","tz"]))return S4("cache",Z);let{from:Q,to:Y,tz:V}=B,H=/^(?:[01]\d|2[0-3]):[0-5]\d$/;if(typeof Q!=="string"||!H.test(Q)||typeof Y!=="string"||!H.test(Y)||Q===Y||typeof V!=="string"||V.length===0)return S4("cache",Z);new Intl.DateTimeFormat("en",{timeZone:V}),W.hours={from:Q,to:Y,tz:V}}return W}catch{return S4("cache",Z)}}function U7($,Z){let J=t0($);if(!J)return;let X=J.report;if(typeof X!=="function")return;let z=X.call(J,Z);if(c9(z)&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}function c6($,Z){try{let{at:J,ttlMs:X,source:z}=Z;if(!Number.isSafeInteger(J)||J<0||X!=="implicit"&&(typeof X!=="number"||!Number.isFinite(X)||X<0)||z!=="response"&&z!=="warm")return;U7($,{kind:"cache_touch",at:J,ttl_ms:X,source:z})}catch{}}function a9($,Z){try{let{at:J,reason:X}=Z;if(!Number.isSafeInteger(J)||J<0||typeof X!=="string")return;U7($,{kind:"cache_warm_stopped",at:J,reason:X})}catch{}}function Z2($){return typeof $==="object"&&$!==null}function p0($){return typeof $==="string"&&$.length>0}function nz($){if(!Z2($)||Array.isArray($))return;let{ttlMs:Z,implicit:J,warming:X}=$,z={};if(!(Z!==void 0&&J!==void 0)){if(typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>0)z.ttl_ms=Z;else if(J===!0)z.implicit=!0}if(Z2(X)&&!Array.isArray(X)){let{on:G,stopReason:B}=X;if(typeof G==="boolean")z.warming={on:G,...!G&&A4(B)?{stop_reason:B}:{}}}return Object.keys(z).length>0?z:void 0}function q7($){if(!Z2($)||Array.isArray($))return;let Z={};for(let[X,z]of[["input","input"],["output","output"],["cacheRead","cache_read"],["cacheWrite","cache_write"],["cacheWrite5m","cache_write_5m"],["cacheWrite1h","cache_write_1h"],["reasoning","reasoning"]]){let G=$[X];if(typeof G==="number"&&Number.isSafeInteger(G)&&G>=0)Z[z]=G}let J=$.reasoningIncludedInOutput;if(typeof J==="boolean")Z.reasoning_included_in_output=J;return Object.keys(Z).length>0?Z:void 0}function iz($,Z){if(!Z2($))return;let{account_id:J,credential_id:X}=$;if(typeof J!=="string")return;if(X!==void 0&&typeof X!=="string")return;let z=Z.find((W)=>W.accountId===J&&(X===void 0||W.credentialId===X));if(!z)return;let G=$.hold,B=Z2(G)?G.retry_after_ms:void 0;if(typeof B==="number"&&Number.isFinite(B)&&B>=0)return{candidate:z,hold:{retry_after_ms:B}};return{candidate:z}}async function j7($){let Z;try{let J=t0($.sessionId);if(!J)return;let X=J.accountFor;if(typeof X!=="function")return;let z=$.deadlineMs??500,G=Number.isNaN(z)?500:Math.min(2000,Math.max(1,z)),B=new Promise((H)=>{Z=setTimeout(()=>H(void 0),G),Z.unref()}),W={provider:$.provider,modelId:$.modelId},Q=$.holdWaitMaxS;if(typeof Q==="number"&&Number.isFinite(Q))W.hold_wait_max_s=Math.max(0,Math.floor(Q));let Y=X.call(J,W,{deadlineMs:G});if(!Z2(Y)||typeof Y.then!=="function")return;let V=await Promise.race([Y,B]);return iz(V,$.candidates)}catch{return}finally{clearTimeout(Z)}}function E4($){try{let Z=t0($.sessionId);if(!Z)return;let J=Z.report;if(typeof J!=="function")return;let X;if("kind"in $)switch($.kind){case"billing":{let{attemptId:G,requestKind:B,credentialId:W,provider:Q,model:Y,outcome:V,accountId:H,providerRequestId:q,providerResponseId:F,userMessageId:U,status:j,attempt:K,chargeBasis:N,usage:D,usageByModel:O,cache:M}=$;if(!p0(G)||!p0(W)||!p0(Q)||!p0(Y)||B!=="primary"&&B!=="title"&&B!=="compaction"&&B!=="generate"&&B!=="keep_warm"&&B!=="prime"||V!=="completed"&&V!=="cut"&&V!=="failed")return;let P=q7(D),L=nz(M),C=[];if(Array.isArray(O))for(let T of O){if(!Z2(T)||Array.isArray(T))continue;let A=T.modelUsed;if(!p0(A))continue;let x=q7(T.usage);if(!x)continue;C.push({model_used:A,usage:x})}X={kind:"billing",attempt_id:G,request_kind:B,credential_id:W,provider:Q,model:Y,outcome:V,...p0(H)?{account_id:H}:{},...p0(q)?{provider_request_id:q}:{},...p0(F)?{provider_response_id:F}:{},...p0(U)?{user_message_id:U}:{},...typeof j==="number"&&Number.isInteger(j)&&j>=0?{status:j}:{},...typeof K==="number"&&Number.isInteger(K)&&K>=1?{attempt:K}:{},...N==="subscription_included"||N==="metered_api"?{charge_basis:N}:{},...P?{usage:P}:{},...C.length>0?{usage_by_model:C}:{},...L?{cache:L}:{}};break}case"turn_notes_supported":{let{model:G,supported:B}=$;if(typeof G!=="string"||G.length===0||typeof B!=="boolean")return;X={kind:"turn_notes_supported",model:G,supported:B};break}case"turn_note_skipped":{let{after_tool_use_id:G,reason:B}=$;if(typeof G!=="string"||G.length===0||B!=="anchor_missing"&&B!=="before_user_message"&&B!=="unsupported_model"&&B!=="not_oauth")return;X={kind:"turn_note_skipped",after_tool_use_id:G,reason:B};break}default:return}else{let G={account_id:$.accountId,...$.credentialId!==void 0?{credential_id:$.credentialId}:{}};switch($.outcome){case"served":X={...G,outcome:"served",headers:$.headers};break;case"exhausted":{let{window:B,pool:W}=$;if(B!=="5h"&&B!=="7d")return;if(W!==void 0&&(typeof W!=="string"||!/^[a-z0-9._-]{1,64}$/.test(W)))return;X={...G,outcome:"exhausted",window:B,...W?{pool:W}:{},...$.resetsAt!==void 0?{resets_at:$.resetsAt}:{}};break}default:return}}let z=J.call(Z,X);if(Z2(z)&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}catch{}}function F7($){if($.accountKey)return F9({...$,accountKey:$.accountKey});try{let Z=Reflect.get(globalThis,Symbol.for("cortexkit.routing"));return typeof(typeof Z==="function"?Z($.sessionId):void 0)?.accountFor==="function"?0:void 0}catch{return}}function R4(){try{return typeof Reflect.get(globalThis,Symbol.for("cortexkit.routing"))==="function"}catch{return!1}}function rz($){return $&&!["title","compaction","summary"].includes($)?"primary":"auxiliary"}function ej($,Z){if(typeof $!=="string")return;try{let J=JSON.parse($);return typeof J?.model==="string"?{modelId:J.model,kind:rz(Z)}:void 0}catch{return}}async function $F($){let{request:Z,sessionId:J}=$;if(!$.vaultMode||!$.fresh||!J||!Z?.modelId||Z.kind!=="primary"||Z.retry)return;let X=N7({...$.routing,placement:"roster",mainId:null});if(X.kind==="block")return;let z=new Set($.eligibleIds??X.order),G=$.routes.flatMap((W)=>X.order.includes(W.id)&&z.has(W.id)&&W.identity&&W.credentialId?[{accountId:W.identity,credentialId:W.credentialId,id:W.id}]:[]);if(G.length===0)return;return(await j7({sessionId:J,provider:"openai",modelId:Z.modelId,candidates:G,holdWaitMaxS:F7({...$.wait,sessionId:J,now:$.routing.now})}))?.candidate.id}var oz=["x-codex-primary-used-percent","x-codex-primary-window-minutes","x-codex-primary-reset-at","x-codex-secondary-used-percent","x-codex-secondary-window-minutes","x-codex-secondary-reset-at","retry-after","retry-after-ms"],i9=new Set(["usage_limit_reached","insufficient_quota","quota_exceeded"]);function tz($,Z){let J=$.get("retry-after-ms");if(J!==null&&Number.isFinite(Number(J))&&Number(J)>=0)return Z+Number(J);let X=$.get("retry-after");if(X===null)return;let z=Number(X);if(Number.isFinite(z)&&z>=0)return Z+z*1000;let G=Date.parse(X);return Number.isFinite(G)?G:void 0}function ez($,Z,J,X={}){if(!R4()||!$||!Z?.accountIdentity)return;if(!i9.has(J.window)&&!["primary","secondary","5h","7d"].includes(J.window))return;let z=E(X.body)?X.body:void 0,G=E(z?.response)?z.response:z,B=E(G?.error)?G.error:G,W=E(G?.failed)?G.failed:void 0,Q=typeof W?.rate_limit_reached_type==="string"?W.rate_limit_reached_type:typeof B?.rate_limit_reached_type==="string"?B.rate_limit_reached_type:typeof B?.window==="string"?B.window:J.window,Y=K7(X.quota),V=Q==="primary"||Q==="secondary"?Q:void 0,H=V?Number(X.headers?.get(`x-codex-${V}-window-minutes`)??Y?.[V]?.windowMinutes):void 0,q=H===300?"5h":H===10080?"7d":Q;if(q!=="5h"&&q!=="7d")return;let F=V?Number(X.headers?.get(`x-codex-${V}-reset-at`))*1000:NaN,U=B?.resets_at??W?.resets_at,j=B?.resets_in_seconds??W?.resets_in_seconds,K=typeof U==="number"&&Number.isFinite(U)&&U>0?U*1000:typeof j==="number"&&Number.isFinite(j)&&j>0?(X.now??Date.now())+j*1000:void 0,N=J.resetAt??K,D=N!==void 0&&Number.isFinite(N)&&N>0?N:Number.isFinite(F)&&F>0?F:X.headers?tz(X.headers,X.now??Date.now()):void 0;E4({sessionId:$,accountId:Z.accountIdentity,credentialId:Z.credentialId,outcome:"exhausted",window:q,...D!==void 0?{resetsAt:D}:{}})}function n9($,Z,J){if(!$||!Z?.accountIdentity||J.failed||!R4())return;let{status:X,headers:z}=J,G={sessionId:$,accountId:Z.accountIdentity,credentialId:Z.credentialId};if(X===429){let W=E(J.body)?J.body:void 0,Q=E(W?.error)?W.error:W,Y=J.limit?.window,V=typeof Q?.code==="string"?Q.code:void 0,H=Y&&i9.has(Y)?Y:V&&i9.has(V)?V:void 0;if(!H)return;let q=typeof Q?.rate_limit_reached_type==="string"?Q.rate_limit_reached_type:typeof Q?.window==="string"?Q.window:H;ez($,Z,{window:q,resetAt:J.limit?.resetAt},{headers:z,quota:J.quota,now:J.now});return}if(X<200||X>=300)return;let B={};for(let W of oz){let Q=z.get(W);if(Q!==null)B[W]=Q}E4({...G,outcome:"served",headers:B})}function $G($){return E($)&&($.type==="error"||$.type==="response.failed"||E($.response)&&$.response.status==="failed")}function ZG($){return $.includes('"response.failed"')||$.includes('"type":"error"')||$.includes('"error"')&&/"type"\s*:\s*"error"/.test($)||$.includes('"failed"')&&/"status"\s*:\s*"failed"/.test($)}function ZF($,Z,J,X){if(!R4()||!$||!Z.accountIdentity)return J;let z={status:J.status,headers:J.headers,quota:X.quota};if(J.status===429){try{J.clone().json().then((q)=>{n9($,Z,{...z,body:q,limit:X.parseLimit(q),now:X.now?.()})}).catch(()=>{})}catch{}return J}if(!J.ok)return J;if(!J.body)return n9($,Z,z),J;let G=J.headers.get("content-type")?.includes("text/event-stream"),B=new TextDecoder,W="",Q=!1,Y=(q)=>{if(Q)return;if(q.startsWith("event:")&&q.slice(6).trim()==="error")Q=!0;if(!q.startsWith("data:")||!ZG(q))return;try{Q||=$G(JSON.parse(q.slice(5)))}catch{}},V=J.body.pipeThrough(new TransformStream({transform(q,F){if(G&&!Q){W+=B.decode(q,{stream:!0});let U=W.indexOf(`
|
|
68
68
|
`);while(U>=0)Y(W.slice(0,U)),W=W.slice(U+1),U=W.indexOf(`
|
|
69
|
-
`);if(W.length>1048576)Q=!0,W=""}F.enqueue(q)},flush(){if(G)Y(W+B.decode());
|
|
70
|
-
`,r:"\r",t:"\t"}[X]??X??Z})}function BG($,Z){if(!Z)return $;let J=$.split(Z).join("[credential]"),X=Z.replace(/\s/g,"");if(!X)return J;let z=J.replace(/\s/g,"");if(!z.includes(X))return J;let G=[];for(let Q=0;Q<J.length;Q++){let Y=J[Q]??"";if(!/\s/.test(Y))G.push(Q)}let B=[],W=0;for(let Q=z.indexOf(X);Q>=0;Q=z.indexOf(X,Q+X.length)){let Y=G[Q]??W,V=(G[Q+X.length-1]??Y)+1;B.push(J.slice(W,Y),"[credential]"),W=V}return B.length?B.join("")+J.slice(W):J}function D7($,Z){let J=BG($,Z);return C7(J).replaceAll("***REDACTED***","[credential]")}function w2($,Z){let J=D7($,Z),X=T7(J),z=D7(X,Z);return z===X?J:z}function P7($){let Z=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec($);if(!Z)return;let J=Z[3]??"",X=(Z[2]??"")+J,z=0;while(X[z]==="0")z++;if(z===X.length)return"0";let G=X.length;while(X[G-1]==="0")G--;let B=Z[4]??"0",W=B.startsWith("-")||B.startsWith("+")?1:0;while(B[W]==="0")W++;let Q=B.slice(W)||"0";if(Q.length>16)return;let Y=BigInt((B.startsWith("-")?"-":"")+Q)-BigInt(J.length)+BigInt(X.length-G);return`${Z[1]}${X.slice(z,G)}e${Y}`}function L7($,Z){let J=Z?P7(Z):void 0;return $.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(X)=>{if(!X.startsWith('"'))return Z&&(X===Z||J!==void 0&&P7(X)===J||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(X)&&String(Number(X))===Z)?'"[credential]"':X;let z=T7(X.slice(1,-1)),G=w2(z,Z);return G===z?X:JSON.stringify(G)})}function r9($,Z){let J=L7($,Z);try{return JSON.parse($),J}catch{return w2(J,Z)}}var QG=16384,WG=65536,YG=[/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 VG($){try{let Z=d(JSON.parse($),"request_id");if(typeof Z==="string")return Z;if(typeof Z!=="number")return;let J=0,X,z=!0,G=!1,B;for(let W of $.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Q=W[0];if(Q==="{"||Q==="["){J++;continue}if(Q==="}"||Q==="]"){J--;continue}if(J!==1)continue;if(Q===","){z=!0,G=!1,X=void 0;continue}if(Q===":"){G=!0;continue}if(z&&Q.startsWith('"')){X=JSON.parse(Q),z=!1;continue}if(G&&X==="request_id"&&!Q.startsWith('"'))B=Q;G=!1}return B}catch{return}}function HG($,Z){let J=r9($,Z);if(Buffer.byteLength(J,"utf8")<=WG)return J;let X=YG.flatMap((G)=>G.exec(J)?.[0]??[]);for(let G of["FreeUsageLimitError","GoUsageLimitError"])if(J.includes(G))X.push(G);let z={retry:X};try{let G=JSON.parse(J);if(d(G,"type")==="error")z.type="error";let B=d(G,"error"),W={};for(let Y of["code","type"]){let V=d(B,Y);if(typeof V==="string")W[Y]=V.slice(0,256)}if(Object.keys(W).length)z.error=W;let Q={};for(let Y of["workspace","limitName"]){let V=d(d(G,"metadata"),Y);if(typeof V==="string")Q[Y]=V.slice(0,256)}if(Object.keys(Q).length)z.metadata=Q}catch{}return JSON.stringify(z)}function s6($){if(!$||typeof $!=="object")return!1;let Z=$;for(let J=0;Z&&J<16;J++){if(XG.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function d($,Z){if(!s6($))return;let J=Object.getOwnPropertyDescriptor($,Z);return J&&"value"in J?J.value:void 0}function R4($,Z){return w2($,Z).slice(0,QG)}function u2($,Z){let J=Object.getOwnPropertyDescriptor($,Z)?.get;if(!J)throw Error(`Missing native ${Z} accessor`);return J}var UG=u2(DOMException.prototype,"message"),qG=u2(DOMException.prototype,"name");function n9($,Z){let J=d($,"message"),X=d($,"name");if(s6($)&&$ instanceof DOMException)try{J=UG.call($),X=qG.call($)}catch{}let z=Error(R4(typeof J==="string"?J:typeof $==="string"?$:"Provider request failed",Z));for(let H of Object.getOwnPropertyNames(z))if(H!=="message")Reflect.deleteProperty(z,H);Object.defineProperty(z,"name",{value:typeof X==="string"?R4(X,Z):"Error",configurable:!0,writable:!0});let G=(H,q,F)=>{let U=d(H,F);if(typeof U==="string"||typeof U==="number"&&Number.isFinite(U)||typeof U==="boolean")Object.defineProperty(q,F,{value:typeof U==="string"?R4(U,Z):U,enumerable:!0,configurable:!0,writable:!0})};for(let H of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let q=d($,H);if(typeof q==="number"&&Number.isFinite(q))G($,z,H)}for(let H of["code","type","isRetryable"])G($,z,H);for(let H of["error","data"]){let q=d($,H),F=Object.create(null);for(let j of["type","code","message","resets_at","resets_in_seconds"])G(q,F,j);let U=d(q,"error");if(s6(U)){let j=Object.create(null);for(let K of["type","code","message","resets_at","resets_in_seconds"])G(U,j,K);F.error=j}if(Object.keys(F).length)Object.defineProperty(z,H,{value:F,enumerable:!0})}let B=d($,"responseHeaders");if(B&&typeof B==="object"){let H={};for(let q of["retry-after-ms","retry-after"]){let F=d(B,q);if(typeof F==="string")H[q]=R4(F,Z)}Object.defineProperty(z,"responseHeaders",{value:H,enumerable:!0})}let W=d($,"responseBody");if(typeof W==="string")Object.defineProperty(z,"responseBody",{value:HG(W,Z),enumerable:!0});let Q=d($,"request_id"),Y=d(B,"x-request-id"),V=typeof Q==="string"?Q:typeof Y==="string"?Y:typeof W==="string"?VG(r9(W,Z)):void 0;if(typeof V==="string")Object.defineProperty(z,"request_id",{value:R4(V,Z),enumerable:!0});for(let H of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let q=Symbol.for(H);if(d($,q)===!0)Object.defineProperty(z,q,{value:!0})}return z}function jG($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!zG.test($)&&!GG.test($)))return $;let J;try{J=JSON.parse($)}catch{return $}if(J?.type==="error"||J?.error||J?.response?.error)return L7($,Z);return $}var FG=u2(Response.prototype,"status"),KG=u2(Response.prototype,"statusText"),NG=u2(Response.prototype,"headers"),DG=u2(Response.prototype,"body"),PG=Response.prototype.text,M7=Headers.prototype.entries;async function HF($,Z,J="http"){try{let F=function(U){let j=q&&U.startsWith("\uFEFF")?"\uFEFF":"";return q=!1,j+U.slice(j.length).replace(/^data: ?([^\r\n]*)/gm,(K,N)=>K.slice(0,K.length-N.length)+jG(N,Z))};if(!s6($))throw Error("Invalid provider response");let X=FG.call($),z=NG.call($),G=DG.call($),B=new Headers;for(let[U,j]of M7.call(z))B.append(U,j);let W={status:X,statusText:w2(KG.call($),Z),headers:B};if(X<200||X>299){for(let[j,K]of M7.call(z)){if(w2(j,Z?.toLowerCase())!==j){W.headers.delete(j);continue}try{W.headers.set(j,w2(K,Z))}catch{W.headers.delete(j)}}W.headers.delete("content-length");let U=await PG.call($);return new Response(r9(U,Z),W)}if(!G||J==="http")return $;W.headers.delete("content-length");let Q=ReadableStream.prototype.getReader.call(G),Y=new TextDecoder("utf-8",{ignoreBOM:!0}),V=new TextEncoder,H="",q=!0;return new Response(new ReadableStream({async pull(U){try{for(;;){let j=await Q.read();H+=Y.decode(j.value,{stream:!j.done});let K=!1;for(;;){let N=/\r?\n\r?\n/.exec(H);if(!N)break;let D=N.index+N[0].length;U.enqueue(V.encode(F(H.slice(0,D)))),H=H.slice(D),K=!0}if(j.done){if(H)U.enqueue(V.encode(F(H)));U.close();return}if(K)return}}catch(j){U.error(n9(j,Z))}},async cancel(U){try{await Q.cancel(U)}catch(j){throw n9(j,Z)}finally{Q.releaseLock()}}}),W)}catch(X){throw n9(X,Z)}}var _7={unproven:0,reading:1,provider:2};class o9{namespace;entries=new Map;constructor($){this.namespace=$}record($,Z){if($.accountKey.namespace!==this.namespace)return;if(![$.expiry,$.observedAt,$.evidenceAt,Z].every(Number.isFinite))return;if(this.prune(Z),$.expiry<=Z)return;let J=y($.accountKey),X=this.entries.get(J);if(X?.expiry===$.expiry){if(_7[X.branch]<=_7[$.branch])return}if(this.entries.set(J,$),this.entries.size<=256)return;let z,G=1/0;for(let[B,W]of this.entries)if(W.observedAt<G)z=B,G=W.observedAt;if(z!==void 0)this.entries.delete(z)}read($,Z,J,X){this.prune(X);let z=this.entries.get(y($));return z?.expiry===Z&&z.evidenceAt===J?z:void 0}retire($){this.entries.delete(y($))}clear(){this.entries.clear()}reconcile($,Z){this.prune(Z);for(let[J,X]of this.entries)if(!$.marks.some((z)=>E(z.key.account,X.accountKey)&&z.key.window==="account"&&z.key.scope.kind==="pool"&&z.entries.some((G)=>G.cause==="rate-limit"&&G.until===X.expiry&&G.evidenceAt===X.evidenceAt)))this.entries.delete(J)}prune($){for(let[Z,J]of this.entries)if(J.expiry<=$)this.entries.delete(Z)}}import{randomUUID as S7}from"node:crypto";import{randomUUID as MG}from"node:crypto";function t9($,Z){return(Z?.rows??[]).map((J)=>({account:{namespace:$,accountId:J.routeId,incarnation:String(J.addedAt)},credentialEpoch:String(J.addedAt),...J.accountIdentity===void 0?{}:{identity:J.accountIdentity}}))}async function e9($){let{namespace:Z,path:J}=$,X=MG(),z=new V2,G=new q4(Z,$.logger),B=new K4($.logger),W=$.now??Date.now,Q=async(V)=>{G.assertWritable();let H=await R6(J),{snapshot:q,replacement:F}=G.decode(H?.limits);if(!F&&z.lost(q,V))return B.schedule(()=>Y.commit([],V)),{snapshot:z.recover(q,V,Z,W()),bindings:t9(Z,H),authoritative:!1,degradedAgreement:!0};if(q)z.remember(q);return{snapshot:q??T0(Z,X),bindings:t9(Z,H),authoritative:!0}},Y={namespace:Z,read:Q,subscribe:B.subscribe,commit:async(V,H)=>{G.assertWritable();let q,F,U=()=>{if(G.didCommit(q)&&F)z=new V2,z.remember(F,H)},j=await O7(J,(K)=>{let N=t9(Z,K),D=G.decode(K?.limits),O=D.snapshot;q=D.replacement;let M=!q&&z.lost(O,H),P=Y2(M?z.recover(O,H,Z,W()):O??T0(Z,X),V,{now:W(),bindings:N,authorizeEpoch:(L,C)=>L.credentialEpoch===C.credentialEpoch});return F=P.snapshot,{next:{...K??{version:1,complete:!0,rows:[],declined:[]},limits:P.snapshot},result:{...P,bindings:N,authoritative:!0,degradedAgreement:M}}},{beforePublish:async()=>G.assertWritable(),onPublished:U});return U(),z.remember(j.snapshot,H),j}};return await Q(),Y}var CG=256,TG=256,LG=1024;function $$($){return JSON.stringify([y($.account),$.until,$.evidenceAt])}class Z${log;generation;issued=0;adopted=0;remembered=new Map;staged=new Map;consumed=new Map;exhausted=!1;constructor($=()=>{}){this.log=$}capture($,Z){return{token:++this.issued,view:$,at:Z}}adopt($,Z){let{view:J,token:X,at:z}=$,G=J.snapshot;if(X<=this.adopted||!J.authoritative||J.degradedAgreement||G.namespace!==Z.namespace||G.generation!==Z.generation||G.revision!==Z.revision)return!1;if(this.adopted=X,this.generation!==G.generation)this.generation=G.generation,this.remembered.clear(),this.staged.clear(),this.consumed.clear();let B=new Set(J.bindings.map((Q)=>y(Q.account))),W=new Map;for(let Q of G.marks){if(Q.key.window!=="account"||Q.key.scope.kind!=="pool")continue;if(!B.has(y(Q.key.account)))continue;for(let Y of Q.entries){if(Y.cause!=="rate-limit")continue;let V={account:Q.key.account,until:Y.until,evidenceAt:Y.evidenceAt,committedRevision:Y.committedRevision};W.set($$(V),V)}}for(let Q of[this.remembered,this.staged])for(let[Y,V]of Q){if(!B.has(y(V.account))){Q.delete(Y);continue}if(W.has(Y))continue;let H=G.tombstones.some((q)=>y(q.key.account)===y(V.account)&&q.key.window==="account"&&q.key.scope.kind==="pool"&&q.revision>=V.committedRevision&&(q.cause===void 0||q.cause==="rate-limit"));if(Q===this.staged&&!H)continue;if(Q.delete(Y),!H&&Q===this.remembered&&V.until<=z)this.stage(V)}for(let[Q,Y]of W){if(this.consumed.has(Q))continue;if(Y.until<=z)this.remembered.delete(Q),this.stage(Y);else if(this.remembered.has(Q)||this.remembered.size<CG)this.remembered.set(Q,Y)}return!0}stage($){let Z=$$($);if(this.consumed.has(Z)||this.exhausted)return;let{NEGATIVE_INFINITY:J,NEGATIVE_INFINITY:X}=Number;for(let z of this.consumed.values()){if(y(z.account)!==y($.account))continue;J=Math.max(J,z.until),X=Math.max(X,z.evidenceAt)}if($.until<=J&&$.evidenceAt<=X)return;if(this.staged.has(Z)||this.staged.size<TG)this.staged.set(Z,$)}candidate($,Z){if(this.exhausted||this.generation===void 0)return;let J=y($.account),X;for(let z of this.staged.values()){if(y(z.account)!==J||z.until>Z)continue;if(!X||z.until>X.until||z.until===X.until&&z.evidenceAt>X.evidenceAt)X=z}return X&&{...X,generation:this.generation}}consume($){let Z=$$($);if(this.exhausted||$.generation!==this.generation||!this.staged.has(Z)||this.consumed.has(Z))return!1;let J=[...this.staged].filter(([,X])=>y(X.account)===y($.account));if(this.consumed.size+J.length>LG)return this.exhausted=!0,this.staged.clear(),this.log("OpenAI limits recovery evidence is full; skipping further recovery clears."),!1;for(let[X,z]of J)this.consumed.set(X,z),this.staged.delete(X);return!0}}var z$=5000,J$=1000,X$=60000,_G={now:()=>Date.now(),setTimeout:($,Z)=>setTimeout($,Z),clearTimeout:($)=>clearTimeout($)};class A7{options;clock;dropped;owners=0;registry;recovery;provenance;provenanceGeneration;adapter;acquiring;releasing;deadline;fallback=!1;fallbackResolve;fallbackSignal=new Promise(($)=>{this.fallbackResolve=$});failureAt;retryAt=0;retryDelay=J$;failureTimer;latestRead;adoptedBindings=[];controls=new Map;projection;producerId=S7();constructor($,Z,J){this.options=$;this.clock=Z;this.dropped=J;this.recovery=new Z$($.log),this.provenance=new o9($.namespace)}stopTracking(){if(this.fallback)return;this.fallback=!0,this.clock.clearTimeout(this.failureTimer),this.fallbackResolve(),this.options.log("OpenAI limits tracking is unavailable; serving without timed marks for this process.");let $=this.registry;if(this.registry=void 0,this.adapter=void 0,this.latestRead=void 0,this.provenance.clear(),$)this.releasing=$.dispose().catch(()=>{})}wait($){return new Promise((Z)=>this.clock.setTimeout(Z,Math.max(0,$)))}async bounded($,Z){let J;try{return await Promise.race([$,this.fallbackSignal.then(()=>{return}),new Promise((X)=>{J=this.clock.setTimeout(()=>X(void 0),Math.max(0,Z-this.clock.now()))})])}finally{this.clock.clearTimeout(J)}}recordFailure(){if(!this.registry||this.fallback)return;let $=this.clock.now();if(this.failureAt===void 0)this.failureAt=$,this.failureTimer=this.clock.setTimeout(()=>this.stopTracking(),X$);if(this.retryAt=$+this.retryDelay,this.retryDelay=Math.min(X$,this.retryDelay*2),$-this.failureAt>=X$)this.stopTracking()}recordSuccess(){this.failureAt=void 0,this.retryAt=0,this.retryDelay=J$,this.clock.clearTimeout(this.failureTimer),this.failureTimer=void 0}async makeAdapter(){let $=await this.options.adapter();return{namespace:$.namespace,read:async(Z)=>{if(this.adoptRead(),this.registry&&this.clock.now()<this.retryAt)throw this.registry.lastFailure??Error("limits-reload-backoff");try{let J=await $.read(Z);this.latestRead=this.recovery.capture(J,this.clock.now());let X=!Z||J.snapshot.generation!==Z.generation||J.snapshot.revision>=Z.revision;if(J.authoritative&&!J.degradedAgreement&&X)this.recordSuccess();else if(!J.authoritative||J.degradedAgreement)this.recordFailure();return J}catch(J){throw this.recordFailure(),J}},commit:async(Z,J)=>{this.adoptRead();let X=await $.commit(Z,J);return this.latestRead=this.recovery.capture(X,this.clock.now()),X},subscribe:$.subscribe?.bind($)}}async ready($){if(!$||this.fallback||this.registry)return;if(!this.acquiring)this.acquiring=this.acquire().finally(()=>{this.acquiring=void 0});await this.acquiring}async acquire(){await this.releasing,this.deadline??=this.clock.now()+z$;while(!this.fallback&&!this.registry){if(this.clock.now()>=this.deadline){this.stopTracking();return}let $=(async()=>{return this.adapter??=await this.makeAdapter(),j9({adapter:this.adapter,clock:this.clock,isAccessRestrictive:this.options.isAccessRestrictive,onAbandon:()=>this.stopTracking(),onRejected:(Z)=>{this.controls.delete(JSON.stringify([Z.producerId,Z.operationId]))}})})();try{let Z=await this.bounded($,this.deadline);if(!Z||this.fallback){this.stopTracking(),$.then((J)=>J.dispose()).catch(()=>{});return}if(this.registry=Z,Z.abandoned){this.stopTracking();return}this.adoptRead()}catch(Z){if(Z instanceof H4||Z instanceof U4){this.stopTracking();return}if(Z instanceof L0&&Z.code==="pool-not-ready"){this.deadline=void 0,this.adapter=void 0;return}await this.wait(Math.min(J$,Math.max(0,this.deadline-this.clock.now())))}}}adoptRead(){let $=this.current();if($&&this.latestRead&&this.recovery.adopt(this.latestRead,$.snapshot)){if(this.provenanceGeneration!==void 0&&this.provenanceGeneration!==$.snapshot.generation)this.provenance.clear();this.provenanceGeneration=$.snapshot.generation,this.provenance.reconcile($.snapshot,this.clock.now()),this.projection=p9(this.latestRead.view.bindings),this.adoptedBindings=this.latestRead.view.bindings;for(let Z of $.snapshot.operationIds)this.controls.delete(JSON.stringify([Z.producerId,Z.operationId]))}}current(){if(this.registry?.abandoned)this.stopTracking();return this.registry}snapshot(){return this.adoptRead(),this.current()?.snapshot}enqueue($,Z){let J=this.current();if(J){if($.type!=="mark")this.controls.set(JSON.stringify([$.producerId,$.operationId]),$);if(J.enqueue($),$.type!=="mark")this.provenance.retire($.binding.account);else if(Z&&Z.expiry===$.until&&Z.evidenceAt===$.evidenceAt&&y(Z.accountKey)===y($.binding.account))this.provenance.record(Z,this.clock.now());else this.provenance.retire($.binding.account)}else if($.type==="mark")this.dropped()}dropSignal(){this.dropped()}observe($){this.adoptRead();let Z=this.current();if(!Z||!$)return;return{...Z.observe($),registry:Z,evidence:this.recovery.candidate($,this.clock.now())}}afterProbe($,Z,J){if(!$?.evidence||!Z||J||this.current()!==$.registry)return;if(this.adoptRead(),$.registry.snapshot.marks.some((z)=>y(z.key.account)===y($.binding.account)&&z.entries.some((G)=>G.until>this.clock.now()))||!this.recovery.consume($.evidence))return;this.enqueue({type:"clear",producerId:this.producerId,operationId:S7(),binding:$.binding,baseRevision:$.baseRevision,keys:[{scope:{kind:"pool"},window:"account"}],cause:"rate-limit",evidenceAt:$.evidence.evidenceAt})}dispatchAtBound($){this.adoptRead();let Z=this.current()?.snapshot;if(!Z)return{status:"ready"};let J=this.adoptedBindings.find((G)=>y(G.account)===y($.account)),X=[...this.controls.values()].some((G)=>y(G.binding.account)===y($.account)),z=Z.access.some((G)=>y(G.account)===y($.account)&&this.options.isAccessRestrictive(G.state));return{status:!J||!w0(J,$)||X||z?"blocked":"ready",snapshot:Z}}async release(){if(--this.owners!==0)return;if(await this.acquiring,this.owners!==0)return;let $=this.current();if(this.registry=void 0,this.clock.clearTimeout(this.failureTimer),$)this.releasing=$.dispose(),await this.releasing;this.adapter=void 0,this.projection=void 0,this.deadline=void 0,this.provenance.clear()}}class E7{lease;projectionDeadline;constructor($){this.lease=$}snapshot(){return this.lease.snapshot()}async reloadForBindings($){for(;;){this.lease.adoptRead();let Z=this.lease.current();if(!Z)return;if(p9($())===this.lease.projection)return;if(this.projectionDeadline??=this.lease.clock.now()+z$,this.lease.clock.now()>=this.projectionDeadline)return;if(await this.lease.bounded(Z.reload(),this.projectionDeadline),this.lease.adoptRead(),this.lease.clock.now()>=this.projectionDeadline)return;if(Z.degradedAgreement)return}}async beforeDispatch($,Z,J=$?.account.accountId){await this.reloadForBindings(Z);let X=()=>{if(!J)return"ready";let Q=Z().find((Y)=>Y.account.accountId===J);if(!Q)return $?"absent":"ready";if($&&(y(Q.account)!==y($.account)||!w0(Q,$)))return"changed";return"ready"},z=X();if(z!=="ready")return{status:z};let G=this.lease.current();if(!G||!$)return{status:"ready"};if(this.projectionDeadline!==void 0&&this.lease.clock.now()>=this.projectionDeadline)return this.lease.dispatchAtBound($);let B=this.projectionDeadline??this.lease.clock.now()+z$,W=await this.lease.bounded(G.beforeDispatch($),B);if(W?.blocked&&this.lease.current())await this.lease.bounded(G.reload(),B),W=await this.lease.bounded(G.beforeDispatch($),B);if(z=X(),z!=="ready")return{status:z};if(!this.lease.current())return{status:"ready"};return this.lease.adoptRead(),{status:!W||W.blocked?"blocked":"ready",snapshot:W?.snapshot}}}class R7{lease;disposed=!1;constructor($){this.lease=$;$.owners++}get namespace(){return this.lease.options.namespace}get registry(){return this.lease.current()}get provenance(){return this.lease.adoptRead(),this.lease.provenance}async forRequest($){if(this.disposed)throw Error("limits-owner-disposed");return await this.lease.ready($),new E7(this.lease)}snapshot(){return this.lease.snapshot()}observe($){return this.lease.observe($)}enqueue($,Z){this.lease.enqueue($,Z)}dropSignal(){this.lease.dropSignal()}afterProbe($,Z,J=!1){this.lease.afterProbe($,Z,J)}async reload(){let $=this.lease.current();if($)await $.reload();this.lease.adoptRead()}async flush(){await this.lease.current()?.flush()}async dispose(){if(this.disposed)return;this.disposed=!0,await this.lease.release()}}function OG($=_G,Z={}){let J=new Map,X=Z.droppedSignalLog??{logged:!1};return{acquire(z){let G=J.get(z.namespace);if(!G)G=new A7(z,$,()=>{if(X.logged)return;X.logged=!0,z.log("OpenAI limit signal dropped because timed-mark tracking is unavailable.")}),J.set(z.namespace,G);return new R7(G)}}}var I7=Symbol.for("@cortexkit/openai-auth/limits-leases/v1"),b7=globalThis,k7=b7[I7]??OG();b7[I7]=k7;function SG($){let{source:Z}=$,J=Z.kind==="pool"?nZ(Z.configPath,Z.statePath):rZ(Z.rosterPath),X=$.log??(()=>{});return k7.acquire({namespace:J,log:X,isAccessRestrictive:$.isAccessRestrictive??(()=>!1),adapter:()=>Z.kind==="pool"?q9({namespace:J,store:Z.store,logger:{warn:X}}):e9({namespace:J,path:Z.rosterPath,logger:{warn:X}})})}function yF($,Z,J){let X=$.get(Z.sessionId),z=new Set(Z.validPinnedAccountIds);if(X&&!Z.excludeAccountIds.includes(X.accountId)&&x7(X,z,Z.wireAccountIdByAccount[X.accountId])){if(Z.persist){let Q=Z.quotaCheckedAtByAccount[X.accountId];J(Z.sessionId,{accountId:X.accountId,inputBytes:Z.requestBytes,...X.wireIdentity!==void 0?{wireIdentity:X.wireIdentity}:{},...Q!==void 0?{quotaCheckedAt:Q}:{}})}return{accountId:X.accountId}}let G=new Map(Object.entries(Z.quotaCheckedAtByAccount)),B=y7($,G,Z.sessionId),W=Z.select(B);if(!W)return;if(Z.persist){let Q=Z.wireAccountIdByAccount[W.accountId];J(Z.sessionId,{accountId:W.accountId,inputBytes:Z.requestBytes,...Q!==void 0?{wireIdentity:Q}:{},...W.quotaCheckedAt!==void 0?{quotaCheckedAt:W.quotaCheckedAt}:{}})}return{accountId:W.accountId}}import{statSync as AG}from"node:fs";var h7=30000,EG=8,RG=1800000;function m7($){return JSON.stringify([$.id,$.credentialEpoch??null])}function mF($){try{let Z=AG($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function wF($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}function IG($,Z){try{return g7($,Z)}catch{return $}}function uF($,Z,J){let X=m7(Z);$.set(X,[...$.get(X)??[],{credentialEpoch:Z.credentialEpoch,identity:Z.identity,observation:J}].slice(-EG))}function pF($,Z,J){let X=$;for(let z of Z.get(m7($))??[]){if(!(J-z.observation.checkedAt<=RG)||z.credentialEpoch!==$.credentialEpoch||z.identity!==$.identity)continue;X={...X,quota:IG(X.quota,z.observation)}}return X}function lF($,Z,J,X){let z=I4($);if(typeof Z?.status==="number"||f7(Z)){let B=v7({error:Z,now:J,refreshToken:$,...X?{previous:{message:"",checkedAt:J,nextRetryAt:X.nextRetryAt,retryCount:X.retryCount,tokenHash:X.tokenHash}}:{}});return{nextRetryAt:B.nextRetryAt,tokenHash:z,retryCount:B.retryCount}}return{nextRetryAt:J+h7,tokenHash:z,retryCount:X?.tokenHash===z?X.retryCount:0}}function dF($,Z,J,X){let z=new Map;for(let G of $){if(X(G,J))continue;let B=Z.get(G.id);z.set(G.id,B&&B.nextRetryAt>J?B.nextRetryAt:J+h7)}return z}var bG={quota:"Every OpenAI account has used up its quota.",killswitch:"Every OpenAI account is below its killswitch quota floor (see the Limits section of `/openai`).","timed-mark":"Every OpenAI account is paused by OpenAI for now."},kG={quota:"OpenAI quota exhausted — retrying on another account.",killswitch:"Killswitch: all OpenAI accounts are below their configured quota threshold.","timed-mark":"OpenAI rate limit reached — retrying on another account.",hold:"OpenAI usage limit reached on this account. Waiting for it keeps the conversation's prompt cache."};function w7($){return({retryIn:Z,reset:J})=>`${$}${Z?` Retry in ${Z}.`:""}${J?` Resets in ${J}.`:""}`}var xG=X9({refusals:Object.fromEntries(Object.entries(bG).map(([$,Z])=>[$,w7(Z)])),retryable:Object.fromEntries(Object.entries(kG).map(([$,Z])=>[$,w7(Z)])),formatReset:x2});function iF($){let Z=[],J=!1,X=!1,z=$.familyOf??(()=>{return}),G=$.accounts.flatMap((Y)=>{if(Y.usable===!1)return[];let V=E(Y.account,Y.readingAccount??Y.account)&&!(Y.identity&&Y.readingIdentity&&Y.identity!==Y.readingIdentity),H=[];if(V){for(let q of["primary","secondary"]){let F=Y.reading?.[q];if(!F)continue;let U=$2(F.checkedAt,$.now),j=Y.floors?.[q],K=j!==void 0&&F.remainingPercent<j?"killswitch-floor":U&&F.usedPercent>=100?"exhausted":void 0;if(!K)continue;if(K==="killswitch-floor")X=!0;else J=!0;let N=U?l6(F.resetsAt):void 0;H.push({window:q,scope:{kind:"pool"},blockedBy:K,...N===void 0?{}:{reset:{at:N,checkedAt:F.checkedAt}}})}for(let q of Y.confirmedBlockers??[]){if(!q.confirmed||!$2(q.observedAt,$.now))continue;J=!0,H.push({window:q.window,scope:{kind:"pool"},blockedBy:"exhausted",...q.resetAt===void 0?{}:{reset:{at:q.resetAt,observedAt:q.observedAt}}})}}for(let q of Y.marks??[]){if(!Number.isFinite(q.until)||q.until<=$.now)continue;let F=$.provenance?.read(Y.account,q.until,q.evidenceAt,$.now),U=F&&F.branch!=="unproven"&&$2(F.observedAt,$.now);if(!U)Z.push(q.until);H.push({window:"account",scope:{kind:"pool"},blockedBy:"exhausted",...U?{reset:{at:q.until,observedAt:F.observedAt}}:{}})}return[{account:Y.account,readingAccount:Y.account,windows:H}]}),B=$.activity&&$.currentAccountKey&&E($.activity.accountKey,$.currentAccountKey)?$.activity:void 0,W={candidates:G,effectiveModel:$.effectiveModel,familyOf:z,maxAgeMs:l9,maxSameAccountWait:h0($.maxSameAccountWait),activity:B,accountKey:B?.accountKey},Q=F6(W,$.now);if(Q&&Z.some((Y)=>Y<Q.resetAt))W={...W,candidates:[]};return{source:"pool",reason:"quota",messageKey:X?"killswitch":J?"quota":"timed-mark",scan:W}}function nF($,Z){let J=$.phase==="pre-send"?{...$,attempted:void 0,selection:void 0,hold:void 0}:$,X=eZ({...J,terminal:Z},{mode:"sticky"});if(!X)throw Error("Missing OpenAI terminal decision");return X}function rF($){let Z=$.decision,J=$.host!=="pi"&&Z.action==="hold"&&Z.waitKind!=="terminal",X=$.host!=="pi"&&!$.requestThrow&&(J||h0($.maxSameAccountWait)!==0&&Z.retryable),z=J?"hold":$.cause??(Z.action==="refuse"?Z.messageKey:"quota");return W9({family:$.host==="pi"?"pi-final":$.requestThrow?"json-412":J?"openai-429":Z.action==="refuse"?Z.family==="pi-final"?"pi-final":X?"openai-429":"json-412":X?"openai-429":"pi-final",messageKey:z,messages:xG,now:$.now,...X&&"retryAfterMs"in Z?{retryAfterMs:Z.retryAfterMs}:{},..."resetAt"in Z&&Z.resetAt!==void 0?{resetAt:Z.resetAt}:{}})}import{randomUUID as yG}from"node:crypto";function gG($){if(!R($))return;let Z=R($.input_tokens_details)?$.input_tokens_details:void 0,J=Z?.cached_tokens,X=Z?.cache_write_tokens,z=R($.output_tokens_details)?$.output_tokens_details.reasoning_tokens:void 0;return{...typeof $.input_tokens==="number"?{input:Math.max(0,$.input_tokens-(typeof J==="number"?J:0)-(typeof X==="number"&&X>0?X:0))}:{},...typeof J==="number"?{cacheRead:J}:{},...typeof X==="number"&&X>0?{cacheWrite:X}:{},...typeof $.output_tokens==="number"?{output:$.output_tokens}:{},...typeof z==="number"?{reasoning:z}:{},reasoningIncludedInOutput:!0}}class fG{sessionId;receipt;requestKind;model;attempt;warming;freeQuota;attemptId=yG();reported=!1;completed=!1;failed=!1;responseId;usage;constructor($,Z,J,X,z,G,B=!1){this.sessionId=$;this.receipt=Z;this.requestKind=J;this.model=X;this.attempt=z;this.warming=G;this.freeQuota=B}event($){if(!R($))return;if($.type==="error"||$.type==="response.failed")this.failed=!0;if($.type!=="response.completed"&&$.type!=="response.incomplete"&&$.type!=="response.failed")return;if(this.completed=$.type!=="response.failed",R($.response)){if(typeof $.response.id==="string")this.responseId=$.response.id;this.usage=gG($.response.usage)}}piCompleted($,Z){if(this.completed=!0,this.piResponseId($),!R(Z))return;let J={reasoningIncludedInOutput:!0};for(let X of["input","output","cacheRead","reasoning"])if(typeof Z[X]==="number")J[X]=Z[X];if(typeof Z.cacheWrite==="number"&&Z.cacheWrite>0)J.cacheWrite=Z.cacheWrite;this.usage=J}piResponseId($){this.responseId=$}end($,Z,J,X=!1){if(this.reported)return;this.reported=!0;let z;try{z=this.warming?.(this.sessionId)}catch{}E4({sessionId:this.sessionId,kind:"billing",attemptId:this.attemptId,requestKind:this.requestKind,credentialId:this.receipt.credentialId,...this.receipt.accountIdentity?{accountId:this.receipt.accountIdentity}:{},provider:"openai",model:this.model,...this.freeQuota?{chargeBasis:"subscription_included"}:{},attempt:this.attempt,cache:{implicit:!0,warming:z?.on?{on:!0}:{on:!1,...A4(z?.stopReason)?{stopReason:z.stopReason}:{}}},outcome:this.failed||J!==void 0&&(J<200||J>=300)?"failed":this.completed&&(Z||X)?"completed":$?"cut":"failed",...J!==void 0?{status:J}:{},...this.responseId?{providerResponseId:this.responseId}:{},...this.usage?{usage:this.usage}:{}})}}import{readdir as hG,readFile as mG,rm as wG,stat as uG}from"node:fs/promises";import{homedir as pG,uptime as lG}from"node:os";import{join as l2}from"node:path";var B$=Symbol.for("@cortexkit/openai-auth/runtime-layout-runs"),Q$=globalThis,G$=globalThis,vG=Q$[B$];Q$[B$]??={};var p2=Q$[B$];p2.legacyGeneration??=vG===void 0&&G$[Symbol.for("@cortexkit/openai-auth/runtime-layouts")]===void 0&&(G$[Symbol.for("@cortexkit/openai-auth/opencode-vaults")]!==void 0||G$[Symbol.for("__openaiAuthRpcServers")]!==void 0||("__openaiAuthRpcServers"in globalThis));p2.runs??=new Map;p2.logged??=new Set;var l0=Object.assign(p2,{runs:p2.runs,logged:p2.logged});function J0(){return l0.legacyGeneration===!0}function a6(){return process.env.XDG_STATE_HOME||l2(pG(),".local","state")}function dG($=a6()){return l2($,"cortexkit","openai-auth","processes")}function cG($=a6()){return l2($,"cortexkit","openai-auth","rpc")}function sG($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}function u7($){let Z=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec($.trim());if(!Z)return;return{core:[Number(Z[1]),Number(Z[2]),Number(Z[3])],pre:Z[4]?Z[4].split("."):[]}}function p7($,Z){let J=u7($),X=u7(Z);if(!J||!X)return;for(let z=0;z<3;z++){let G=J.core[z]-X.core[z];if(G!==0)return Math.sign(G)}if(J.pre.length===0||X.pre.length===0)return Math.sign(X.pre.length-J.pre.length);for(let z=0;z<Math.max(J.pre.length,X.pre.length);z++){let G=J.pre[z],B=X.pre[z];if(G===void 0)return-1;if(B===void 0)return 1;let W=/^\d+$/.test(G),Q=/^\d+$/.test(B);if(W&&Q){let Y=Number(G)-Number(B);if(Y!==0)return Math.sign(Y)}else if(W!==Q)return W?-1:1;else if(G!==B)return G<B?-1:1}return 0}async function W$($){try{return{ok:!0,names:await hG($)}}catch(Z){let J=Z.code;if(J==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:J,error:`${$}: ${String(Z)}`}}}async function l7($,Z){let J;try{J=await mG($,"utf8")}catch(X){if(X.code==="ENOENT")return{kind:"gone"};return{kind:"unreadable"}}try{let X=JSON.parse(J);if(X!==null&&typeof X==="object"&&X.pid===Z){let z=X.layouts;return{kind:"ok",version:typeof X.version==="string"?X.version:"unknown",startedAt:X.startedAt,...z!==null&&typeof z==="object"&&!Array.isArray(z)?{layouts:z}:{}}}}catch{}return{kind:"unreadable"}}async function c7($){let Z=$.isAlive??sG,J=$.selfPid??process.pid,z=($.now??Date.now)()-($.uptime??lG)()*1000-300000,G=(j)=>typeof j==="number"&&Number.isFinite(j)&&j<z,B=new Map,W=(j)=>{let K=j.pid==="unknown"?`dir:${j.detail}`:j.pid;if(!B.has(K))B.set(K,j)};if($.layoutMove&&J===process.pid&&J0())W({pid:J,version:"unknown",detail:"an older plugin generation ran in this process"});let Q=(j)=>{try{return Z(j)}catch{return!0}},Y=(j,K)=>{let N=K.exec(j),D=N?Number(N[1]):Number.NaN;return Number.isSafeInteger(D)&&D>=1?D:void 0},V=dG($.stateHome),H=await W$(V);if(!H.ok)W({pid:"unknown",version:"unknown",detail:H.error});for(let j of H.ok?H.names:[]){let K=Y(j,/^(\d+)\.json$/);if(K===void 0||K===J)continue;let N=l2(V,j),D=await l7(N,K);if(D.kind==="gone")continue;if(D.kind==="ok"&&G(D.startedAt)){await wG(N,{force:!0}).catch(()=>{});continue}if(!Q(K))continue;if(D.kind==="unreadable"){W({pid:K,version:"unknown",detail:N});continue}let O=p7(D.version,$.currentVersion);if(O===void 0||O<0){W({pid:K,version:D.version,detail:N});continue}if($.layoutMove===!0&&(D.layouts===void 0||Object.values(D.layouts).includes("legacy")))W({pid:K,version:D.version,detail:N})}let q=$.rpcDir??cG($.stateHome),F=await W$(q);if(!F.ok)W({pid:"unknown",version:"unknown",detail:F.error});for(let j of F.ok?F.names:[]){if(!d7(j))continue;let K=l2(q,j),N=await W$(K);if(!N.ok){if(N.code==="ENOTDIR")continue;W({pid:"unknown",version:"unknown",detail:N.error});continue}for(let D of N.names){let O=Y(D,/^port-(\d+)\.json$/);if(O===void 0||O===J||!Q(O))continue;let M=l2(K,D),P=await l7(M,O);if(P.kind==="gone")continue;if(P.kind==="ok"){let T=P.startedAt===void 0?await uG(M).then((A)=>A.mtimeMs).catch(()=>{return}):P.startedAt;if(G(T))continue}let L=P.kind==="ok"?P.version:"unknown",C=p7(L,$.currentVersion);if(C===void 0||C<0)W({pid:O,version:L,detail:M})}}let U=(j)=>j.pid==="unknown"?Number.POSITIVE_INFINITY:j.pid;return B.size===0?{open:!0}:{open:!1,blockers:[...B.values()].sort((j,K)=>U(j)-U(K))}}import{createHash as aG}from"node:crypto";import{existsSync as iG,realpathSync as Y$}from"node:fs";import{homedir as n7}from"node:os";import{basename as nG,dirname as rG,join as q0,resolve as U$}from"node:path";var q$="openai-auth-sessions.json",j$="openai-auth-sessions-opencode2.json",i6="layout.json",F$="config-dir.json";function n6(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return oG()}function oG(){return q0(process.env.XDG_CONFIG_HOME||q0(n7(),".config"),"opencode")}function r6(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||q0(n6(),V$)}function d2($,Z){let J=U$($);return Z==="win32"||Z==="darwin"?J.toLowerCase():J}function s7($){try{return Y$.native($)}catch{try{return q0(Y$.native(rG($)),nG($))}catch{return}}}function o6($,Z,J=process.platform){if(d2($,J)===d2(Z,J))return!0;let X=s7($),z=s7(Z);return X!==void 0&&z!==void 0&&d2(X,J)===d2(z,J)}function a7($){try{return Y$.native($)}catch{return U$($)}}var i7=new Map;function t6($=n6()){let Z=a6(),J=q0(n7(),".config","opencode"),X=`${$}\x00${J}\x00${Z}`,z=i7.get(X);if(z&&$1(z))return z;let G=a7($);if(z&&z.key===G)return z;let B=G===a7(J),W=q0(Z,"cortexkit","openai-auth"),Q={key:G,configDir:$,stateHomeDir:B?q0(W,"opencode"):q0(W,`opencode-${aG("sha256").update(G).digest("hex").slice(0,16)}`),isDefaultConfigDir:B};return i7.set(X,Q),Q}var r7=Symbol.for("@cortexkit/openai-auth/runtime-layouts"),o7=globalThis,K$=o7[r7]??new Map;o7[r7]=K$;function t7($){return`${$.stateHomeDir}\x00${$.key}`}function e6($,Z){K$.set(t7($),J0()?"legacy":Z)}function $1($){return K$.get(t7($))}function e7($=n6()){if(J0())return $;let Z=t6($);return($1(Z)??(iG(q0(Z.stateHomeDir,i6))?"state-home":"legacy"))==="state-home"?Z.stateHomeDir:$}function oK($){return q0(e7(),$==="opencode1"?q$:j$)}function N$($){let Z=q0(n6(),V$);return $===Z||d2($,process.platform)===d2(Z,process.platform)}function $8($=r6()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return N$($)?void 0:H$($)}function Z8($=r6()){return N$($)?void 0:$}function tG($=r6()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z){if(o6($,Z))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${U$($)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return Z}if(!N$($))return H$($);return q0(e7(),b4)}function tK($=r6()){return{configPath:$,statePath:tG($)}}import{createHash as BB}from"node:crypto";import{readFileSync as QB}from"node:fs";import{readFile as WB}from"node:fs/promises";import{resolve as YB}from"node:path";import{createHash as eG}from"node:crypto";import{readFile as $B}from"node:fs/promises";import{homedir as ZB}from"node:os";import{join as J8,resolve as JB}from"node:path";var XB="openai",X8=250,x4="main-refresh";function P$($){if(typeof $.access!=="string"||typeof $.refresh!=="string")return;let Z=Buffer.from($.access),J=Buffer.from($.refresh),X=(z)=>{let G=Buffer.alloc(4);return G.writeUInt32BE(z.length),G};return eG("sha256").update(X(Z)).update(Z).update(X(J)).update(J).digest("hex")}function Y8($){if(!$||typeof $!=="object")return;let Z=$;if(Z.type!=="oauth")return;return{type:"oauth",...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.refresh==="string"?{refresh:Z.refresh}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.accountId==="string"?{accountId:Z.accountId}:{}}}function V8($){let Z=Y8($);if(typeof Z?.access!=="string"||typeof Z.refresh!=="string")return;return{access:Z.access,refresh:Z.refresh,...typeof Z.expires==="number"?{expires:Z.expires}:{}}}function z8($){if(P2($)&&$.type==="api"&&typeof $.key==="string")return{kind:"api"};let Z=Y8($);if(!Z)return{kind:"indeterminate"};return O4(Z)?{kind:"tombstone",oauth:Z}:{kind:"real",oauth:Z}}async function G8($){return $.auth.get({path:{id:XB}})}async function B8($){return Object.keys(await $.auth.all()).length>0}async function H8($){let Z=await G8($.client);if(Z!==void 0)return z8(Z);let J=await B8($.client),X=$.now();if(await $.sleep(X8),$.now()-X<X8)return{kind:"indeterminate"};let z=await G8($.client);if(z!==void 0)return z8(z);let G=await B8($.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function Z1($=process.env,Z=ZB()){let J=$.XDG_DATA_HOME||J8(Z,".local","share");return J8(J,"opencode","auth.json")}function P2($){return!!$&&typeof $==="object"&&!Array.isArray($)}var Q8=($)=>$===void 0||typeof $==="string";function zB($){if(!P2($))return!1;switch($.type){case"oauth":return typeof $.refresh==="string"&&typeof $.access==="string"&&typeof $.expires==="number"&&Number.isSafeInteger($.expires)&&$.expires>=0&&Q8($.accountId)&&Q8($.enterpriseUrl);case"api":return typeof $.key==="string"&&($.metadata===void 0||P2($.metadata)&&Object.values($.metadata).every((Z)=>typeof Z==="string"));case"wellknown":return typeof $.key==="string"&&typeof $.token==="string";default:return!1}}async function D$($,Z=process.env){let J=Z.OPENCODE_AUTH_CONTENT;if(J)try{let z=JSON.parse(J);return P2(z)?z:{}}catch{}let X;try{X=JSON.parse(await $B($,"utf8"))}catch{return{}}if(!P2(X))return{};return Object.fromEntries(Object.entries(X).filter(([,z])=>zB(z)))}function W8($){if(!$.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse($.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class J1 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function GB($){let Z=$.env??process.env,J=$.path??Z1(Z),X=new Map;return{path:JB(J),migrationDisabledReason:()=>W8(Z)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(z){let G=(await D$(J,Z))[z.path.id];return X.set(z.path.id,JSON.stringify(G)),G},async all(){return D$(J,Z)},async set(z){if(W8(Z))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let G=(await D$(J,Z))[z.path.id];if(k4(z.body)&&(!X.has(z.path.id)||X.get(z.path.id)!==JSON.stringify(G)))throw new J1;let B=await $.set(z);if(P2(B)&&"error"in B&&B.error!==void 0)throw Error(`OpenCode refused the write of its ${z.path.id} login: ${JSON.stringify(B.error)}`);return B}}}function BN($,Z={}){let J=P2($)?$.auth:void 0,X=J&&typeof J==="object"?J.set:void 0;if(typeof X!=="function")return{reason:"the OpenCode client has no auth.set to write its login slot with"};return{slot:GB({...Z,set:(z)=>X.call(J,z)})}}var c2="openai",VB="common-auth-placeholder:v1:openai",y4=Object.freeze({type:"oauth",access:"",refresh:VB,expires:0});function k4($){if(!j0($))return!1;return $.type===y4.type&&$.access===y4.access&&$.refresh===y4.refresh&&$.expires===y4.expires}var X1="openaiAuthPool",HB=120000,M8="pool-migration",UB="slot-transfer-origin-unknown",qB="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.",W1=Object.freeze({mainRefreshTtlMs:HB,fallbackTtlMs:D8,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function z1($,Z,J){return $.kind==="placeholder"&&!Z&&!J.pending}class M2 extends Error{constructor($){super(`timed out waiting for the legacy ${$} lock`);this.name="LegacyLockContention"}}function j0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function jB($){let Z=$.now??Date.now;return{paths:$.paths,slot:$.slot,now:Z,sleep:$.sleep??((J)=>new Promise((X)=>setTimeout(X,J))),newId:$.newId??(()=>crypto.randomUUID()),log:$.log??o("pool-migration"),...$.vaultServes?{vaultServes:$.vaultServes}:{},locks:{...W1,...$.legacyLocks},leaseWait:$.leaseWait??{timeoutMs:4000,pollMs:50},store:B4({provider:c2,configPath:$.paths.configPath,statePath:$.paths.statePath,quota:B1,now:Z,...$.store}),onStep:async(J)=>{await $.onStep?.(J)}}}async function a2($){let Z;try{Z=await WB($,"utf8")}catch(X){if(X.code==="ENOENT")return{};throw X}let J=JSON.parse(Z);if(!j0(J))throw Error("config root is not an object");return J}async function g4($,Z,J,X,z){let G=performance.now();for(;;){if(z?.aborted)throw new M2(Z);let B=await K0({name:Z,path:J,ttlMs:X,renew:$.locks.renew,...$.locks.renewIntervalMs!==void 0?{renewIntervalMs:$.locks.renewIntervalMs}:{}});if(B){if(!z?.aborted)return B;throw await B.release(),new M2(Z)}if(performance.now()-G>=$.locks.timeoutMs)throw new M2(Z);await $.sleep($.locks.retryMs)}}async function DN($,Z,J={}){let X={...W1,...J},z=performance.now();for(;;){let G=await K0({name:x4,path:$,ttlMs:X.mainRefreshTtlMs,renew:X.renew,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}});if(G)try{return await Z()}finally{await G.release().catch(()=>{})}if(performance.now()-z>=X.timeoutMs)throw new M2(x4);await new Promise((B)=>setTimeout(B,X.retryMs))}}async function f4($,Z){let J=$.locks.saveTtlMs,X=await g4($,"save",$.paths.configPath,J);try{let z=await g4($,"save",$.paths.statePath,J);try{let G=await a2($.paths.configPath);if(!await Z(G))return;await P0($.paths.configPath,G,{beforeRename:async()=>{await X.assertOwned(),await z.assertOwned()}})}finally{await z.release().catch(()=>{})}}finally{await X.release().catch(()=>{})}}function FB($){if(!j0($))return;let{rowId:Z,operation:J,rowFingerprint:X,slotFingerprint:z}=$,{credentialFingerprint:G,carryLegacyMain:B,recordedAt:W,identity:Q}=$;if(typeof Z!=="string"||!Z)return;if(J!=="add"&&J!=="rotate"&&J!=="replace")return;if(X!==null&&typeof X!=="string")return;if(typeof z!=="string")return;if(typeof G!=="string")return;return{rowId:Z,operation:J,rowFingerprint:X,slotFingerprint:z,credentialFingerprint:G,...typeof Q==="string"&&Q?{identity:Q}:{},carryLegacyMain:B===!0,recordedAt:typeof W==="number"?W:0}}function C8($,Z){if(!j0($)||!Z)return!1;return O0($).pending?.credentialFingerprint===D0({type:"oauth",refresh:Z})}function PN($,Z){let J;try{J=JSON.parse(QB($,"utf8"))}catch{return!1}return C8(J,Z)}class KB extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var NB=600000;async function MN($,Z,J={}){let X=J.now??Date.now,z=(Q)=>{let Y=O0(Q).pending;return Y&&C8(Q,Z)&&X()-Y.recordedAt>=NB?Y:void 0},G=z(await a2($.configPath));if(!G)return!1;let B={...W1,...J.legacyLocks},W=await K0({name:M8,path:$.configPath,ttlMs:B.mainRefreshTtlMs});if(!W)return!1;try{let Q=await a2($.configPath),Y=O0(Q).migratedAt!==void 0,V=await B4({provider:c2,configPath:$.configPath,statePath:$.statePath,quota:B1,now:X}).read();if(Y&&V.status!=="ready")return!1;let H;if(V.status==="ready"){let F=V.rows.find((j)=>j.id===G.rowId&&!j.invalid),U=F?.fingerprint??null;if(Y&&F&&U===G.credentialFingerprint)return!1;if(F&&U!==G.credentialFingerprint&&U!==G.rowFingerprint)H=J.slotAccess!==void 0?P$({type:"oauth",access:J.slotAccess,refresh:Z}):G.slotFingerprint}let q=!1;if(await f4({paths:$,locks:B,sleep:(F)=>new Promise((U)=>setTimeout(U,F))},(F)=>{let U=O0(F),j=z(F);if(!j||j.recordedAt!==G.recordedAt)return!1;let{pending:K,...N}=U;return Y1(F,H!==void 0?{...N,declinedSlotFingerprint:H}:N),q=!0,!0}),q)(J.log??o("pool-migration")).warn(H!==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:G.rowId,recordedAt:G.recordedAt});return q}finally{await W.release().catch(()=>{})}}function O0($){let Z=$[X1];if(!j0(Z))return{};let J=FB(Z.pending);return{...typeof Z.migratedAt==="number"?{migratedAt:Z.migratedAt}:{},...J?{pending:J}:{},...typeof Z.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:Z.declinedSlotFingerprint}:{}}}function Y1($,Z){let X={...j0($[X1])?$[X1]:{}};for(let z of["migratedAt","pending","declinedSlotFingerprint"])delete X[z];Object.assign(X,Z),$[X1]=X}function DB($){let Z=$?I6($):void 0;return Z?b6(Z):void 0}function PB($){let Z=P$({type:"oauth",...$}),J=DB($.access);return{kind:"real",credential:$,fingerprint:Z,credentialFingerprint:D0({type:"oauth",refresh:$.refresh}),...J?{identity:J}:{}}}function T8($){if(k4($))return{kind:"placeholder",...j0($)&&typeof $.accountId==="string"?{origin:$.accountId}:{}};let Z=V8($);if(!Z?.refresh.trim())return{kind:"empty"};return PB(Z)}async function v4($){let Z=await H8({client:{auth:{get:(J)=>$.slot.get(J),all:()=>$.slot.all()}},now:$.now,sleep:$.sleep});if(Z.kind==="real")return T8(Z.oauth);return Z.kind==="slot-absent"||Z.kind==="indeterminate"?{kind:Z.kind}:{kind:Z.kind}}async function CN($,Z){if(!k4(Z))return!1;let J=await a2($.configPath),X=await B4({provider:c2,configPath:$.configPath,statePath:$.statePath,quota:B1}).read();if(X.status==="error")return!1;let z=X.status==="ready"?X.rows.some((G)=>G.id==="main"):X.roster.some((G)=>j0(G)&&G.id==="main");return z1({kind:"placeholder"},z,O0(J))}async function MB($){let Z=$.now()+$.leaseWait.timeoutMs;for(;;){let J=await v4($);if(J.kind!=="real")return J;if(!await L8($,J.credential.refresh))return J;if($.now()>=Z)return{kind:"retry"};await $.sleep($.leaseWait.pollMs)}}async function L8($,Z){let J=await Q1($.paths),X=J?.refresh?.mainRefreshLeaseUntil;return Boolean(X&&X>$.now()&&J?.refresh?.mainRefreshLeaseTokenHash===I4(Z))}function CB($){return $.length>0&&$.trim()===$&&!["__proto__","constructor","prototype","main"].includes($)}function TB($,Z,J,X,z){let G=J.identity?{identity:J.identity}:{},B=Z.find((V)=>!V.invalid&&V.fingerprint===J.credentialFingerprint);if(B)return{rowId:B.id,operation:"rotate",rowFingerprint:B.fingerprint??null,...G,carryLegacyMain:$==="migrate"&&B.id==="main"};let W=Z.find((V)=>V.id==="main");if(!W||!W.invalid&&!W.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...G,carryLegacyMain:$==="migrate"};if(J.identity){let V=Z.find((H)=>!H.invalid&&H.type==="oauth"&&H.enabled&&H.identity===J.identity);if(V)return{rowId:V.id,operation:"replace",rowFingerprint:V.fingerprint??null,...G,carryLegacyMain:$==="migrate"&&V.id==="main"}}let Q=new Set(Z.map((V)=>V.id));return{rowId:X??(J.identity&&CB(J.identity)&&!Q.has(J.identity)?J.identity:z()),operation:"add",rowFingerprint:null,...G,carryLegacyMain:!1}}function LB($,Z,J,X,z,G,B){let W=Z.pending;if(W){let Q=J.find((H)=>H.id===W.rowId&&!H.invalid),Y=Q?.fingerprint??null,V=X.kind==="real"&&X.fingerprint===W.slotFingerprint;if(Q&&Y===W.credentialFingerprint)return{kind:"finish",record:W};if((Q||W.rowFingerprint===null)&&Y===W.rowFingerprint)return V&&X.kind==="real"?{kind:"transfer",record:W,credential:X.credential,fresh:!1}:{kind:"drop-record"};if(!Q)return{kind:"drop-record"};return V?{kind:"ambiguous",record:W}:{kind:"drop-record"}}if(X.kind==="indeterminate")return{kind:"drop-record"};if(X.kind!=="real")return{kind:"nothing",slot:X.kind};if(Z.declinedSlotFingerprint===X.fingerprint)return{kind:"nothing",slot:"declined"};return{kind:"transfer",record:{...TB($,J,X,z,B),slotFingerprint:X.fingerprint,credentialFingerprint:X.credentialFingerprint,recordedAt:G},credential:X.credential,fresh:!0}}async function _B($,Z,J){let X={type:"oauth",access:J.access,refresh:J.refresh,...J.expires!==void 0?{expires:J.expires}:{}},z=Z.identity?{identity:Z.identity}:{},G={extraLocks:G1($.paths,Z.rowId,$.locks)};if(Z.operation==="add")await $.store.add({id:Z.rowId,credential:X,...z},G);else if(Z.operation==="replace")await $.store.replace(Z.rowId,X,z,G);else{let B=await $.store.read(),W=B.status==="ready"?B.rows.find((Q)=>Q.id===Z.rowId):void 0;await $.store.rotate(Z.rowId,X,W?.identity===void 0?z:{},G)}}async function OB($,Z){let J=await $.store.read();if(J.status!=="ready")return;let X=J.rows.find((z)=>z.id===Z.rowId&&!z.invalid);return X?.fingerprint===Z.credentialFingerprint?X:void 0}function SB($,Z){let J=[],X=[["primary",$.primary],["secondary",$.secondary]],z=0;for(let[W,Q]of X){if(!Q||!Number.isFinite(Q.checkedAt)||!Number.isFinite(Q.usedPercent))continue;z=Math.max(z,Q.checkedAt),J.push({checkedAt:Q.checkedAt,readings:[{label:W,usedPercent:Q.usedPercent,...typeof Q.resetsAt==="string"?{resetsAt:Q.resetsAt}:{},...Number.isFinite(Q.windowMinutes)?{windowMinutes:Q.windowMinutes}:{}}]})}let G=Z??(z||void 0),B=$.spendControl;if(G!==void 0&&B)J.push({checkedAt:G,budget:{kind:"reading",reached:B.reached,remainingPercent:B.remainingPercent,usedPercent:B.usedPercent,limit:B.limit,used:B.used,remaining:B.remaining,...B.resetsAt!==void 0?{resetsAt:B.resetsAt}:{},...B.unit!==void 0?{unit:B.unit}:{}}});else if(G!==void 0&&$.spendControlCleared)J.push({checkedAt:G,budget:{kind:"cleared"}});return J.sort((W,Q)=>W.checkedAt-Q.checkedAt)}async function AB($,Z){let J=await Q1($.paths);if(!J)return;let X=J.quota?.mainQuotaToken,z=Z.credential?.type==="oauth"?Z.credential.access:void 0,B=!X||z!==void 0&&X===F8(z)?J.quota?.mainQuota:void 0;if(B&&Z.credentialEpoch!==void 0){let V={credentialEpoch:Z.credentialEpoch,...Z.identity!==void 0?{identity:Z.identity}:{}};for(let H of SB(B,J.quota?.mainQuotaCheckedAt))try{await $.store.recordQuota(Z.id,V,H)}catch(q){$.log.warn("legacy main quota not carried to the pool row",{rowId:Z.id,error:q instanceof Error?q.message:String(q)})}}let W=J.refresh?.mainLastRefreshError,Q=J.accounts.find((V)=>V.id===Z.id);if(!Q||!K8(Q)||Q.corrupt)return;if(!W&&!B)return;let Y={...J,accounts:[{...Q,...Q.lastRefreshError||!W?{}:{lastRefreshError:W},...Q.quota||!B?{}:{quota:B}}]};try{await N8(Y,$.paths,{accounts:[Z.id]})}catch(V){$.log.warn("legacy main backoff not carried to the pool row",{rowId:Z.id,error:V instanceof Error?V.message:String(V)})}}async function s2($,Z,J={}){await f4($,(X)=>{let z=O0(X);if(delete X.mainAccountId,Z==="migrate"&&z.migratedAt===void 0)EB(X);return Y1(X,{...z.migratedAt!==void 0||Z==="migrate"?{migratedAt:z.migratedAt??$.now()}:{},...J.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:J.declinedSlotFingerprint}:z.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:z.declinedSlotFingerprint}:{}}),!0})}function EB($){let Z=$.routing;if(Z===void 0)$.routing={mode:"main-first"};else if(j0(Z)&&Z.mode===void 0)$.routing={...Z,mode:"main-first"}}async function C$($){await f4($,(Z)=>{let J=O0(Z);if(!J.pending)return!1;let{pending:X,...z}=J;return Y1(Z,z),!0})}async function RB($,Z){await f4($,(J)=>{let X=O0(J);if(Z.identity)J.mainAccountId=Z.identity;return Y1(J,{...X,pending:Z}),!0})}async function IB($,Z,J,X){let z=await g4($,x4,$.paths.configPath,$.locks.mainRefreshTtlMs);try{return await bB($,Z,J,X)}finally{await z.release().catch(()=>{})}}async function bB($,Z,J,X){let z=(Y)=>({status:"completed",rowId:J.rowId,operation:X,placeholder:Y}),G=await v4($);if(G.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(G.kind==="placeholder"){if(G.origin===void 0)return{status:"untagged-placeholder"};if(G.origin!==M$($))return{status:"foreign-placeholder"};return await s2($,Z),await $.onStep("after-record-clear"),z("already-present")}if(Object.keys(await $.slot.all()).length===0)return{status:"retry",reason:"torn-read"};if(G.kind==="real"&&G.fingerprint!==J.slotFingerprint&&J.identity!==void 0&&G.identity===J.identity)return await C$($),await $.onStep("after-record-clear"),{status:"restart"};if(G.kind!=="real"||G.fingerprint!==J.slotFingerprint)return await s2($,Z),await $.onStep("after-record-clear"),z("slot-moved-on");await $.onStep("before-placeholder-write");let B=await $.slot.get({path:{id:c2}}),W=B===void 0||B===null?void 0:T8(B);if(W?.kind!=="real"||W.fingerprint!==J.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await $.slot.set({path:{id:c2},body:{...y4,accountId:M$($)}})}catch(Y){if(Y instanceof J1)return{status:"retry",reason:"slot-changed"};throw Y}await $.onStep("after-placeholder-write");let Q=await $.slot.get({path:{id:c2}});if(!k4(Q))return{status:"retry",reason:"placeholder-overwritten"};if(j0(Q)&&Q.accountId===void 0)return{status:"untagged-placeholder"};if(j0(Q)&&Q.accountId!==M$($))return{status:"foreign-placeholder"};return await s2($,Z),await $.onStep("after-record-clear"),z("written")}async function kB($,Z,J){let{record:X}=J;if(J.fresh)await RB($,X),await $.onStep("after-record-write");if(await L8($,J.credential.refresh))return{status:"restart"};let z=await v4($);if(z.kind!=="real"||z.fingerprint!==X.slotFingerprint)return{status:"restart"};return await _B($,X,J.credential),await $.onStep("after-row-write"),_8($,Z,X,J.fresh?X.operation:"resumed")}async function _8($,Z,J,X){let z=await OB($,J);if(!z)return{status:"retry",reason:"verify-failed"};if(await $.onStep("after-verify"),J.carryLegacyMain)await AB($,z),await $.onStep("after-carry-over");let G=await IB($,Z,J,X);if(G.status==="untagged-placeholder"){await $.store.disable(J.rowId,UB,{extraLocks:G1($.paths,J.rowId,$.locks),attribution:{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}}}),await s2($,Z);let B=`${$.paths.configPath}\x00${J.rowId}`;if(!j8.has(B))j8.add(B),$.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${qB}`,{rowId:J.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(G.status!=="foreign-placeholder")return G;return await $.store.remove(J.rowId,{extraLocks:G1($.paths,J.rowId,$.locks),protect:(B,W)=>W.row?.fingerprint!==J.credentialFingerprint?"the transfer row changed before rollback":void 0}),await C$($),await T$($),{status:"refused",reason:"placeholder-without-main"}}var U8=new Set,q8=new Set,j8=new Set;function M$($){return`openai-auth-pool:${BB("sha256").update(YB($.paths.configPath)).digest("hex")}`}async function xB($){try{let Z=await $();return Z.open?[]:Z.blockers}catch(Z){return[{pid:"unknown",version:"unknown",detail:Z instanceof Error?Z.message:String(Z)}]}}async function O8($,Z,J){let X=jB($),z=X.slot.migrationDisabledReason?.();if(z){let Y=X.slot.path??Z1();if(!q8.has(Y))q8.add(Y),X.log.info("account pool migration is off: the host login slot is read-only",{reason:z});return{status:"slot-read-only",reason:z}}let G;try{G=await a2(X.paths.configPath)}catch(Y){return{status:"error",reason:Y instanceof Error?Y.message:String(Y)}}let B=await S8(X,Z,G);if(B){if(B.status==="already-migrated"&&"mainAccountId"in G)await T$(X);return B}if(J){let Y=await xB(J);if(Y.length>0){let V=`${X.paths.configPath}\x00${Y.map((H)=>`${H.pid}@${H.version}`).join(",")}`;if(!U8.has(V))U8.add(V),X.log.info("account pool migration deferred: an older openai-auth version is running",{blockers:Y});return{status:"deferred",reason:"older-version-running",blockers:Y}}}let W,Q;try{Q=await g4(X,"pool-slot-transfer",X.slot.path??Z1(),X.locks.mainRefreshTtlMs,$.signal),W=await g4(X,M8,X.paths.configPath,X.locks.mainRefreshTtlMs,$.signal)}catch(Y){if(await Q?.release().catch(()=>{}),Y instanceof M2)return{status:"retry",reason:"lock-contention"};throw Y}try{return await yB(X,Z)}catch(Y){if(Y instanceof M2)return{status:"retry",reason:"lock-contention"};if(Y instanceof b)return{status:"retry",reason:Y.kind==="lock-contention"?"lock-contention":`store-${Y.kind}`};throw Y}finally{await W?.release().catch(()=>{}),await Q?.release().catch(()=>{})}}async function S8($,Z,J){let X=O0(J);if(X.pending)return;if(Z==="migrate"&&X.migratedAt!==void 0){let z=await $.store.read();if(z.status==="ready"&&!z.rows.some((G)=>G.id==="main")&&!X.pending&&z1(await v4($),z.rows.some((G)=>G.id==="main"),X))return{status:"refused",reason:"placeholder-without-main"};return{status:"already-migrated"}}if(Z==="adopt"&&X.migratedAt===void 0)return{status:"not-migrated"};return}async function yB($,Z){let J;for(let X=0;X<4;X++){let z=await a2($.paths.configPath),G=await S8($,Z,z);if(G){if(G.status==="already-migrated")await T$($);return G}let B=await $.store.read(),W=O0(z);if(B.status==="pending-migration"){if(z1(await v4($),B.roster.some((H)=>j0(H)&&H.id==="main"),W))return{status:"refused",reason:"placeholder-without-main"};await $.store.initialize(),await $.onStep("after-pool-key-write"),B=await $.store.read()}if(B.status!=="ready")return{status:"error",reason:B.status==="error"?`${B.file}: ${B.reason}`:"pool still pending migration"};let Q=await MB($);if(Q.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(Q.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(z1(Q,B.rows.some((H)=>H.id==="main"),W))return{status:"refused",reason:"placeholder-without-main"};let Y=LB(Z,W,B.rows,Q,J,$.now(),$.newId);if(Y.kind==="nothing"){if(Z==="migrate")await s2($,Z),await $.onStep("after-marker-write");return{status:"nothing-to-import",slot:Y.slot}}if(Y.kind==="drop-record"){await C$($),await $.onStep("after-record-clear");continue}if(Y.kind==="ambiguous")return await s2($,Z,{declinedSlotFingerprint:Y.record.slotFingerprint}),await $.onStep("after-record-clear"),$.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:Y.record.rowId}),{status:"ambiguous",rowId:Y.record.rowId};if(Y.kind==="transfer"&&Y.fresh)J=Y.record.rowId;let V=Y.kind==="finish"?await _8($,Z,Y.record,"resumed"):await kB($,Z,Y);if(V.status!=="restart")return V}return{status:"retry",reason:"unsettled"}}async function T$($){await f4($,(Z)=>{if(!("mainAccountId"in Z))return!1;if(O0(Z).pending)return!1;return delete Z.mainAccountId,!0})}function TN($){return O8($,"migrate",$.fence)}function LN($){return O8($,"adopt")}class A8 extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function G1($,Z,J={}){let X={...W1,...J},z={renew:X.renew,timeoutMs:X.timeoutMs,retryMs:X.retryMs,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}};return[{name:x4,path:$.configPath,ttlMs:X.mainRefreshTtlMs,...z},{name:P8(Z),path:$.configPath,ttlMs:X.fallbackTtlMs,...z}]}async function _N($,Z,J,X={}){let z=$.now??Date.now,G=$.sleep??((Q)=>new Promise((Y)=>setTimeout(Y,Q))),B=$.leaseWait??{timeoutMs:4000,pollMs:50},W=async(Q,Y)=>{let V=I4(Q.refresh),H=async()=>{let q=await Q1($.paths),F=q?.refresh?.mainRefreshLeaseUntil;return Boolean(F&&F>z()&&q?.refresh?.mainRefreshLeaseTokenHash===V)};if(await H()){let q=z()+B.timeoutMs;while(z()<q&&await H())await G(B.pollMs);throw new A8}return J(Q,Y)};return $.store.refresh(Z,W,{...X,extraLocks:G1($.paths,Z,$.legacyLocks)})}function E8(){let $=crypto.getRandomValues(new Uint8Array(16)),Z=Date.now();$[0]=Z/1099511627776&255,$[1]=Z/4294967296&255,$[2]=Z/16777216&255,$[3]=Z/65536&255,$[4]=Z/256&255,$[5]=Z&255,$[6]=($[6]??0)&15|112,$[8]=($[8]??0)&63|128;let J=Array.from($,(X)=>X.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}import{chmodSync as gB,mkdirSync as R8,readFileSync as fB,renameSync as vB,writeFileSync as hB}from"node:fs";import{dirname as I8}from"node:path";var L$="sessions",mB=1e4,wB=5000,uB=25;async function pB($,Z=wB){let J=performance.now()+Z;for(;;){let X=await K0({name:L$,path:$,ttlMs:mB});if(X||performance.now()>=J)return X;await new Promise((z)=>setTimeout(z,uB))}}function lB($){let Z=new Map,J=JSON.parse(fB($,"utf8"));if(!R(J.sessions))return Z;for(let[X,z]of Object.entries(J.sessions)){if(!R(z)||typeof z.threadID!=="string")continue;Z.set(X,z.threadID)}return Z}function kN($,Z=E8){let J=new Map,X;try{X=lB($)}catch{return J}for(let[z,G]of X)J.set(z,{threadID:G,turnID:Z(),windowID:`${G}:0`});return J}function dB($,Z){let J=`${$}.tmp-${process.pid}`;R8(I8($),{recursive:!0});let X={version:1,sessions:Object.fromEntries([...Z].map(([z,G])=>[z,{threadID:G}]))};hB(J,`${JSON.stringify(X,null,2)}
|
|
71
|
-
`,{encoding:"utf8",mode:384}),
|
|
72
|
-
`,{mode:384}),await iB(B,G)}catch(W){throw await _$(B,{force:!0}).catch(()=>{}),W}}return J}async function uN($){let Z=$.pid??process.pid,J=$.dir??O$();U1??=($.now??Date.now)(),V1++;let X;try{X=await g8(J,{pid:Z,version:$.version,startedAt:U1,layouts:y8()})}catch(G){$.logger.warn("process heartbeat not written",{dir:J,error:G instanceof Error?G.message:String(G)})}let z=!1;return{path:X,async release(){if(z)return;if(z=!0,V1=Math.max(0,V1-1),V1>0)return;if(oB())return;await _$(b8(Z,J),{force:!0}).catch((G)=>{$.logger.warn("process heartbeat not removed",{dir:J,error:G instanceof Error?G.message:String(G)})})}}}async function j1($){let Z=J0()?"legacy":$.layout;if(q1.set($.key,Z),Z!=="legacy")return;U1??=($.now??Date.now)(),await g8($.dir??O$(),{pid:$.pid??process.pid,version:$.version,startedAt:U1,layouts:y8()})}import{createHash as tB}from"node:crypto";import{realpathSync as eB}from"node:fs";import{chmod as $Q,mkdir as ZQ,readdir as d8,readFile as S0,rmdir as c8,stat as s8,unlink as u4}from"node:fs/promises";import{basename as A$,dirname as N1,isAbsolute as JQ,join as m,relative as XQ,resolve as D1}from"node:path";var zQ="runtime-layout",i2="layout-moving.json",a8=1e4,F1=15000,GQ=4*F1+a8,BQ=50,QQ=5,WQ=50,YQ=[0,10,20,40,80,100],f8=500,VQ="openai-auth keeps its files in OpenCode's config folder until every running OpenCode using it has restarted on this version.",v8="openai-auth found runtime files in OpenCode's config folder again (an older version may have run). It does not use them and leaves them in place; its files are in its state folder.";class X0 extends Error{stateDir;errorClass;constructor($,Z,J=HQ($,Z)){super(J);this.stateDir=$;this.errorClass=Z;this.name="RuntimeLayoutRefusal"}}function HQ($,Z){if(Z==="ERR_PRIVATE_FILES_SECURITY")return`openai-auth cannot start: ${$} is not a folder only your user can access, or it is a link, so the plugin will not use it (${Z}). Replace it with a plain folder of your own, then restart OpenCode.`;return`openai-auth cannot start: it could not settle where its runtime files live in ${$} (${Z}). Check that this folder can be created and written by your user, then restart OpenCode.`}function h8($,Z){return new X0($,"foreign-folder",`openai-auth cannot start: ${$} belongs to another OpenCode config folder, not ${Z}. It was left untouched. Move it aside, then restart OpenCode.`)}function P1($,Z){return new X0($,"credential-conflict",`openai-auth cannot start: runtime credentials conflict between ${Z.old} and ${Z.next}. Keep the newer one, delete the other, then restart OpenCode.`)}function JD(){let $=l0.notice;if(!$||$.shown)return;return $.shown=!0,$.text}function g0($,Z){if(l0.logged.has($))return;l0.logged.add($),Z()}function d0($){if($ instanceof X0)return $.errorClass;let Z=$?.code;if(typeof Z==="string"&&Z)return Z;return $ instanceof Error?$.name:typeof $}function UQ($){let{path:Z,stage:J}=$??{};return{...typeof Z==="string"&&Z?{file:A$(Z)}:{},...typeof J==="string"&&J?{stage:J}:{}}}class w4 extends Error{code;constructor($,Z){super(Z);this.code=$;this.name="LayoutMoveError"}}class E$ extends w4{path;constructor($){super("old-credential-kept",`${$} could not be removed`);this.path=$}}function i8($,Z,J,X){g0(`${$.key}\x00cleanup`,()=>Z.warn("openai-auth could not finish removing its old files from OpenCode's config folder; it tries again at the next start",{configDir:$.configDir,step:J,errorClass:d0(X),...UQ(X)}))}function XD($){let Z=t6(),J=$1(Z);if(J)return Promise.resolve(J);let X=`${Z.stateHomeDir}\x00${Z.key}`,z=l0.runs.get(X);if(!z)z=qQ(Z,$).catch((G)=>{if(G instanceof X0)throw G;throw new X0(Z.stateHomeDir,d0(G))}).finally(()=>{l0.runs.delete(X)}),l0.runs.set(X,z);return z}async function qQ($,Z){let J=Z.log??o("runtime-layout");if(J0()){e6($,"legacy"),g0("legacy-generation",()=>J.info("openai-auth keeps its runtime files in OpenCode's config folder until restart: an older plugin version ran in this process"));try{await j1({key:$.key,layout:"legacy",version:Z.version})}catch(K){J.warn("process heartbeat not written",{errorClass:d0(K)})}return"legacy"}let X=$.stateHomeDir,z=m(X,i6),G=I$($),B=FQ(),W=B.length>0,Q=B.some((K)=>n8(K,X)),Y=Z.fence??jQ(Z.version),V=async()=>{return await j1({key:$.key,layout:"state-home",version:Z.version}),e6($,"state-home"),"state-home"},H=await m4(z,X);if(await l8($,H),H?.oldFilesRemoved&&!Q){await IQ($,G,B,H,J);let K=await F0(m(X,i2)).catch(()=>!0),N=!W&&(await $J(G).catch(()=>[!0])).length>0;if(!K&&!N)return V()}let q=await zJ($.configDir,X),F;try{if(!q)await BJ(X);F=await K1(zQ,z,Z.layoutLockWaitMs??GQ)}catch(K){if(H=await m4(z,X),H&&!Q)return V();throw new X0(X,d0(K))}let U=F,j=async()=>{try{await U.assertOwned(),await j1({key:$.key,layout:"legacy",version:Z.version})}catch(K){throw new X0(X,d0(K))}return e6($,"legacy"),"legacy"};try{if(H=await m4(z,X),await l8($,H),!q)await bQ($);if(Q)return g0(`${$.key}\x00override`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: a path set by OPENCODE_OPENAI_AUTH_STATE_FILE or OPENCODE_OPENAI_AUTH_FILE is inside its state folder, which it never touches",{stateDir:X,overrides:B})),await j();if(H){if(!W&&!q)await NQ($,G,z,H,U,{fence:Y,log:J,steps:Z.steps});else if(H.oldFilesRemoved)await DQ($,U,Z.steps,J);return await V()}if(W)return await j();if(q)return g0(`${$.key}\x00aliased`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: its state folder is that same folder",{configDir:$.configDir,stateDir:X})),await j();let K=await Y();if(!K.open)return m8($,K.blockers,J),await j();let N=!1;try{let D=await KQ($,G,z,U,{fence:Y,log:J,steps:Z.steps,onMarker:()=>{N=!0}});if(D.kind==="deferred")return m8($,D.blockers,J),await j();if(D.kind==="refused")return g0(`${$.key}\x00refused`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: it will not move them",{reason:D.reason,paths:D.paths,stateDir:X})),await j();if(D.moved)J.info("openai-auth moved its runtime files out of OpenCode's config folder",{from:$.configDir,to:X});return await V()}catch(D){if(D instanceof X0)throw D;if(N&&await m4(z,X))return await V();return g0(`${$.key}\x00failed`,()=>J.warn("openai-auth's runtime files stay in OpenCode's config folder: moving them failed; the move is tried again at the next start",{configDir:$.configDir,errorClass:d0(D)})),await j()}}finally{await U.release().catch(()=>{})}}function jQ($){return()=>c7({currentVersion:$,layoutMove:!0})}function m8($,Z,J){g0(`${$.key}\x00deferred`,()=>J.info(VQ,{configDir:$.configDir,blockers:Z}))}function FQ(){let $=$8();if($===void 0)return[];let Z=Z8();return[$,k6($),...Z?[Z]:[]]}function n8($,Z){let J=XQ(w8(Z),w8($));if(J==="")return!0;if(!J.startsWith("..")&&!JQ(J))return!0;return o6($,Z)}function w8($){let Z=D1($),J=[];for(;;){try{return m(eB.native(Z),...J)}catch{}let X=N1(Z);if(X===Z)return D1($);J.unshift(A$(Z)),Z=X}}async function KQ($,Z,J,X,z){let G=$.stateHomeDir,B=await o8($,Z),W=!1;try{let Q=await z.fence();if(!Q.open)return{kind:"deferred",blockers:Q.blockers};let Y=await XJ($,Z);if(Y.length>0)return{kind:"refused",reason:"same-physical-file",paths:Y};let V=await kQ(G),H=(await OQ(Z)).filter((K)=>!V.has(K));if(H.length>0)return{kind:"refused",reason:"destination-in-use",paths:H};let q=await JJ(Z);await X.assertOwned(),await xQ(G,[...new Set([...V,...q.map((K)=>K.next)])]);let F=new Set(q.map((K)=>K.next));for(let K of V){if(F.has(K))continue;await X.assertOwned(),await u4(K).catch((N)=>{if(N.code!=="ENOENT")throw N})}for(let K of q)await X.assertOwned(),await SQ(K);await z.steps?.afterCopy?.(),await X.assertOwned();for(let K of B)await K.assertOwned();let U=await CQ(Z,q),j={version:1,oldDir:$.key,...U?{keptVaultState:U}:{}};z.onMarker(),await S$(J,j),await z.steps?.afterMarker?.(),await X.assertOwned();try{await GJ($,q,X,{log:z.log,keptVaultState:U,steps:z.steps}),await ZJ(Z,X,B,z.steps)}catch(K){if(!(K instanceof E$))throw K;return i8($,z.log,"remove-old-copies",K),{kind:"moved",moved:q.length>0}}return W=!0,await X.assertOwned(),await S$(J,{...j,oldFilesRemoved:!0}),await R$(G,X,z.steps),{kind:"moved",moved:q.length>0}}finally{for(let Q of B.reverse())await Q.release().catch(()=>{});if(W)await r8(Z,X,z.steps)}}async function NQ($,Z,J,X,z,G){let B=[],W=!1,Q="fence";try{if(!(await G.fence()).open)return;if(Q="data-locks",B=await o8($,Z),Q="fence",!(await G.fence()).open)return;Q="same-file-check";let Y=await XJ($,Z);if(Y.length>0){g0(`${$.key}\x00cleanup-aliased`,()=>G.log.warn("openai-auth leaves its old files in OpenCode's config folder: they are the same files as its new ones",{paths:Y}));return}if(Q="remove-old-copies",await z.assertOwned(),!X.oldFilesRemoved)await GJ($,await JJ(Z),z,{log:G.log,keptVaultState:X.keptVaultState,steps:G.steps});Q="remove-old-temps",await ZJ(Z,z,B,G.steps),W=!0,Q="marker",await z.assertOwned(),await S$(J,{...X,oldFilesRemoved:!0}),Q="manifest",await R$($.stateHomeDir,z,G.steps)}catch(Y){if(Y instanceof X0)throw Y;i8($,G.log,Q,Y)}finally{for(let Y of B.reverse())await Y.release().catch(()=>{});if(W)await r8(Z,z,G.steps)}}async function DQ($,Z,J,X){try{await R$($.stateHomeDir,Z,J)}catch(z){g0(`${$.key}\x00manifest`,()=>X.warn(`openai-auth could not remove ${i2} from its state folder; it tries again at the next start`,{stateDir:$.stateHomeDir,errorClass:d0(z)}))}}async function R$($,Z,J){let X=m($,i2);if(!await F0(X))return;await J?.beforeRemove?.(X),await Z.assertOwned(),await yQ($)}async function r8($,Z,J){try{await J?.beforeRemove?.($.vault.old),await Z.assertOwned(),await c8($.vault.old)}catch{}}async function o8($,Z){let J=[];try{if(await F0($.configDir)){if(J.push(await K1("save",Z.state.old,F1)),await F0(Z.vault.old))J.push(await K1("claustrum-roster-write",j2(Z.vault.old,"opencode").rosterPath,F1));for(let X of Z.sessions)J.push(await K1(L$,X.old,F1))}return J}catch(X){for(let z of J.reverse())await z.release().catch(()=>{});throw X}}function I$($){let Z=m($.configDir,b4),J=m($.stateHomeDir,b4);return{state:{old:Z,next:J},vault:{old:k6(Z),next:k6(J)},sessions:[q$,j$].map((X)=>({old:m($.configDir,X),next:m($.stateHomeDir,X)}))}}var PQ=/^[0-9a-f]{64}$/;function t8($){return tB("sha256").update($).digest("hex")}function M1($){return{old:j2($.vault.old,"opencode").statePath,next:j2($.vault.next,"opencode").statePath}}var u8=M9("opencode"),MQ="opencode-enrollment-no-token.json";async function e8($){try{let Z=await E6($,u8);return Z.state==="blocked"&&Z.code==="missing_token"&&Z.proposedName===u8}catch{return!1}}async function CQ($,Z){let J=M1($);if(!Z.some((z)=>z.old===J.old))return;return await e8({statePath:J.next,tokenPath:m($.vault.next,MQ)})?t8(await S0(J.next)):void 0}async function TQ($,Z){if(!Z)return!1;try{return t8(await S0($))===Z}catch{return!1}}async function b$($,Z){if(!Z)return!1;let J=j2($.vault.old,"opencode");if(await TQ(J.statePath,Z))return!0;return e8(J)}async function zD($){let Z=t6(),J=I$(Z);if(D1($)!==D1(J.vault.next))return;let X=Z.stateHomeDir,z=await m4(m(X,i6),X);if(!z?.keptVaultState||z.oldDir!==Z.key)return;let G=M1(J).old;if(!await b$(J,z.keptVaultState))return;await u4(G).catch((B)=>{if(B.code!=="ENOENT")throw B}),await c8(J.vault.old).catch(()=>{})}function LQ($){return $.includes(".lock")||$.includes(".tmp")}var _Q=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/;async function $J($){let Z=j2($.vault.old,"opencode"),J=[$.state.old,...$.sessions.map((z)=>z.old),Z.rosterPath,Z.statePath,Z.tokenPath],X=[];for(let z of new Set(J.map(N1))){let G;try{G=await d8(z,{withFileTypes:!0})}catch(W){if(W.code==="ENOENT")continue;throw W}let B=J.filter((W)=>N1(W)===z).map((W)=>`${A$(W)}.`);for(let W of G)if(W.isFile()&&B.some((Q)=>W.name.startsWith(Q)&&_Q.test(W.name.slice(Q.length))))X.push(m(z,W.name))}return X}async function ZJ($,Z,J,X){for(let z of await $J($)){await X?.beforeRemove?.(z),await Z.assertOwned();for(let G of J)await G.assertOwned();await u4(z).catch((G)=>{if(G.code!=="ENOENT")throw G})}}async function C1($){let Z;try{Z=await d8($,{withFileTypes:!0})}catch(J){let X=J.code;if(X==="ENOENT"||X==="ENOTDIR")return[];throw J}return Z.filter((J)=>J.isFile()&&!LQ(J.name)).map((J)=>J.name).sort()}async function JJ($){let Z=[];if(await F0($.state.old))Z.push($.state);for(let J of await C1($.vault.old))Z.push({old:m($.vault.old,J),next:m($.vault.next,J)});for(let J of $.sessions)if(await F0(J.old))Z.push(J);return Z}async function OQ($){let Z=[];if(await F0($.state.next))Z.push($.state.next);for(let J of await C1($.vault.next))Z.push(m($.vault.next,J));for(let J of $.sessions)if(await F0(J.next))Z.push(J.next);return Z}async function XJ($,Z){let J=[[$.configDir,$.stateHomeDir],[Z.vault.old,Z.vault.next],[Z.state.old,Z.state.next],...Z.sessions.map((z)=>[z.old,z.next])];for(let z of await C1(Z.vault.old))J.push([m(Z.vault.old,z),m(Z.vault.next,z)]);let X=[];for(let[z,G]of J)if(await zJ(z,G))X.push(z);return X}async function zJ($,Z){let J=async(z)=>{try{let G=await s8(z,{bigint:!0});return G.ino===0n?void 0:`${G.dev}:${G.ino}`}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;throw G}},X=await J($);return X!==void 0&&X===await J(Z)}async function SQ($){let Z=await S0($.old),J=Z.toString("utf8");if(!Buffer.from(J,"utf8").equals(Z))throw new w4("not-utf8",`${$.old} is not UTF-8 text`);if(await T1($.next,J),!(await S0($.next)).equals(Z))throw new w4("copy-mismatch",`${$.next} does not match ${$.old}`)}async function GJ($,Z,J,X){let z=[],G=[],B=I$($),W=M1(B).old,Q=[...Z.filter((V)=>V.old!==W),...Z.filter((V)=>V.old===W)];for(let V of Q){if(await J.assertOwned(),V.old===W){if(await b$(B,X.keptVaultState))continue;if(G.length>0)continue;if(X.keptVaultState&&await AQ(V.old,V.next))continue}let H=V.old===B.state.old||n8(V.old,B.vault.old);if(!await RQ(V,$.stateHomeDir,H,()=>EQ(V.old,J,X.steps)))(H?G:z).push(V.old)}if(z.length>0)X.log.warn("openai-auth left old files in OpenCode's config folder; it no longer reads them",{configDir:$.configDir,kept:z});let[Y]=G;if(Y!==void 0)throw new E$(Y)}async function AQ($,Z){try{return(await S0($)).equals(await S0(Z))}catch{return!1}}async function EQ($,Z,J){await J?.beforeRemove?.($),await Z.assertOwned()}function p8($){let Z=$?.code;return process.platform==="win32"&&(Z==="EBUSY"||Z==="EPERM"||Z==="EACCES")}async function RQ($,Z,J,X){let z=performance.now();for(let G of YQ){if(G>0)await new Promise((W)=>setTimeout(W,G));let B;try{B=(await S0($.old)).equals(await S0($.next))}catch(W){if(W.code==="ENOENT"&&!await F0($.old))return!0;if(p8(W)){if(performance.now()-z>=f8)return!1;continue}if(J)throw P1(Z,$);return!1}if(!B){if(J)throw P1(Z,$);return!1}await X();try{return await u4($.old),!0}catch(W){if(W.code==="ENOENT")return!0;if(!p8(W)||performance.now()-z>=f8)return!1}}return!1}async function IQ($,Z,J,X,z){let G=(W)=>J.some((Q)=>o6(Q,W));if(!G(Z.state.old)&&await F0(Z.state.old))throw P1($.stateHomeDir,Z.state);if(!G(Z.vault.old)){let W=M1(Z).old;for(let Q of await C1(Z.vault.old)){let Y=m(Z.vault.old,Q);if(Y===W&&await b$(Z,X.keptVaultState))continue;if(!G(Y))throw P1($.stateHomeDir,{old:Y,next:m(Z.vault.next,Q)})}}let B=[];try{for(let W of Z.sessions)if(await F0(W.old))B.push(W.old)}catch{}if(B.length===0)return;g0(`${$.key}\x00reappeared`,()=>{l0.notice={text:`${v8} Old folder: ${$.configDir}`,shown:!1},z.warn(v8,{configDir:$.configDir,stateDir:$.stateHomeDir,found:B})})}async function m4($,Z){let J,X;for(let z=0;z<QQ;z++){if(z>0)await new Promise((G)=>setTimeout(G,WQ));try{J=await S0($,"utf8");break}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;X=G}}if(J===void 0)throw new X0(Z,d0(X));try{let z=JSON.parse(J);if(z&&typeof z==="object"&&!Array.isArray(z))return{version:1,...typeof z.oldDir==="string"?{oldDir:z.oldDir}:{},...z.oldFilesRemoved===!0?{oldFilesRemoved:!0}:{},...typeof z.keptVaultState==="string"&&PQ.test(z.keptVaultState)?{keptVaultState:z.keptVaultState}:{}}}catch{}throw new X0(Z,"malformed-marker",`openai-auth cannot start: ${$} is malformed. The old files are still in OpenCode's config folder. Delete layout.json, then restart OpenCode.`)}async function l8($,Z){let J=$.stateHomeDir;if(Z?.oldDir!==void 0&&Z.oldDir!==$.key)throw h8(J,$.key);let X;try{X=await S0(m(J,F$),"utf8")}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;throw new X0(J,d0(G))}let z;try{z=JSON.parse(X)?.configDir}catch{}if(z!==$.key)throw h8(J,$.key)}async function bQ($){let Z=m($.stateHomeDir,F$);if(await F0(Z))return;await T1(Z,`${JSON.stringify({version:1,configDir:$.key},null,2)}
|
|
73
|
-
`)}async function
|
|
74
|
-
`)}async function
|
|
75
|
-
`)}async function T1($,Z){await BJ(N1($)),await P0($,null,{serialize:()=>Z,durable:!0,durability:"file-only-on-windows"})}async function BJ($){if(process.platform==="win32")return;await
|
|
76
|
-
export{B4 as ka,u as la,qX as ma,
|
|
69
|
+
`);if(W.length>1048576)Q=!0,W=""}F.enqueue(q)},flush(){if(G)Y(W+B.decode());n9($,Z,{...z,failed:Q})}})),H=new Response(V,{status:J.status,statusText:J.statusText,headers:J.headers});return Object.defineProperties(H,{url:{value:J.url},redirected:{value:J.redirected}}),H}function JG($){let Z=s9($);if(!Z?.keep_warm)return;return{mode:Z.keep_warm,hours:Z.hours}}function GF($,Z){let J=JG($);return J?J.mode!=="off":Z}function BF($,Z){c6($,{...Z,ttlMs:"implicit",source:"warm"})}function QF($,Z){a9($,Z)}function XG($,Z){setTimeout(()=>{c6($,{at:Z,ttlMs:"implicit",source:"response"})},0)}function WF($,Z,J=Date.now){if(!Z||!$.ok||!R4())return $;let X=()=>{XG(Z,J())};if(!$.body)return X(),$;let z=$.body.getReader();return new Response(new ReadableStream({async pull(G){try{let B=await z.read();if(B.done)G.close(),X();else G.enqueue(B.value)}catch(B){G.error(B)}},cancel(G){return z.cancel(G)}},{highWaterMark:0}),{status:$.status,statusText:$.statusText,headers:$.headers})}import{types as zG}from"node:util";var GG=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,BG=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function T7($){return $.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,(Z,J,X)=>{if(J)return String.fromCharCode(Number.parseInt(J,16));return{b:"\b",f:"\f",n:`
|
|
70
|
+
`,r:"\r",t:"\t"}[X]??X??Z})}function QG($,Z){if(!Z)return $;let J=$.split(Z).join("[credential]"),X=Z.replace(/\s/g,"");if(!X)return J;let z=J.replace(/\s/g,"");if(!z.includes(X))return J;let G=[];for(let Q=0;Q<J.length;Q++){let Y=J[Q]??"";if(!/\s/.test(Y))G.push(Q)}let B=[],W=0;for(let Q=z.indexOf(X);Q>=0;Q=z.indexOf(X,Q+X.length)){let Y=G[Q]??W,V=(G[Q+X.length-1]??Y)+1;B.push(J.slice(W,Y),"[credential]"),W=V}return B.length?B.join("")+J.slice(W):J}function D7($,Z){let J=QG($,Z);return C7(J).replaceAll("***REDACTED***","[credential]")}function w2($,Z){let J=D7($,Z),X=T7(J),z=D7(X,Z);return z===X?J:z}function P7($){let Z=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec($);if(!Z)return;let J=Z[3]??"",X=(Z[2]??"")+J,z=0;while(X[z]==="0")z++;if(z===X.length)return"0";let G=X.length;while(X[G-1]==="0")G--;let B=Z[4]??"0",W=B.startsWith("-")||B.startsWith("+")?1:0;while(B[W]==="0")W++;let Q=B.slice(W)||"0";if(Q.length>16)return;let Y=BigInt((B.startsWith("-")?"-":"")+Q)-BigInt(J.length)+BigInt(X.length-G);return`${Z[1]}${X.slice(z,G)}e${Y}`}function L7($,Z){let J=Z?P7(Z):void 0;return $.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(X)=>{if(!X.startsWith('"'))return Z&&(X===Z||J!==void 0&&P7(X)===J||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(X)&&String(Number(X))===Z)?'"[credential]"':X;let z=T7(X.slice(1,-1)),G=w2(z,Z);return G===z?X:JSON.stringify(G)})}function o9($,Z){let J=L7($,Z);try{return JSON.parse($),J}catch{return w2(J,Z)}}var WG=16384,YG=65536,VG=[/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 HG($){try{let Z=d(JSON.parse($),"request_id");if(typeof Z==="string")return Z;if(typeof Z!=="number")return;let J=0,X,z=!0,G=!1,B;for(let W of $.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Q=W[0];if(Q==="{"||Q==="["){J++;continue}if(Q==="}"||Q==="]"){J--;continue}if(J!==1)continue;if(Q===","){z=!0,G=!1,X=void 0;continue}if(Q===":"){G=!0;continue}if(z&&Q.startsWith('"')){X=JSON.parse(Q),z=!1;continue}if(G&&X==="request_id"&&!Q.startsWith('"'))B=Q;G=!1}return B}catch{return}}function UG($,Z){let J=o9($,Z);if(Buffer.byteLength(J,"utf8")<=YG)return J;let X=VG.flatMap((G)=>G.exec(J)?.[0]??[]);for(let G of["FreeUsageLimitError","GoUsageLimitError"])if(J.includes(G))X.push(G);let z={retry:X};try{let G=JSON.parse(J);if(d(G,"type")==="error")z.type="error";let B=d(G,"error"),W={};for(let Y of["code","type"]){let V=d(B,Y);if(typeof V==="string")W[Y]=V.slice(0,256)}if(Object.keys(W).length)z.error=W;let Q={};for(let Y of["workspace","limitName"]){let V=d(d(G,"metadata"),Y);if(typeof V==="string")Q[Y]=V.slice(0,256)}if(Object.keys(Q).length)z.metadata=Q}catch{}return JSON.stringify(z)}function s6($){if(!$||typeof $!=="object")return!1;let Z=$;for(let J=0;Z&&J<16;J++){if(zG.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function d($,Z){if(!s6($))return;let J=Object.getOwnPropertyDescriptor($,Z);return J&&"value"in J?J.value:void 0}function I4($,Z){return w2($,Z).slice(0,WG)}function u2($,Z){let J=Object.getOwnPropertyDescriptor($,Z)?.get;if(!J)throw Error(`Missing native ${Z} accessor`);return J}var qG=u2(DOMException.prototype,"message"),jG=u2(DOMException.prototype,"name");function r9($,Z){let J=d($,"message"),X=d($,"name");if(s6($)&&$ instanceof DOMException)try{J=qG.call($),X=jG.call($)}catch{}let z=Error(I4(typeof J==="string"?J:typeof $==="string"?$:"Provider request failed",Z));for(let H of Object.getOwnPropertyNames(z))if(H!=="message")Reflect.deleteProperty(z,H);Object.defineProperty(z,"name",{value:typeof X==="string"?I4(X,Z):"Error",configurable:!0,writable:!0});let G=(H,q,F)=>{let U=d(H,F);if(typeof U==="string"||typeof U==="number"&&Number.isFinite(U)||typeof U==="boolean")Object.defineProperty(q,F,{value:typeof U==="string"?I4(U,Z):U,enumerable:!0,configurable:!0,writable:!0})};for(let H of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let q=d($,H);if(typeof q==="number"&&Number.isFinite(q))G($,z,H)}for(let H of["code","type","isRetryable"])G($,z,H);for(let H of["error","data"]){let q=d($,H),F=Object.create(null);for(let j of["type","code","message","resets_at","resets_in_seconds"])G(q,F,j);let U=d(q,"error");if(s6(U)){let j=Object.create(null);for(let K of["type","code","message","resets_at","resets_in_seconds"])G(U,j,K);F.error=j}if(Object.keys(F).length)Object.defineProperty(z,H,{value:F,enumerable:!0})}let B=d($,"responseHeaders");if(B&&typeof B==="object"){let H={};for(let q of["retry-after-ms","retry-after"]){let F=d(B,q);if(typeof F==="string")H[q]=I4(F,Z)}Object.defineProperty(z,"responseHeaders",{value:H,enumerable:!0})}let W=d($,"responseBody");if(typeof W==="string")Object.defineProperty(z,"responseBody",{value:UG(W,Z),enumerable:!0});let Q=d($,"request_id"),Y=d(B,"x-request-id"),V=typeof Q==="string"?Q:typeof Y==="string"?Y:typeof W==="string"?HG(o9(W,Z)):void 0;if(typeof V==="string")Object.defineProperty(z,"request_id",{value:I4(V,Z),enumerable:!0});for(let H of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let q=Symbol.for(H);if(d($,q)===!0)Object.defineProperty(z,q,{value:!0})}return z}function FG($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!GG.test($)&&!BG.test($)))return $;let J;try{J=JSON.parse($)}catch{return $}if(J?.type==="error"||J?.error||J?.response?.error)return L7($,Z);return $}var KG=u2(Response.prototype,"status"),NG=u2(Response.prototype,"statusText"),DG=u2(Response.prototype,"headers"),PG=u2(Response.prototype,"body"),MG=Response.prototype.text,M7=Headers.prototype.entries;async function UF($,Z,J="http"){try{let F=function(U){let j=q&&U.startsWith("\uFEFF")?"\uFEFF":"";return q=!1,j+U.slice(j.length).replace(/^data: ?([^\r\n]*)/gm,(K,N)=>K.slice(0,K.length-N.length)+FG(N,Z))};if(!s6($))throw Error("Invalid provider response");let X=KG.call($),z=DG.call($),G=PG.call($),B=new Headers;for(let[U,j]of M7.call(z))B.append(U,j);let W={status:X,statusText:w2(NG.call($),Z),headers:B};if(X<200||X>299){for(let[j,K]of M7.call(z)){if(w2(j,Z?.toLowerCase())!==j){W.headers.delete(j);continue}try{W.headers.set(j,w2(K,Z))}catch{W.headers.delete(j)}}W.headers.delete("content-length");let U=await MG.call($);return new Response(o9(U,Z),W)}if(!G||J==="http")return $;W.headers.delete("content-length");let Q=ReadableStream.prototype.getReader.call(G),Y=new TextDecoder("utf-8",{ignoreBOM:!0}),V=new TextEncoder,H="",q=!0;return new Response(new ReadableStream({async pull(U){try{for(;;){let j=await Q.read();H+=Y.decode(j.value,{stream:!j.done});let K=!1;for(;;){let N=/\r?\n\r?\n/.exec(H);if(!N)break;let D=N.index+N[0].length;U.enqueue(V.encode(F(H.slice(0,D)))),H=H.slice(D),K=!0}if(j.done){if(H)U.enqueue(V.encode(F(H)));U.close();return}if(K)return}}catch(j){U.error(r9(j,Z))}},async cancel(U){try{await Q.cancel(U)}catch(j){throw r9(j,Z)}finally{Q.releaseLock()}}}),W)}catch(X){throw r9(X,Z)}}var _7={unproven:0,reading:1,provider:2};class t9{namespace;entries=new Map;constructor($){this.namespace=$}record($,Z){if($.accountKey.namespace!==this.namespace)return;if(![$.expiry,$.observedAt,$.evidenceAt,Z].every(Number.isFinite))return;if(this.prune(Z),$.expiry<=Z)return;let J=y($.accountKey),X=this.entries.get(J);if(X?.expiry===$.expiry){if(_7[X.branch]<=_7[$.branch])return}if(this.entries.set(J,$),this.entries.size<=256)return;let z,G=1/0;for(let[B,W]of this.entries)if(W.observedAt<G)z=B,G=W.observedAt;if(z!==void 0)this.entries.delete(z)}read($,Z,J,X){this.prune(X);let z=this.entries.get(y($));return z?.expiry===Z&&z.evidenceAt===J?z:void 0}retire($){this.entries.delete(y($))}clear(){this.entries.clear()}reconcile($,Z){this.prune(Z);for(let[J,X]of this.entries)if(!$.marks.some((z)=>R(z.key.account,X.accountKey)&&z.key.window==="account"&&z.key.scope.kind==="pool"&&z.entries.some((G)=>G.cause==="rate-limit"&&G.until===X.expiry&&G.evidenceAt===X.evidenceAt)))this.entries.delete(J)}prune($){for(let[Z,J]of this.entries)if(J.expiry<=$)this.entries.delete(Z)}}import{randomUUID as S7}from"node:crypto";import{randomUUID as CG}from"node:crypto";function e9($,Z){return(Z?.rows??[]).map((J)=>({account:{namespace:$,accountId:J.routeId,incarnation:String(J.addedAt)},credentialEpoch:String(J.addedAt),...J.accountIdentity===void 0?{}:{identity:J.accountIdentity}}))}async function $$($){let{namespace:Z,path:J}=$,X=CG(),z=new V2,G=new q4(Z,$.logger),B=new K4($.logger),W=$.now??Date.now,Q=async(V)=>{G.assertWritable();let H=await I6(J),{snapshot:q,replacement:F}=G.decode(H?.limits);if(!F&&z.lost(q,V))return B.schedule(()=>Y.commit([],V)),{snapshot:z.recover(q,V,Z,W()),bindings:e9(Z,H),authoritative:!1,degradedAgreement:!0};if(q)z.remember(q);return{snapshot:q??T0(Z,X),bindings:e9(Z,H),authoritative:!0}},Y={namespace:Z,read:Q,subscribe:B.subscribe,commit:async(V,H)=>{G.assertWritable();let q,F,U=()=>{if(G.didCommit(q)&&F)z=new V2,z.remember(F,H)},j=await O7(J,(K)=>{let N=e9(Z,K),D=G.decode(K?.limits),O=D.snapshot;q=D.replacement;let M=!q&&z.lost(O,H),P=Y2(M?z.recover(O,H,Z,W()):O??T0(Z,X),V,{now:W(),bindings:N,authorizeEpoch:(L,C)=>L.credentialEpoch===C.credentialEpoch});return F=P.snapshot,{next:{...K??{version:1,complete:!0,rows:[],declined:[]},limits:P.snapshot},result:{...P,bindings:N,authoritative:!0,degradedAgreement:M}}},{beforePublish:async()=>G.assertWritable(),onPublished:U});return U(),z.remember(j.snapshot,H),j}};return await Q(),Y}var TG=256,LG=256,_G=1024;function Z$($){return JSON.stringify([y($.account),$.until,$.evidenceAt])}class J${log;generation;issued=0;adopted=0;remembered=new Map;staged=new Map;consumed=new Map;exhausted=!1;constructor($=()=>{}){this.log=$}capture($,Z){return{token:++this.issued,view:$,at:Z}}adopt($,Z){let{view:J,token:X,at:z}=$,G=J.snapshot;if(X<=this.adopted||!J.authoritative||J.degradedAgreement||G.namespace!==Z.namespace||G.generation!==Z.generation||G.revision!==Z.revision)return!1;if(this.adopted=X,this.generation!==G.generation)this.generation=G.generation,this.remembered.clear(),this.staged.clear(),this.consumed.clear();let B=new Set(J.bindings.map((Q)=>y(Q.account))),W=new Map;for(let Q of G.marks){if(Q.key.window!=="account"||Q.key.scope.kind!=="pool")continue;if(!B.has(y(Q.key.account)))continue;for(let Y of Q.entries){if(Y.cause!=="rate-limit")continue;let V={account:Q.key.account,until:Y.until,evidenceAt:Y.evidenceAt,committedRevision:Y.committedRevision};W.set(Z$(V),V)}}for(let Q of[this.remembered,this.staged])for(let[Y,V]of Q){if(!B.has(y(V.account))){Q.delete(Y);continue}if(W.has(Y))continue;let H=G.tombstones.some((q)=>y(q.key.account)===y(V.account)&&q.key.window==="account"&&q.key.scope.kind==="pool"&&q.revision>=V.committedRevision&&(q.cause===void 0||q.cause==="rate-limit"));if(Q===this.staged&&!H)continue;if(Q.delete(Y),!H&&Q===this.remembered&&V.until<=z)this.stage(V)}for(let[Q,Y]of W){if(this.consumed.has(Q))continue;if(Y.until<=z)this.remembered.delete(Q),this.stage(Y);else if(this.remembered.has(Q)||this.remembered.size<TG)this.remembered.set(Q,Y)}return!0}stage($){let Z=Z$($);if(this.consumed.has(Z)||this.exhausted)return;let{NEGATIVE_INFINITY:J,NEGATIVE_INFINITY:X}=Number;for(let z of this.consumed.values()){if(y(z.account)!==y($.account))continue;J=Math.max(J,z.until),X=Math.max(X,z.evidenceAt)}if($.until<=J&&$.evidenceAt<=X)return;if(this.staged.has(Z)||this.staged.size<LG)this.staged.set(Z,$)}candidate($,Z){if(this.exhausted||this.generation===void 0)return;let J=y($.account),X;for(let z of this.staged.values()){if(y(z.account)!==J||z.until>Z)continue;if(!X||z.until>X.until||z.until===X.until&&z.evidenceAt>X.evidenceAt)X=z}return X&&{...X,generation:this.generation}}consume($){let Z=Z$($);if(this.exhausted||$.generation!==this.generation||!this.staged.has(Z)||this.consumed.has(Z))return!1;let J=[...this.staged].filter(([,X])=>y(X.account)===y($.account));if(this.consumed.size+J.length>_G)return this.exhausted=!0,this.staged.clear(),this.log("OpenAI limits recovery evidence is full; skipping further recovery clears."),!1;for(let[X,z]of J)this.consumed.set(X,z),this.staged.delete(X);return!0}}var G$=5000,X$=1000,z$=60000,OG={now:()=>Date.now(),setTimeout:($,Z)=>setTimeout($,Z),clearTimeout:($)=>clearTimeout($)};class A7{options;clock;dropped;owners=0;registry;recovery;provenance;provenanceGeneration;adapter;acquiring;releasing;deadline;fallback=!1;fallbackResolve;fallbackSignal=new Promise(($)=>{this.fallbackResolve=$});failureAt;retryAt=0;retryDelay=X$;failureTimer;latestRead;adoptedBindings=[];controls=new Map;projection;producerId=S7();constructor($,Z,J){this.options=$;this.clock=Z;this.dropped=J;this.recovery=new J$($.log),this.provenance=new t9($.namespace)}stopTracking(){if(this.fallback)return;this.fallback=!0,this.clock.clearTimeout(this.failureTimer),this.fallbackResolve(),this.options.log("OpenAI limits tracking is unavailable; serving without timed marks for this process.");let $=this.registry;if(this.registry=void 0,this.adapter=void 0,this.latestRead=void 0,this.provenance.clear(),$)this.releasing=$.dispose().catch(()=>{})}wait($){return new Promise((Z)=>this.clock.setTimeout(Z,Math.max(0,$)))}async bounded($,Z){let J;try{return await Promise.race([$,this.fallbackSignal.then(()=>{return}),new Promise((X)=>{J=this.clock.setTimeout(()=>X(void 0),Math.max(0,Z-this.clock.now()))})])}finally{this.clock.clearTimeout(J)}}recordFailure(){if(!this.registry||this.fallback)return;let $=this.clock.now();if(this.failureAt===void 0)this.failureAt=$,this.failureTimer=this.clock.setTimeout(()=>this.stopTracking(),z$);if(this.retryAt=$+this.retryDelay,this.retryDelay=Math.min(z$,this.retryDelay*2),$-this.failureAt>=z$)this.stopTracking()}recordSuccess(){this.failureAt=void 0,this.retryAt=0,this.retryDelay=X$,this.clock.clearTimeout(this.failureTimer),this.failureTimer=void 0}async makeAdapter(){let $=await this.options.adapter();return{namespace:$.namespace,read:async(Z)=>{if(this.adoptRead(),this.registry&&this.clock.now()<this.retryAt)throw this.registry.lastFailure??Error("limits-reload-backoff");try{let J=await $.read(Z);this.latestRead=this.recovery.capture(J,this.clock.now());let X=!Z||J.snapshot.generation!==Z.generation||J.snapshot.revision>=Z.revision;if(J.authoritative&&!J.degradedAgreement&&X)this.recordSuccess();else if(!J.authoritative||J.degradedAgreement)this.recordFailure();return J}catch(J){throw this.recordFailure(),J}},commit:async(Z,J)=>{this.adoptRead();let X=await $.commit(Z,J);return this.latestRead=this.recovery.capture(X,this.clock.now()),X},subscribe:$.subscribe?.bind($)}}async ready($){if(!$||this.fallback||this.registry)return;if(!this.acquiring)this.acquiring=this.acquire().finally(()=>{this.acquiring=void 0});await this.acquiring}async acquire(){await this.releasing,this.deadline??=this.clock.now()+G$;while(!this.fallback&&!this.registry){if(this.clock.now()>=this.deadline){this.stopTracking();return}let $=(async()=>{return this.adapter??=await this.makeAdapter(),j9({adapter:this.adapter,clock:this.clock,isAccessRestrictive:this.options.isAccessRestrictive,onAbandon:()=>this.stopTracking(),onRejected:(Z)=>{this.controls.delete(JSON.stringify([Z.producerId,Z.operationId]))}})})();try{let Z=await this.bounded($,this.deadline);if(!Z||this.fallback){this.stopTracking(),$.then((J)=>J.dispose()).catch(()=>{});return}if(this.registry=Z,Z.abandoned){this.stopTracking();return}this.adoptRead()}catch(Z){if(Z instanceof H4||Z instanceof U4){this.stopTracking();return}if(Z instanceof L0&&Z.code==="pool-not-ready"){this.deadline=void 0,this.adapter=void 0;return}await this.wait(Math.min(X$,Math.max(0,this.deadline-this.clock.now())))}}}adoptRead(){let $=this.current();if($&&this.latestRead&&this.recovery.adopt(this.latestRead,$.snapshot)){if(this.provenanceGeneration!==void 0&&this.provenanceGeneration!==$.snapshot.generation)this.provenance.clear();this.provenanceGeneration=$.snapshot.generation,this.provenance.reconcile($.snapshot,this.clock.now()),this.projection=p9(this.latestRead.view.bindings),this.adoptedBindings=this.latestRead.view.bindings;for(let Z of $.snapshot.operationIds)this.controls.delete(JSON.stringify([Z.producerId,Z.operationId]))}}current(){if(this.registry?.abandoned)this.stopTracking();return this.registry}snapshot(){return this.adoptRead(),this.current()?.snapshot}enqueue($,Z){let J=this.current();if(J){if($.type!=="mark")this.controls.set(JSON.stringify([$.producerId,$.operationId]),$);if(J.enqueue($),$.type!=="mark")this.provenance.retire($.binding.account);else if(Z&&Z.expiry===$.until&&Z.evidenceAt===$.evidenceAt&&y(Z.accountKey)===y($.binding.account))this.provenance.record(Z,this.clock.now());else this.provenance.retire($.binding.account)}else if($.type==="mark")this.dropped()}dropSignal(){this.dropped()}observe($){this.adoptRead();let Z=this.current();if(!Z||!$)return;return{...Z.observe($),registry:Z,evidence:this.recovery.candidate($,this.clock.now())}}afterProbe($,Z,J){if(!$?.evidence||!Z||J||this.current()!==$.registry)return;if(this.adoptRead(),$.registry.snapshot.marks.some((z)=>y(z.key.account)===y($.binding.account)&&z.entries.some((G)=>G.until>this.clock.now()))||!this.recovery.consume($.evidence))return;this.enqueue({type:"clear",producerId:this.producerId,operationId:S7(),binding:$.binding,baseRevision:$.baseRevision,keys:[{scope:{kind:"pool"},window:"account"}],cause:"rate-limit",evidenceAt:$.evidence.evidenceAt})}dispatchAtBound($){this.adoptRead();let Z=this.current()?.snapshot;if(!Z)return{status:"ready"};let J=this.adoptedBindings.find((G)=>y(G.account)===y($.account)),X=[...this.controls.values()].some((G)=>y(G.binding.account)===y($.account)),z=Z.access.some((G)=>y(G.account)===y($.account)&&this.options.isAccessRestrictive(G.state));return{status:!J||!w0(J,$)||X||z?"blocked":"ready",snapshot:Z}}async release(){if(--this.owners!==0)return;if(await this.acquiring,this.owners!==0)return;let $=this.current();if(this.registry=void 0,this.clock.clearTimeout(this.failureTimer),$)this.releasing=$.dispose(),await this.releasing;this.adapter=void 0,this.projection=void 0,this.deadline=void 0,this.provenance.clear()}}class E7{lease;projectionDeadline;constructor($){this.lease=$}snapshot(){return this.lease.snapshot()}async reloadForBindings($){for(;;){this.lease.adoptRead();let Z=this.lease.current();if(!Z)return;if(p9($())===this.lease.projection)return;if(this.projectionDeadline??=this.lease.clock.now()+G$,this.lease.clock.now()>=this.projectionDeadline)return;if(await this.lease.bounded(Z.reload(),this.projectionDeadline),this.lease.adoptRead(),this.lease.clock.now()>=this.projectionDeadline)return;if(Z.degradedAgreement)return}}async beforeDispatch($,Z,J=$?.account.accountId){await this.reloadForBindings(Z);let X=()=>{if(!J)return"ready";let Q=Z().find((Y)=>Y.account.accountId===J);if(!Q)return $?"absent":"ready";if($&&(y(Q.account)!==y($.account)||!w0(Q,$)))return"changed";return"ready"},z=X();if(z!=="ready")return{status:z};let G=this.lease.current();if(!G||!$)return{status:"ready"};if(this.projectionDeadline!==void 0&&this.lease.clock.now()>=this.projectionDeadline)return this.lease.dispatchAtBound($);let B=this.projectionDeadline??this.lease.clock.now()+G$,W=await this.lease.bounded(G.beforeDispatch($),B);if(W?.blocked&&this.lease.current())await this.lease.bounded(G.reload(),B),W=await this.lease.bounded(G.beforeDispatch($),B);if(z=X(),z!=="ready")return{status:z};if(!this.lease.current())return{status:"ready"};return this.lease.adoptRead(),{status:!W||W.blocked?"blocked":"ready",snapshot:W?.snapshot}}}class R7{lease;disposed=!1;constructor($){this.lease=$;$.owners++}get namespace(){return this.lease.options.namespace}get registry(){return this.lease.current()}get provenance(){return this.lease.adoptRead(),this.lease.provenance}async forRequest($){if(this.disposed)throw Error("limits-owner-disposed");return await this.lease.ready($),new E7(this.lease)}snapshot(){return this.lease.snapshot()}observe($){return this.lease.observe($)}enqueue($,Z){this.lease.enqueue($,Z)}dropSignal(){this.lease.dropSignal()}afterProbe($,Z,J=!1){this.lease.afterProbe($,Z,J)}async reload(){let $=this.lease.current();if($)await $.reload();this.lease.adoptRead()}async flush(){await this.lease.current()?.flush()}async dispose(){if(this.disposed)return;this.disposed=!0,await this.lease.release()}}function SG($=OG,Z={}){let J=new Map,X=Z.droppedSignalLog??{logged:!1};return{acquire(z){let G=J.get(z.namespace);if(!G)G=new A7(z,$,()=>{if(X.logged)return;X.logged=!0,z.log("OpenAI limit signal dropped because timed-mark tracking is unavailable.")}),J.set(z.namespace,G);return new R7(G)}}}var I7=Symbol.for("@cortexkit/openai-auth/limits-leases/v1"),b7=globalThis,k7=b7[I7]??SG();b7[I7]=k7;function AG($){let{source:Z}=$,J=Z.kind==="pool"?rZ(Z.configPath,Z.statePath):oZ(Z.rosterPath),X=$.log??(()=>{});return k7.acquire({namespace:J,log:X,isAccessRestrictive:$.isAccessRestrictive??(()=>!1),adapter:()=>Z.kind==="pool"?q9({namespace:J,store:Z.store,logger:{warn:X}}):$$({namespace:J,path:Z.rosterPath,logger:{warn:X}})})}function gF($,Z,J){let X=$.get(Z.sessionId),z=new Set(Z.validPinnedAccountIds);if(X&&!Z.excludeAccountIds.includes(X.accountId)&&x7(X,z,Z.wireAccountIdByAccount[X.accountId])){if(Z.persist){let Q=Z.quotaCheckedAtByAccount[X.accountId];J(Z.sessionId,{accountId:X.accountId,inputBytes:Z.requestBytes,...X.wireIdentity!==void 0?{wireIdentity:X.wireIdentity}:{},...Q!==void 0?{quotaCheckedAt:Q}:{}})}return{accountId:X.accountId}}let G=new Map(Object.entries(Z.quotaCheckedAtByAccount)),B=y7($,G,Z.sessionId),W=Z.select(B);if(!W)return;if(Z.persist){let Q=Z.wireAccountIdByAccount[W.accountId];J(Z.sessionId,{accountId:W.accountId,inputBytes:Z.requestBytes,...Q!==void 0?{wireIdentity:Q}:{},...W.quotaCheckedAt!==void 0?{quotaCheckedAt:W.quotaCheckedAt}:{}})}return{accountId:W.accountId}}import{statSync as EG}from"node:fs";var h7=30000,RG=8,IG=1800000;function m7($){return JSON.stringify([$.id,$.credentialEpoch??null])}function wF($){try{let Z=EG($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function uF($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}function bG($,Z){try{return g7($,Z)}catch{return $}}function pF($,Z,J){let X=m7(Z);$.set(X,[...$.get(X)??[],{credentialEpoch:Z.credentialEpoch,identity:Z.identity,observation:J}].slice(-RG))}function lF($,Z,J){let X=$;for(let z of Z.get(m7($))??[]){if(!(J-z.observation.checkedAt<=IG)||z.credentialEpoch!==$.credentialEpoch||z.identity!==$.identity)continue;X={...X,quota:bG(X.quota,z.observation)}}return X}function dF($,Z,J,X){let z=b4($);if(typeof Z?.status==="number"||f7(Z)){let B=v7({error:Z,now:J,refreshToken:$,...X?{previous:{message:"",checkedAt:J,nextRetryAt:X.nextRetryAt,retryCount:X.retryCount,tokenHash:X.tokenHash}}:{}});return{nextRetryAt:B.nextRetryAt,tokenHash:z,retryCount:B.retryCount}}return{nextRetryAt:J+h7,tokenHash:z,retryCount:X?.tokenHash===z?X.retryCount:0}}function cF($,Z,J,X){let z=new Map;for(let G of $){if(X(G,J))continue;let B=Z.get(G.id);z.set(G.id,B&&B.nextRetryAt>J?B.nextRetryAt:J+h7)}return z}var kG={quota:"Every OpenAI account has used up its quota.",killswitch:"Every OpenAI account is below its killswitch quota floor (see the Limits section of `/openai`).","timed-mark":"Every OpenAI account is paused by OpenAI for now."},xG={quota:"OpenAI quota exhausted — retrying on another account.",killswitch:"Killswitch: all OpenAI accounts are below their configured quota threshold.","timed-mark":"OpenAI rate limit reached — retrying on another account.",hold:"OpenAI usage limit reached on this account. Waiting for it keeps the conversation's prompt cache."};function w7($){return({retryIn:Z,reset:J})=>`${$}${Z?` Retry in ${Z}.`:""}${J?` Resets in ${J}.`:""}`}var yG=X9({refusals:Object.fromEntries(Object.entries(kG).map(([$,Z])=>[$,w7(Z)])),retryable:Object.fromEntries(Object.entries(xG).map(([$,Z])=>[$,w7(Z)])),formatReset:x2});function iF($){let Z=[],J=!1,X=!1,z=$.familyOf??(()=>{return}),G=$.accounts.flatMap((Y)=>{if(Y.usable===!1)return[];let V=R(Y.account,Y.readingAccount??Y.account)&&!(Y.identity&&Y.readingIdentity&&Y.identity!==Y.readingIdentity),H=[];if(V){for(let q of["primary","secondary"]){let F=Y.reading?.[q];if(!F)continue;let U=$2(F.checkedAt,$.now),j=Y.floors?.[q],K=j!==void 0&&F.remainingPercent<j?"killswitch-floor":U&&F.usedPercent>=100?"exhausted":void 0;if(!K)continue;if(K==="killswitch-floor")X=!0;else J=!0;let N=U?d6(F.resetsAt):void 0;H.push({window:q,scope:{kind:"pool"},blockedBy:K,...N===void 0?{}:{reset:{at:N,checkedAt:F.checkedAt}}})}for(let q of Y.confirmedBlockers??[]){if(!q.confirmed||!$2(q.observedAt,$.now))continue;J=!0,H.push({window:q.window,scope:{kind:"pool"},blockedBy:"exhausted",...q.resetAt===void 0?{}:{reset:{at:q.resetAt,observedAt:q.observedAt}}})}}for(let q of Y.marks??[]){if(!Number.isFinite(q.until)||q.until<=$.now)continue;let F=$.provenance?.read(Y.account,q.until,q.evidenceAt,$.now),U=F&&F.branch!=="unproven"&&$2(F.observedAt,$.now);if(!U)Z.push(q.until);H.push({window:"account",scope:{kind:"pool"},blockedBy:"exhausted",...U?{reset:{at:q.until,observedAt:F.observedAt}}:{}})}return[{account:Y.account,readingAccount:Y.account,windows:H}]}),B=$.activity&&$.currentAccountKey&&R($.activity.accountKey,$.currentAccountKey)?$.activity:void 0,W={candidates:G,effectiveModel:$.effectiveModel,familyOf:z,maxAgeMs:l9,maxSameAccountWait:h0($.maxSameAccountWait),activity:B,accountKey:B?.accountKey},Q=K6(W,$.now);if(Q&&Z.some((Y)=>Y<Q.resetAt))W={...W,candidates:[]};return{source:"pool",reason:"quota",messageKey:X?"killswitch":J?"quota":"timed-mark",scan:W}}function rF($,Z){let J=$.phase==="pre-send"?{...$,attempted:void 0,selection:void 0,hold:void 0}:$,X=$7({...J,terminal:Z},{mode:"sticky"});if(!X)throw Error("Missing OpenAI terminal decision");return X}function oF($){let Z=$.decision,J=$.host!=="pi"&&Z.action==="hold"&&Z.waitKind!=="terminal",X=$.host!=="pi"&&!$.requestThrow&&(J||h0($.maxSameAccountWait)!==0&&Z.retryable),z=J?"hold":$.cause??(Z.action==="refuse"?Z.messageKey:"quota");return W9({family:$.host==="pi"?"pi-final":$.requestThrow?"json-412":J?"openai-429":Z.action==="refuse"?Z.family==="pi-final"?"pi-final":X?"openai-429":"json-412":X?"openai-429":"pi-final",messageKey:z,messages:yG,now:$.now,...X&&"retryAfterMs"in Z?{retryAfterMs:Z.retryAfterMs}:{},..."resetAt"in Z&&Z.resetAt!==void 0?{resetAt:Z.resetAt}:{}})}import{randomUUID as gG}from"node:crypto";function fG($){if(!E($))return;let Z=E($.input_tokens_details)?$.input_tokens_details:void 0,J=Z?.cached_tokens,X=Z?.cache_write_tokens,z=E($.output_tokens_details)?$.output_tokens_details.reasoning_tokens:void 0;return{...typeof $.input_tokens==="number"?{input:Math.max(0,$.input_tokens-(typeof J==="number"?J:0)-(typeof X==="number"&&X>0?X:0))}:{},...typeof J==="number"?{cacheRead:J}:{},...typeof X==="number"&&X>0?{cacheWrite:X}:{},...typeof $.output_tokens==="number"?{output:$.output_tokens}:{},...typeof z==="number"?{reasoning:z}:{},reasoningIncludedInOutput:!0}}class vG{sessionId;receipt;requestKind;model;attempt;warming;freeQuota;attemptId=gG();reported=!1;completed=!1;failed=!1;responseId;usage;constructor($,Z,J,X,z,G,B=!1){this.sessionId=$;this.receipt=Z;this.requestKind=J;this.model=X;this.attempt=z;this.warming=G;this.freeQuota=B}event($){if(!E($))return;if($.type==="error"||$.type==="response.failed")this.failed=!0;if($.type!=="response.completed"&&$.type!=="response.incomplete"&&$.type!=="response.failed")return;if(this.completed=$.type!=="response.failed",E($.response)){if(typeof $.response.id==="string")this.responseId=$.response.id;this.usage=fG($.response.usage)}}piCompleted($,Z){if(this.completed=!0,this.piResponseId($),!E(Z))return;let J={reasoningIncludedInOutput:!0};for(let X of["input","output","cacheRead","reasoning"])if(typeof Z[X]==="number")J[X]=Z[X];if(typeof Z.cacheWrite==="number"&&Z.cacheWrite>0)J.cacheWrite=Z.cacheWrite;this.usage=J}piResponseId($){this.responseId=$}end($,Z,J,X=!1){if(this.reported)return;this.reported=!0;let z;try{z=this.warming?.(this.sessionId)}catch{}E4({sessionId:this.sessionId,kind:"billing",attemptId:this.attemptId,requestKind:this.requestKind,credentialId:this.receipt.credentialId,...this.receipt.accountIdentity?{accountId:this.receipt.accountIdentity}:{},provider:"openai",model:this.model,...this.freeQuota?{chargeBasis:"subscription_included"}:{},attempt:this.attempt,cache:{implicit:!0,warming:z?.on?{on:!0}:{on:!1,...A4(z?.stopReason)?{stopReason:z.stopReason}:{}}},outcome:this.failed||J!==void 0&&(J<200||J>=300)?"failed":this.completed&&(Z||X)?"completed":$?"cut":"failed",...J!==void 0?{status:J}:{},...this.responseId?{providerResponseId:this.responseId}:{},...this.usage?{usage:this.usage}:{}})}}import{readdir as mG,readFile as wG,rm as uG,stat as pG}from"node:fs/promises";import{homedir as lG,uptime as dG}from"node:os";import{join as l2}from"node:path";var Q$=Symbol.for("@cortexkit/openai-auth/runtime-layout-runs"),W$=globalThis,B$=globalThis,hG=W$[Q$];W$[Q$]??={};var p2=W$[Q$];p2.legacyGeneration??=hG===void 0&&B$[Symbol.for("@cortexkit/openai-auth/runtime-layouts")]===void 0&&(B$[Symbol.for("@cortexkit/openai-auth/opencode-vaults")]!==void 0||B$[Symbol.for("__openaiAuthRpcServers")]!==void 0||("__openaiAuthRpcServers"in globalThis));p2.runs??=new Map;p2.logged??=new Set;var l0=Object.assign(p2,{runs:p2.runs,logged:p2.logged});function J0(){return l0.legacyGeneration===!0}function a6(){return process.env.XDG_STATE_HOME||l2(lG(),".local","state")}function cG($=a6()){return l2($,"cortexkit","openai-auth","processes")}function sG($=a6()){return l2($,"cortexkit","openai-auth","rpc")}function aG($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}function u7($){let Z=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec($.trim());if(!Z)return;return{core:[Number(Z[1]),Number(Z[2]),Number(Z[3])],pre:Z[4]?Z[4].split("."):[]}}function p7($,Z){let J=u7($),X=u7(Z);if(!J||!X)return;for(let z=0;z<3;z++){let G=J.core[z]-X.core[z];if(G!==0)return Math.sign(G)}if(J.pre.length===0||X.pre.length===0)return Math.sign(X.pre.length-J.pre.length);for(let z=0;z<Math.max(J.pre.length,X.pre.length);z++){let G=J.pre[z],B=X.pre[z];if(G===void 0)return-1;if(B===void 0)return 1;let W=/^\d+$/.test(G),Q=/^\d+$/.test(B);if(W&&Q){let Y=Number(G)-Number(B);if(Y!==0)return Math.sign(Y)}else if(W!==Q)return W?-1:1;else if(G!==B)return G<B?-1:1}return 0}async function Y$($){try{return{ok:!0,names:await mG($)}}catch(Z){let J=Z.code;if(J==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:J,error:`${$}: ${String(Z)}`}}}async function l7($,Z){let J;try{J=await wG($,"utf8")}catch(X){if(X.code==="ENOENT")return{kind:"gone"};return{kind:"unreadable"}}try{let X=JSON.parse(J);if(X!==null&&typeof X==="object"&&X.pid===Z){let z=X.layouts;return{kind:"ok",version:typeof X.version==="string"?X.version:"unknown",startedAt:X.startedAt,...z!==null&&typeof z==="object"&&!Array.isArray(z)?{layouts:z}:{}}}}catch{}return{kind:"unreadable"}}async function c7($){let Z=$.isAlive??aG,J=$.selfPid??process.pid,z=($.now??Date.now)()-($.uptime??dG)()*1000-300000,G=(j)=>typeof j==="number"&&Number.isFinite(j)&&j<z,B=new Map,W=(j)=>{let K=j.pid==="unknown"?`dir:${j.detail}`:j.pid;if(!B.has(K))B.set(K,j)};if($.layoutMove&&J===process.pid&&J0())W({pid:J,version:"unknown",detail:"an older plugin generation ran in this process"});let Q=(j)=>{try{return Z(j)}catch{return!0}},Y=(j,K)=>{let N=K.exec(j),D=N?Number(N[1]):Number.NaN;return Number.isSafeInteger(D)&&D>=1?D:void 0},V=cG($.stateHome),H=await Y$(V);if(!H.ok)W({pid:"unknown",version:"unknown",detail:H.error});for(let j of H.ok?H.names:[]){let K=Y(j,/^(\d+)\.json$/);if(K===void 0||K===J)continue;let N=l2(V,j),D=await l7(N,K);if(D.kind==="gone")continue;if(D.kind==="ok"&&G(D.startedAt)){await uG(N,{force:!0}).catch(()=>{});continue}if(!Q(K))continue;if(D.kind==="unreadable"){W({pid:K,version:"unknown",detail:N});continue}let O=p7(D.version,$.currentVersion);if(O===void 0||O<0){W({pid:K,version:D.version,detail:N});continue}if($.layoutMove===!0&&(D.layouts===void 0||Object.values(D.layouts).includes("legacy")))W({pid:K,version:D.version,detail:N})}let q=$.rpcDir??sG($.stateHome),F=await Y$(q);if(!F.ok)W({pid:"unknown",version:"unknown",detail:F.error});for(let j of F.ok?F.names:[]){if(!d7(j))continue;let K=l2(q,j),N=await Y$(K);if(!N.ok){if(N.code==="ENOTDIR")continue;W({pid:"unknown",version:"unknown",detail:N.error});continue}for(let D of N.names){let O=Y(D,/^port-(\d+)\.json$/);if(O===void 0||O===J||!Q(O))continue;let M=l2(K,D),P=await l7(M,O);if(P.kind==="gone")continue;if(P.kind==="ok"){let T=P.startedAt===void 0?await pG(M).then((A)=>A.mtimeMs).catch(()=>{return}):P.startedAt;if(G(T))continue}let L=P.kind==="ok"?P.version:"unknown",C=p7(L,$.currentVersion);if(C===void 0||C<0)W({pid:O,version:L,detail:M})}}let U=(j)=>j.pid==="unknown"?Number.POSITIVE_INFINITY:j.pid;return B.size===0?{open:!0}:{open:!1,blockers:[...B.values()].sort((j,K)=>U(j)-U(K))}}import{createHash as nG}from"node:crypto";import{existsSync as iG,realpathSync as V$}from"node:fs";import{homedir as i7}from"node:os";import{basename as rG,dirname as oG,join as q0,resolve as q$}from"node:path";var j$="openai-auth-sessions.json",F$="openai-auth-sessions-opencode2.json",n6="layout.json",K$="config-dir.json";function i6(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return tG()}function tG(){return q0(process.env.XDG_CONFIG_HOME||q0(i7(),".config"),"opencode")}function r6(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||q0(i6(),H$)}function d2($,Z){let J=q$($);return Z==="win32"||Z==="darwin"?J.toLowerCase():J}function s7($){try{return V$.native($)}catch{try{return q0(V$.native(oG($)),rG($))}catch{return}}}function o6($,Z,J=process.platform){if(d2($,J)===d2(Z,J))return!0;let X=s7($),z=s7(Z);return X!==void 0&&z!==void 0&&d2(X,J)===d2(z,J)}function a7($){try{return V$.native($)}catch{return q$($)}}var n7=new Map;function t6($=i6()){let Z=a6(),J=q0(i7(),".config","opencode"),X=`${$}\x00${J}\x00${Z}`,z=n7.get(X);if(z&&$1(z))return z;let G=a7($);if(z&&z.key===G)return z;let B=G===a7(J),W=q0(Z,"cortexkit","openai-auth"),Q={key:G,configDir:$,stateHomeDir:B?q0(W,"opencode"):q0(W,`opencode-${nG("sha256").update(G).digest("hex").slice(0,16)}`),isDefaultConfigDir:B};return n7.set(X,Q),Q}var r7=Symbol.for("@cortexkit/openai-auth/runtime-layouts"),o7=globalThis,N$=o7[r7]??new Map;o7[r7]=N$;function t7($){return`${$.stateHomeDir}\x00${$.key}`}function e6($,Z){N$.set(t7($),J0()?"legacy":Z)}function $1($){return N$.get(t7($))}function e7($=i6()){if(J0())return $;let Z=t6($);return($1(Z)??(iG(q0(Z.stateHomeDir,n6))?"state-home":"legacy"))==="state-home"?Z.stateHomeDir:$}function tK($){return q0(e7(),$==="opencode1"?j$:F$)}function D$($){let Z=q0(i6(),H$);return $===Z||d2($,process.platform)===d2(Z,process.platform)}function $8($=r6()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return D$($)?void 0:U$($)}function Z8($=r6()){return D$($)?void 0:$}function eG($=r6()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z){if(o6($,Z))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${q$($)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return Z}if(!D$($))return U$($);return q0(e7(),k4)}function eK($=r6()){return{configPath:$,statePath:eG($)}}import{createHash as QB}from"node:crypto";import{readFileSync as WB}from"node:fs";import{readFile as YB}from"node:fs/promises";import{resolve as VB}from"node:path";import{createHash as $B}from"node:crypto";import{readFile as ZB}from"node:fs/promises";import{homedir as JB}from"node:os";import{join as J8,resolve as XB}from"node:path";var zB="openai",X8=250,y4="main-refresh";function M$($){if(typeof $.access!=="string"||typeof $.refresh!=="string")return;let Z=Buffer.from($.access),J=Buffer.from($.refresh),X=(z)=>{let G=Buffer.alloc(4);return G.writeUInt32BE(z.length),G};return $B("sha256").update(X(Z)).update(Z).update(X(J)).update(J).digest("hex")}function Y8($){if(!$||typeof $!=="object")return;let Z=$;if(Z.type!=="oauth")return;return{type:"oauth",...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.refresh==="string"?{refresh:Z.refresh}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.accountId==="string"?{accountId:Z.accountId}:{}}}function V8($){let Z=Y8($);if(typeof Z?.access!=="string"||typeof Z.refresh!=="string")return;return{access:Z.access,refresh:Z.refresh,...typeof Z.expires==="number"?{expires:Z.expires}:{}}}function z8($){if(P2($)&&$.type==="api"&&typeof $.key==="string")return{kind:"api"};let Z=Y8($);if(!Z)return{kind:"indeterminate"};return O4(Z)?{kind:"tombstone",oauth:Z}:{kind:"real",oauth:Z}}async function G8($){return $.auth.get({path:{id:zB}})}async function B8($){return Object.keys(await $.auth.all()).length>0}async function H8($){let Z=await G8($.client);if(Z!==void 0)return z8(Z);let J=await B8($.client),X=$.now();if(await $.sleep(X8),$.now()-X<X8)return{kind:"indeterminate"};let z=await G8($.client);if(z!==void 0)return z8(z);let G=await B8($.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function Z1($=process.env,Z=JB()){let J=$.XDG_DATA_HOME||J8(Z,".local","share");return J8(J,"opencode","auth.json")}function P2($){return!!$&&typeof $==="object"&&!Array.isArray($)}var Q8=($)=>$===void 0||typeof $==="string";function GB($){if(!P2($))return!1;switch($.type){case"oauth":return typeof $.refresh==="string"&&typeof $.access==="string"&&typeof $.expires==="number"&&Number.isSafeInteger($.expires)&&$.expires>=0&&Q8($.accountId)&&Q8($.enterpriseUrl);case"api":return typeof $.key==="string"&&($.metadata===void 0||P2($.metadata)&&Object.values($.metadata).every((Z)=>typeof Z==="string"));case"wellknown":return typeof $.key==="string"&&typeof $.token==="string";default:return!1}}async function P$($,Z=process.env){let J=Z.OPENCODE_AUTH_CONTENT;if(J)try{let z=JSON.parse(J);return P2(z)?z:{}}catch{}let X;try{X=JSON.parse(await ZB($,"utf8"))}catch{return{}}if(!P2(X))return{};return Object.fromEntries(Object.entries(X).filter(([,z])=>GB(z)))}function W8($){if(!$.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse($.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class J1 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function BB($){let Z=$.env??process.env,J=$.path??Z1(Z),X=new Map;return{path:XB(J),migrationDisabledReason:()=>W8(Z)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(z){let G=(await P$(J,Z))[z.path.id];return X.set(z.path.id,JSON.stringify(G)),G},async all(){return P$(J,Z)},async set(z){if(W8(Z))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let G=(await P$(J,Z))[z.path.id];if(x4(z.body)&&(!X.has(z.path.id)||X.get(z.path.id)!==JSON.stringify(G)))throw new J1;let B=await $.set(z);if(P2(B)&&"error"in B&&B.error!==void 0)throw Error(`OpenCode refused the write of its ${z.path.id} login: ${JSON.stringify(B.error)}`);return B}}}function QN($,Z={}){let J=P2($)?$.auth:void 0,X=J&&typeof J==="object"?J.set:void 0;if(typeof X!=="function")return{reason:"the OpenCode client has no auth.set to write its login slot with"};return{slot:BB({...Z,set:(z)=>X.call(J,z)})}}var c2="openai",HB="common-auth-placeholder:v1:openai",g4=Object.freeze({type:"oauth",access:"",refresh:HB,expires:0});function x4($){if(!j0($))return!1;return $.type===g4.type&&$.access===g4.access&&$.refresh===g4.refresh&&$.expires===g4.expires}var X1="openaiAuthPool",UB=120000,M8="pool-migration",qB="slot-transfer-origin-unknown",jB="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.",W1=Object.freeze({mainRefreshTtlMs:UB,fallbackTtlMs:D8,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function z1($,Z,J){return $.kind==="placeholder"&&!Z&&!J.pending}class M2 extends Error{constructor($){super(`timed out waiting for the legacy ${$} lock`);this.name="LegacyLockContention"}}function j0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function FB($){let Z=$.now??Date.now;return{paths:$.paths,slot:$.slot,now:Z,sleep:$.sleep??((J)=>new Promise((X)=>setTimeout(X,J))),newId:$.newId??(()=>crypto.randomUUID()),log:$.log??o("pool-migration"),...$.vaultServes?{vaultServes:$.vaultServes}:{},locks:{...W1,...$.legacyLocks},leaseWait:$.leaseWait??{timeoutMs:4000,pollMs:50},store:B4({provider:c2,configPath:$.paths.configPath,statePath:$.paths.statePath,quota:B1,now:Z,...$.store}),onStep:async(J)=>{await $.onStep?.(J)}}}async function a2($){let Z;try{Z=await YB($,"utf8")}catch(X){if(X.code==="ENOENT")return{};throw X}let J=JSON.parse(Z);if(!j0(J))throw Error("config root is not an object");return J}async function f4($,Z,J,X,z){let G=performance.now();for(;;){if(z?.aborted)throw new M2(Z);let B=await K0({name:Z,path:J,ttlMs:X,renew:$.locks.renew,...$.locks.renewIntervalMs!==void 0?{renewIntervalMs:$.locks.renewIntervalMs}:{}});if(B){if(!z?.aborted)return B;throw await B.release(),new M2(Z)}if(performance.now()-G>=$.locks.timeoutMs)throw new M2(Z);await $.sleep($.locks.retryMs)}}async function PN($,Z,J={}){let X={...W1,...J},z=performance.now();for(;;){let G=await K0({name:y4,path:$,ttlMs:X.mainRefreshTtlMs,renew:X.renew,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}});if(G)try{return await Z()}finally{await G.release().catch(()=>{})}if(performance.now()-z>=X.timeoutMs)throw new M2(y4);await new Promise((B)=>setTimeout(B,X.retryMs))}}async function v4($,Z){let J=$.locks.saveTtlMs,X=await f4($,"save",$.paths.configPath,J);try{let z=await f4($,"save",$.paths.statePath,J);try{let G=await a2($.paths.configPath);if(!await Z(G))return;await P0($.paths.configPath,G,{beforeRename:async()=>{await X.assertOwned(),await z.assertOwned()}})}finally{await z.release().catch(()=>{})}}finally{await X.release().catch(()=>{})}}function KB($){if(!j0($))return;let{rowId:Z,operation:J,rowFingerprint:X,slotFingerprint:z}=$,{credentialFingerprint:G,carryLegacyMain:B,recordedAt:W,identity:Q}=$;if(typeof Z!=="string"||!Z)return;if(J!=="add"&&J!=="rotate"&&J!=="replace")return;if(X!==null&&typeof X!=="string")return;if(typeof z!=="string")return;if(typeof G!=="string")return;return{rowId:Z,operation:J,rowFingerprint:X,slotFingerprint:z,credentialFingerprint:G,...typeof Q==="string"&&Q?{identity:Q}:{},carryLegacyMain:B===!0,recordedAt:typeof W==="number"?W:0}}function C8($,Z){if(!j0($)||!Z)return!1;return O0($).pending?.credentialFingerprint===D0({type:"oauth",refresh:Z})}function MN($,Z){let J;try{J=JSON.parse(WB($,"utf8"))}catch{return!1}return C8(J,Z)}class NB extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var DB=600000;async function CN($,Z,J={}){let X=J.now??Date.now,z=(Q)=>{let Y=O0(Q).pending;return Y&&C8(Q,Z)&&X()-Y.recordedAt>=DB?Y:void 0},G=z(await a2($.configPath));if(!G)return!1;let B={...W1,...J.legacyLocks},W=await K0({name:M8,path:$.configPath,ttlMs:B.mainRefreshTtlMs});if(!W)return!1;try{let Q=await a2($.configPath),Y=O0(Q).migratedAt!==void 0,V=await B4({provider:c2,configPath:$.configPath,statePath:$.statePath,quota:B1,now:X}).read();if(Y&&V.status!=="ready")return!1;let H;if(V.status==="ready"){let F=V.rows.find((j)=>j.id===G.rowId&&!j.invalid),U=F?.fingerprint??null;if(Y&&F&&U===G.credentialFingerprint)return!1;if(F&&U!==G.credentialFingerprint&&U!==G.rowFingerprint)H=J.slotAccess!==void 0?M$({type:"oauth",access:J.slotAccess,refresh:Z}):G.slotFingerprint}let q=!1;if(await v4({paths:$,locks:B,sleep:(F)=>new Promise((U)=>setTimeout(U,F))},(F)=>{let U=O0(F),j=z(F);if(!j||j.recordedAt!==G.recordedAt)return!1;let{pending:K,...N}=U;return Y1(F,H!==void 0?{...N,declinedSlotFingerprint:H}:N),q=!0,!0}),q)(J.log??o("pool-migration")).warn(H!==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:G.rowId,recordedAt:G.recordedAt});return q}finally{await W.release().catch(()=>{})}}function O0($){let Z=$[X1];if(!j0(Z))return{};let J=KB(Z.pending);return{...typeof Z.migratedAt==="number"?{migratedAt:Z.migratedAt}:{},...J?{pending:J}:{},...typeof Z.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:Z.declinedSlotFingerprint}:{}}}function Y1($,Z){let X={...j0($[X1])?$[X1]:{}};for(let z of["migratedAt","pending","declinedSlotFingerprint"])delete X[z];Object.assign(X,Z),$[X1]=X}function PB($){let Z=$?b6($):void 0;return Z?k6(Z):void 0}function MB($){let Z=M$({type:"oauth",...$}),J=PB($.access);return{kind:"real",credential:$,fingerprint:Z,credentialFingerprint:D0({type:"oauth",refresh:$.refresh}),...J?{identity:J}:{}}}function T8($){if(x4($))return{kind:"placeholder",...j0($)&&typeof $.accountId==="string"?{origin:$.accountId}:{}};let Z=V8($);if(!Z?.refresh.trim())return{kind:"empty"};return MB(Z)}async function h4($){let Z=await H8({client:{auth:{get:(J)=>$.slot.get(J),all:()=>$.slot.all()}},now:$.now,sleep:$.sleep});if(Z.kind==="real")return T8(Z.oauth);return Z.kind==="slot-absent"||Z.kind==="indeterminate"?{kind:Z.kind}:{kind:Z.kind}}async function TN($,Z){if(!x4(Z))return!1;let J=await a2($.configPath),X=await B4({provider:c2,configPath:$.configPath,statePath:$.statePath,quota:B1}).read();if(X.status==="error")return!1;let z=X.status==="ready"?X.rows.some((G)=>G.id==="main"):X.roster.some((G)=>j0(G)&&G.id==="main");return z1({kind:"placeholder"},z,O0(J))}async function CB($){let Z=$.now()+$.leaseWait.timeoutMs;for(;;){let J=await h4($);if(J.kind!=="real")return J;if(!await L8($,J.credential.refresh))return J;if($.now()>=Z)return{kind:"retry"};await $.sleep($.leaseWait.pollMs)}}async function L8($,Z){let J=await Q1($.paths),X=J?.refresh?.mainRefreshLeaseUntil;return Boolean(X&&X>$.now()&&J?.refresh?.mainRefreshLeaseTokenHash===b4(Z))}function TB($){return $.length>0&&$.trim()===$&&!["__proto__","constructor","prototype","main"].includes($)}function LB($,Z,J,X,z){let G=J.identity?{identity:J.identity}:{},B=Z.find((V)=>!V.invalid&&V.fingerprint===J.credentialFingerprint);if(B)return{rowId:B.id,operation:"rotate",rowFingerprint:B.fingerprint??null,...G,carryLegacyMain:$==="migrate"&&B.id==="main"};let W=Z.find((V)=>V.id==="main");if(!W||!W.invalid&&!W.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...G,carryLegacyMain:$==="migrate"};if(J.identity){let V=Z.find((H)=>!H.invalid&&H.type==="oauth"&&H.enabled&&H.identity===J.identity);if(V)return{rowId:V.id,operation:"replace",rowFingerprint:V.fingerprint??null,...G,carryLegacyMain:$==="migrate"&&V.id==="main"}}let Q=new Set(Z.map((V)=>V.id));return{rowId:X??(J.identity&&TB(J.identity)&&!Q.has(J.identity)?J.identity:z()),operation:"add",rowFingerprint:null,...G,carryLegacyMain:!1}}function _B($,Z,J,X,z,G,B){let W=Z.pending;if(W){let Q=J.find((H)=>H.id===W.rowId&&!H.invalid),Y=Q?.fingerprint??null,V=X.kind==="real"&&X.fingerprint===W.slotFingerprint;if(Q&&Y===W.credentialFingerprint)return{kind:"finish",record:W};if((Q||W.rowFingerprint===null)&&Y===W.rowFingerprint)return V&&X.kind==="real"?{kind:"transfer",record:W,credential:X.credential,fresh:!1}:{kind:"drop-record"};if(!Q)return{kind:"drop-record"};return V?{kind:"ambiguous",record:W}:{kind:"drop-record"}}if(X.kind==="indeterminate")return{kind:"drop-record"};if(X.kind!=="real")return{kind:"nothing",slot:X.kind};if(Z.declinedSlotFingerprint===X.fingerprint)return{kind:"nothing",slot:"declined"};return{kind:"transfer",record:{...LB($,J,X,z,B),slotFingerprint:X.fingerprint,credentialFingerprint:X.credentialFingerprint,recordedAt:G},credential:X.credential,fresh:!0}}async function OB($,Z,J){let X={type:"oauth",access:J.access,refresh:J.refresh,...J.expires!==void 0?{expires:J.expires}:{}},z=Z.identity?{identity:Z.identity}:{},G={extraLocks:G1($.paths,Z.rowId,$.locks)};if(Z.operation==="add")await $.store.add({id:Z.rowId,credential:X,...z},G);else if(Z.operation==="replace")await $.store.replace(Z.rowId,X,z,G);else{let B=await $.store.read(),W=B.status==="ready"?B.rows.find((Q)=>Q.id===Z.rowId):void 0;await $.store.rotate(Z.rowId,X,W?.identity===void 0?z:{},G)}}async function SB($,Z){let J=await $.store.read();if(J.status!=="ready")return;let X=J.rows.find((z)=>z.id===Z.rowId&&!z.invalid);return X?.fingerprint===Z.credentialFingerprint?X:void 0}function AB($,Z){let J=[],X=[["primary",$.primary],["secondary",$.secondary]],z=0;for(let[W,Q]of X){if(!Q||!Number.isFinite(Q.checkedAt)||!Number.isFinite(Q.usedPercent))continue;z=Math.max(z,Q.checkedAt),J.push({checkedAt:Q.checkedAt,readings:[{label:W,usedPercent:Q.usedPercent,...typeof Q.resetsAt==="string"?{resetsAt:Q.resetsAt}:{},...Number.isFinite(Q.windowMinutes)?{windowMinutes:Q.windowMinutes}:{}}]})}let G=Z??(z||void 0),B=$.spendControl;if(G!==void 0&&B)J.push({checkedAt:G,budget:{kind:"reading",reached:B.reached,remainingPercent:B.remainingPercent,usedPercent:B.usedPercent,limit:B.limit,used:B.used,remaining:B.remaining,...B.resetsAt!==void 0?{resetsAt:B.resetsAt}:{},...B.unit!==void 0?{unit:B.unit}:{}}});else if(G!==void 0&&$.spendControlCleared)J.push({checkedAt:G,budget:{kind:"cleared"}});return J.sort((W,Q)=>W.checkedAt-Q.checkedAt)}async function EB($,Z){let J=await Q1($.paths);if(!J)return;let X=J.quota?.mainQuotaToken,z=Z.credential?.type==="oauth"?Z.credential.access:void 0,B=!X||z!==void 0&&X===F8(z)?J.quota?.mainQuota:void 0;if(B&&Z.credentialEpoch!==void 0){let V={credentialEpoch:Z.credentialEpoch,...Z.identity!==void 0?{identity:Z.identity}:{}};for(let H of AB(B,J.quota?.mainQuotaCheckedAt))try{await $.store.recordQuota(Z.id,V,H)}catch(q){$.log.warn("legacy main quota not carried to the pool row",{rowId:Z.id,error:q instanceof Error?q.message:String(q)})}}let W=J.refresh?.mainLastRefreshError,Q=J.accounts.find((V)=>V.id===Z.id);if(!Q||!K8(Q)||Q.corrupt)return;if(!W&&!B)return;let Y={...J,accounts:[{...Q,...Q.lastRefreshError||!W?{}:{lastRefreshError:W},...Q.quota||!B?{}:{quota:B}}]};try{await N8(Y,$.paths,{accounts:[Z.id]})}catch(V){$.log.warn("legacy main backoff not carried to the pool row",{rowId:Z.id,error:V instanceof Error?V.message:String(V)})}}async function s2($,Z,J={}){await v4($,(X)=>{let z=O0(X);if(delete X.mainAccountId,Z==="migrate"&&z.migratedAt===void 0)RB(X);return Y1(X,{...z.migratedAt!==void 0||Z==="migrate"?{migratedAt:z.migratedAt??$.now()}:{},...J.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:J.declinedSlotFingerprint}:z.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:z.declinedSlotFingerprint}:{}}),!0})}function RB($){let Z=$.routing;if(Z===void 0)$.routing={mode:"main-first"};else if(j0(Z)&&Z.mode===void 0)$.routing={...Z,mode:"main-first"}}async function T$($){await v4($,(Z)=>{let J=O0(Z);if(!J.pending)return!1;let{pending:X,...z}=J;return Y1(Z,z),!0})}async function IB($,Z){await v4($,(J)=>{let X=O0(J);if(Z.identity)J.mainAccountId=Z.identity;return Y1(J,{...X,pending:Z}),!0})}async function bB($,Z,J,X){let z=await f4($,y4,$.paths.configPath,$.locks.mainRefreshTtlMs);try{return await kB($,Z,J,X)}finally{await z.release().catch(()=>{})}}async function kB($,Z,J,X){let z=(Y)=>({status:"completed",rowId:J.rowId,operation:X,placeholder:Y}),G=await h4($);if(G.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(G.kind==="placeholder"){if(G.origin===void 0)return{status:"untagged-placeholder"};if(G.origin!==C$($))return{status:"foreign-placeholder"};return await s2($,Z),await $.onStep("after-record-clear"),z("already-present")}if(Object.keys(await $.slot.all()).length===0)return{status:"retry",reason:"torn-read"};if(G.kind==="real"&&G.fingerprint!==J.slotFingerprint&&J.identity!==void 0&&G.identity===J.identity)return await T$($),await $.onStep("after-record-clear"),{status:"restart"};if(G.kind!=="real"||G.fingerprint!==J.slotFingerprint)return await s2($,Z),await $.onStep("after-record-clear"),z("slot-moved-on");await $.onStep("before-placeholder-write");let B=await $.slot.get({path:{id:c2}}),W=B===void 0||B===null?void 0:T8(B);if(W?.kind!=="real"||W.fingerprint!==J.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await $.slot.set({path:{id:c2},body:{...g4,accountId:C$($)}})}catch(Y){if(Y instanceof J1)return{status:"retry",reason:"slot-changed"};throw Y}await $.onStep("after-placeholder-write");let Q=await $.slot.get({path:{id:c2}});if(!x4(Q))return{status:"retry",reason:"placeholder-overwritten"};if(j0(Q)&&Q.accountId===void 0)return{status:"untagged-placeholder"};if(j0(Q)&&Q.accountId!==C$($))return{status:"foreign-placeholder"};return await s2($,Z),await $.onStep("after-record-clear"),z("written")}async function xB($,Z,J){let{record:X}=J;if(J.fresh)await IB($,X),await $.onStep("after-record-write");if(await L8($,J.credential.refresh))return{status:"restart"};let z=await h4($);if(z.kind!=="real"||z.fingerprint!==X.slotFingerprint)return{status:"restart"};return await OB($,X,J.credential),await $.onStep("after-row-write"),_8($,Z,X,J.fresh?X.operation:"resumed")}async function _8($,Z,J,X){let z=await SB($,J);if(!z)return{status:"retry",reason:"verify-failed"};if(await $.onStep("after-verify"),J.carryLegacyMain)await EB($,z),await $.onStep("after-carry-over");let G=await bB($,Z,J,X);if(G.status==="untagged-placeholder"){await $.store.disable(J.rowId,qB,{extraLocks:G1($.paths,J.rowId,$.locks),attribution:{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}}}),await s2($,Z);let B=`${$.paths.configPath}\x00${J.rowId}`;if(!j8.has(B))j8.add(B),$.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${jB}`,{rowId:J.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(G.status!=="foreign-placeholder")return G;return await $.store.remove(J.rowId,{extraLocks:G1($.paths,J.rowId,$.locks),protect:(B,W)=>W.row?.fingerprint!==J.credentialFingerprint?"the transfer row changed before rollback":void 0}),await T$($),await L$($),{status:"refused",reason:"placeholder-without-main"}}var U8=new Set,q8=new Set,j8=new Set;function C$($){return`openai-auth-pool:${QB("sha256").update(VB($.paths.configPath)).digest("hex")}`}async function yB($){try{let Z=await $();return Z.open?[]:Z.blockers}catch(Z){return[{pid:"unknown",version:"unknown",detail:Z instanceof Error?Z.message:String(Z)}]}}async function O8($,Z,J){let X=FB($),z=X.slot.migrationDisabledReason?.();if(z){let Y=X.slot.path??Z1();if(!q8.has(Y))q8.add(Y),X.log.info("account pool migration is off: the host login slot is read-only",{reason:z});return{status:"slot-read-only",reason:z}}let G;try{G=await a2(X.paths.configPath)}catch(Y){return{status:"error",reason:Y instanceof Error?Y.message:String(Y)}}let B=await S8(X,Z,G);if(B){if(B.status==="already-migrated"&&"mainAccountId"in G)await L$(X);return B}if(J){let Y=await yB(J);if(Y.length>0){let V=`${X.paths.configPath}\x00${Y.map((H)=>`${H.pid}@${H.version}`).join(",")}`;if(!U8.has(V))U8.add(V),X.log.info("account pool migration deferred: an older openai-auth version is running",{blockers:Y});return{status:"deferred",reason:"older-version-running",blockers:Y}}}let W,Q;try{Q=await f4(X,"pool-slot-transfer",X.slot.path??Z1(),X.locks.mainRefreshTtlMs,$.signal),W=await f4(X,M8,X.paths.configPath,X.locks.mainRefreshTtlMs,$.signal)}catch(Y){if(await Q?.release().catch(()=>{}),Y instanceof M2)return{status:"retry",reason:"lock-contention"};throw Y}try{return await gB(X,Z)}catch(Y){if(Y instanceof M2)return{status:"retry",reason:"lock-contention"};if(Y instanceof b)return{status:"retry",reason:Y.kind==="lock-contention"?"lock-contention":`store-${Y.kind}`};throw Y}finally{await W?.release().catch(()=>{}),await Q?.release().catch(()=>{})}}async function S8($,Z,J){let X=O0(J);if(X.pending)return;if(Z==="migrate"&&X.migratedAt!==void 0){let z=await $.store.read();if(z.status==="ready"&&!z.rows.some((G)=>G.id==="main")&&!X.pending&&z1(await h4($),z.rows.some((G)=>G.id==="main"),X))return{status:"refused",reason:"placeholder-without-main"};return{status:"already-migrated"}}if(Z==="adopt"&&X.migratedAt===void 0)return{status:"not-migrated"};return}async function gB($,Z){let J;for(let X=0;X<4;X++){let z=await a2($.paths.configPath),G=await S8($,Z,z);if(G){if(G.status==="already-migrated")await L$($);return G}let B=await $.store.read(),W=O0(z);if(B.status==="pending-migration"){if(z1(await h4($),B.roster.some((H)=>j0(H)&&H.id==="main"),W))return{status:"refused",reason:"placeholder-without-main"};await $.store.initialize(),await $.onStep("after-pool-key-write"),B=await $.store.read()}if(B.status!=="ready")return{status:"error",reason:B.status==="error"?`${B.file}: ${B.reason}`:"pool still pending migration"};let Q=await CB($);if(Q.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(Q.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(z1(Q,B.rows.some((H)=>H.id==="main"),W))return{status:"refused",reason:"placeholder-without-main"};let Y=_B(Z,W,B.rows,Q,J,$.now(),$.newId);if(Y.kind==="nothing"){if(Z==="migrate")await s2($,Z),await $.onStep("after-marker-write");return{status:"nothing-to-import",slot:Y.slot}}if(Y.kind==="drop-record"){await T$($),await $.onStep("after-record-clear");continue}if(Y.kind==="ambiguous")return await s2($,Z,{declinedSlotFingerprint:Y.record.slotFingerprint}),await $.onStep("after-record-clear"),$.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:Y.record.rowId}),{status:"ambiguous",rowId:Y.record.rowId};if(Y.kind==="transfer"&&Y.fresh)J=Y.record.rowId;let V=Y.kind==="finish"?await _8($,Z,Y.record,"resumed"):await xB($,Z,Y);if(V.status!=="restart")return V}return{status:"retry",reason:"unsettled"}}async function L$($){await v4($,(Z)=>{if(!("mainAccountId"in Z))return!1;if(O0(Z).pending)return!1;return delete Z.mainAccountId,!0})}function LN($){return O8($,"migrate",$.fence)}function _N($){return O8($,"adopt")}class A8 extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function G1($,Z,J={}){let X={...W1,...J},z={renew:X.renew,timeoutMs:X.timeoutMs,retryMs:X.retryMs,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}};return[{name:y4,path:$.configPath,ttlMs:X.mainRefreshTtlMs,...z},{name:P8(Z),path:$.configPath,ttlMs:X.fallbackTtlMs,...z}]}async function ON($,Z,J,X={}){let z=$.now??Date.now,G=$.sleep??((Q)=>new Promise((Y)=>setTimeout(Y,Q))),B=$.leaseWait??{timeoutMs:4000,pollMs:50},W=async(Q,Y)=>{let V=b4(Q.refresh),H=async()=>{let q=await Q1($.paths),F=q?.refresh?.mainRefreshLeaseUntil;return Boolean(F&&F>z()&&q?.refresh?.mainRefreshLeaseTokenHash===V)};if(await H()){let q=z()+B.timeoutMs;while(z()<q&&await H())await G(B.pollMs);throw new A8}return J(Q,Y)};return $.store.refresh(Z,W,{...X,extraLocks:G1($.paths,Z,$.legacyLocks)})}function E8(){let $=crypto.getRandomValues(new Uint8Array(16)),Z=Date.now();$[0]=Z/1099511627776&255,$[1]=Z/4294967296&255,$[2]=Z/16777216&255,$[3]=Z/65536&255,$[4]=Z/256&255,$[5]=Z&255,$[6]=($[6]??0)&15|112,$[8]=($[8]??0)&63|128;let J=Array.from($,(X)=>X.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}import{chmodSync as fB,mkdirSync as R8,readFileSync as vB,renameSync as hB,writeFileSync as mB}from"node:fs";import{dirname as I8}from"node:path";var _$="sessions",wB=1e4,uB=5000,pB=25;async function lB($,Z=uB){let J=performance.now()+Z;for(;;){let X=await K0({name:_$,path:$,ttlMs:wB});if(X||performance.now()>=J)return X;await new Promise((z)=>setTimeout(z,pB))}}function dB($){let Z=new Map,J=JSON.parse(vB($,"utf8"));if(!E(J.sessions))return Z;for(let[X,z]of Object.entries(J.sessions)){if(!E(z)||typeof z.threadID!=="string")continue;Z.set(X,z.threadID)}return Z}function xN($,Z=E8){let J=new Map,X;try{X=dB($)}catch{return J}for(let[z,G]of X)J.set(z,{threadID:G,turnID:Z(),windowID:`${G}:0`});return J}function cB($,Z){let J=`${$}.tmp-${process.pid}`;R8(I8($),{recursive:!0});let X={version:1,sessions:Object.fromEntries([...Z].map(([z,G])=>[z,{threadID:G}]))};mB(J,`${JSON.stringify(X,null,2)}
|
|
71
|
+
`,{encoding:"utf8",mode:384}),fB(J,384),hB(J,$)}var m4=new Map;function yN($){return m4.get($)??Promise.resolve()}function gN($,Z){let X=(m4.get($)??Promise.resolve()).then(async()=>{let z=null;try{if(R8(I8($),{recursive:!0}),z=await lB($),!z)return;cB($,[...Z.entries()].map(([G,B])=>[G,B.threadID]))}catch{}finally{await z?.release().catch(()=>{})}});return m4.set($,X),X.then(()=>{if(m4.get($)===X)m4.delete($)}),X}import{randomUUID as sB}from"node:crypto";import{chmod as aB,mkdir as nB,rename as iB,rm as O$,writeFile as rB}from"node:fs/promises";import{homedir as oB}from"node:os";import{join as H1}from"node:path";function S$(){let $=process.env.XDG_STATE_HOME||H1(oB(),".local","state");return H1($,"cortexkit","openai-auth","processes")}function b8($=process.pid,Z=S$()){return H1(Z,`${$}.json`)}var V1=0,U1,k8=Symbol.for("@cortexkit/openai-auth/process-layouts"),x8=globalThis,q1=x8[k8]??new Map;x8[k8]=q1;function y8(){return{...Object.fromEntries(q1),...J0()?{"*":"legacy"}:{}}}function tB(){if(J0())return!0;for(let $ of q1.values())if($==="legacy")return!0;return!1}async function g8($,Z){await nB($,{recursive:!0,mode:448}),await aB($,448);let J=b8(Z.pid,$),X=H1($,`0${Z.pid}.json`),z=J0()?[X,J]:[J];if(!J0())await O$(X,{force:!0}).catch(()=>{});for(let G of z){let B=`${G}.${sB()}.tmp`;try{await rB(B,`${JSON.stringify(Z)}
|
|
72
|
+
`,{mode:384}),await iB(B,G)}catch(W){throw await O$(B,{force:!0}).catch(()=>{}),W}}return J}async function pN($){let Z=$.pid??process.pid,J=$.dir??S$();U1??=($.now??Date.now)(),V1++;let X;try{X=await g8(J,{pid:Z,version:$.version,startedAt:U1,layouts:y8()})}catch(G){$.logger.warn("process heartbeat not written",{dir:J,error:G instanceof Error?G.message:String(G)})}let z=!1;return{path:X,async release(){if(z)return;if(z=!0,V1=Math.max(0,V1-1),V1>0)return;if(tB())return;await O$(b8(Z,J),{force:!0}).catch((G)=>{$.logger.warn("process heartbeat not removed",{dir:J,error:G instanceof Error?G.message:String(G)})})}}}async function j1($){let Z=J0()?"legacy":$.layout;if(q1.set($.key,Z),Z!=="legacy")return;U1??=($.now??Date.now)(),await g8($.dir??S$(),{pid:$.pid??process.pid,version:$.version,startedAt:U1,layouts:y8()})}import{createHash as eB}from"node:crypto";import{realpathSync as $Q}from"node:fs";import{chmod as ZQ,mkdir as JQ,readdir as d8,readFile as S0,rmdir as c8,stat as s8,unlink as p4}from"node:fs/promises";import{basename as E$,dirname as N1,isAbsolute as XQ,join as m,relative as zQ,resolve as D1}from"node:path";var GQ="runtime-layout",n2="layout-moving.json",a8=1e4,F1=15000,BQ=4*F1+a8,QQ=50,WQ=5,YQ=50,VQ=[0,10,20,40,80,100],f8=500,HQ="openai-auth keeps its files in OpenCode's config folder until every running OpenCode using it has restarted on this version.",v8="openai-auth found runtime files in OpenCode's config folder again (an older version may have run). It does not use them and leaves them in place; its files are in its state folder.";class X0 extends Error{stateDir;errorClass;constructor($,Z,J=UQ($,Z)){super(J);this.stateDir=$;this.errorClass=Z;this.name="RuntimeLayoutRefusal"}}function UQ($,Z){if(Z==="ERR_PRIVATE_FILES_SECURITY")return`openai-auth cannot start: ${$} is not a folder only your user can access, or it is a link, so the plugin will not use it (${Z}). Replace it with a plain folder of your own, then restart OpenCode.`;return`openai-auth cannot start: it could not settle where its runtime files live in ${$} (${Z}). Check that this folder can be created and written by your user, then restart OpenCode.`}function h8($,Z){return new X0($,"foreign-folder",`openai-auth cannot start: ${$} belongs to another OpenCode config folder, not ${Z}. It was left untouched. Move it aside, then restart OpenCode.`)}function P1($,Z){return new X0($,"credential-conflict",`openai-auth cannot start: runtime credentials conflict between ${Z.old} and ${Z.next}. Keep the newer one, delete the other, then restart OpenCode.`)}function XD(){let $=l0.notice;if(!$||$.shown)return;return $.shown=!0,$.text}function g0($,Z){if(l0.logged.has($))return;l0.logged.add($),Z()}function d0($){if($ instanceof X0)return $.errorClass;let Z=$?.code;if(typeof Z==="string"&&Z)return Z;return $ instanceof Error?$.name:typeof $}function qQ($){let{path:Z,stage:J}=$??{};return{...typeof Z==="string"&&Z?{file:E$(Z)}:{},...typeof J==="string"&&J?{stage:J}:{}}}class u4 extends Error{code;constructor($,Z){super(Z);this.code=$;this.name="LayoutMoveError"}}class R$ extends u4{path;constructor($){super("old-credential-kept",`${$} could not be removed`);this.path=$}}function n8($,Z,J,X){g0(`${$.key}\x00cleanup`,()=>Z.warn("openai-auth could not finish removing its old files from OpenCode's config folder; it tries again at the next start",{configDir:$.configDir,step:J,errorClass:d0(X),...qQ(X)}))}function zD($){let Z=t6(),J=$1(Z);if(J)return Promise.resolve(J);let X=`${Z.stateHomeDir}\x00${Z.key}`,z=l0.runs.get(X);if(!z)z=jQ(Z,$).catch((G)=>{if(G instanceof X0)throw G;throw new X0(Z.stateHomeDir,d0(G))}).finally(()=>{l0.runs.delete(X)}),l0.runs.set(X,z);return z}async function jQ($,Z){let J=Z.log??o("runtime-layout");if(J0()){e6($,"legacy"),g0("legacy-generation",()=>J.info("openai-auth keeps its runtime files in OpenCode's config folder until restart: an older plugin version ran in this process"));try{await j1({key:$.key,layout:"legacy",version:Z.version})}catch(K){J.warn("process heartbeat not written",{errorClass:d0(K)})}return"legacy"}let X=$.stateHomeDir,z=m(X,n6),G=b$($),B=KQ(),W=B.length>0,Q=B.some((K)=>i8(K,X)),Y=Z.fence??FQ(Z.version),V=async()=>{return await j1({key:$.key,layout:"state-home",version:Z.version}),e6($,"state-home"),"state-home"},H=await w4(z,X);if(await l8($,H),H?.oldFilesRemoved&&!Q){await bQ($,G,B,H,J);let K=await F0(m(X,n2)).catch(()=>!0),N=!W&&(await $J(G).catch(()=>[!0])).length>0;if(!K&&!N)return V()}let q=await zJ($.configDir,X),F;try{if(!q)await BJ(X);F=await K1(GQ,z,Z.layoutLockWaitMs??BQ)}catch(K){if(H=await w4(z,X),H&&!Q)return V();throw new X0(X,d0(K))}let U=F,j=async()=>{try{await U.assertOwned(),await j1({key:$.key,layout:"legacy",version:Z.version})}catch(K){throw new X0(X,d0(K))}return e6($,"legacy"),"legacy"};try{if(H=await w4(z,X),await l8($,H),!q)await kQ($);if(Q)return g0(`${$.key}\x00override`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: a path set by OPENCODE_OPENAI_AUTH_STATE_FILE or OPENCODE_OPENAI_AUTH_FILE is inside its state folder, which it never touches",{stateDir:X,overrides:B})),await j();if(H){if(!W&&!q)await DQ($,G,z,H,U,{fence:Y,log:J,steps:Z.steps});else if(H.oldFilesRemoved)await PQ($,U,Z.steps,J);return await V()}if(W)return await j();if(q)return g0(`${$.key}\x00aliased`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: its state folder is that same folder",{configDir:$.configDir,stateDir:X})),await j();let K=await Y();if(!K.open)return m8($,K.blockers,J),await j();let N=!1;try{let D=await NQ($,G,z,U,{fence:Y,log:J,steps:Z.steps,onMarker:()=>{N=!0}});if(D.kind==="deferred")return m8($,D.blockers,J),await j();if(D.kind==="refused")return g0(`${$.key}\x00refused`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: it will not move them",{reason:D.reason,paths:D.paths,stateDir:X})),await j();if(D.moved)J.info("openai-auth moved its runtime files out of OpenCode's config folder",{from:$.configDir,to:X});return await V()}catch(D){if(D instanceof X0)throw D;if(N&&await w4(z,X))return await V();return g0(`${$.key}\x00failed`,()=>J.warn("openai-auth's runtime files stay in OpenCode's config folder: moving them failed; the move is tried again at the next start",{configDir:$.configDir,errorClass:d0(D)})),await j()}}finally{await U.release().catch(()=>{})}}function FQ($){return()=>c7({currentVersion:$,layoutMove:!0})}function m8($,Z,J){g0(`${$.key}\x00deferred`,()=>J.info(HQ,{configDir:$.configDir,blockers:Z}))}function KQ(){let $=$8();if($===void 0)return[];let Z=Z8();return[$,x6($),...Z?[Z]:[]]}function i8($,Z){let J=zQ(w8(Z),w8($));if(J==="")return!0;if(!J.startsWith("..")&&!XQ(J))return!0;return o6($,Z)}function w8($){let Z=D1($),J=[];for(;;){try{return m($Q.native(Z),...J)}catch{}let X=N1(Z);if(X===Z)return D1($);J.unshift(E$(Z)),Z=X}}async function NQ($,Z,J,X,z){let G=$.stateHomeDir,B=await o8($,Z),W=!1;try{let Q=await z.fence();if(!Q.open)return{kind:"deferred",blockers:Q.blockers};let Y=await XJ($,Z);if(Y.length>0)return{kind:"refused",reason:"same-physical-file",paths:Y};let V=await xQ(G),H=(await SQ(Z)).filter((K)=>!V.has(K));if(H.length>0)return{kind:"refused",reason:"destination-in-use",paths:H};let q=await JJ(Z);await X.assertOwned(),await yQ(G,[...new Set([...V,...q.map((K)=>K.next)])]);let F=new Set(q.map((K)=>K.next));for(let K of V){if(F.has(K))continue;await X.assertOwned(),await p4(K).catch((N)=>{if(N.code!=="ENOENT")throw N})}for(let K of q)await X.assertOwned(),await AQ(K);await z.steps?.afterCopy?.(),await X.assertOwned();for(let K of B)await K.assertOwned();let U=await TQ(Z,q),j={version:1,oldDir:$.key,...U?{keptVaultState:U}:{}};z.onMarker(),await A$(J,j),await z.steps?.afterMarker?.(),await X.assertOwned();try{await GJ($,q,X,{log:z.log,keptVaultState:U,steps:z.steps}),await ZJ(Z,X,B,z.steps)}catch(K){if(!(K instanceof R$))throw K;return n8($,z.log,"remove-old-copies",K),{kind:"moved",moved:q.length>0}}return W=!0,await X.assertOwned(),await A$(J,{...j,oldFilesRemoved:!0}),await I$(G,X,z.steps),{kind:"moved",moved:q.length>0}}finally{for(let Q of B.reverse())await Q.release().catch(()=>{});if(W)await r8(Z,X,z.steps)}}async function DQ($,Z,J,X,z,G){let B=[],W=!1,Q="fence";try{if(!(await G.fence()).open)return;if(Q="data-locks",B=await o8($,Z),Q="fence",!(await G.fence()).open)return;Q="same-file-check";let Y=await XJ($,Z);if(Y.length>0){g0(`${$.key}\x00cleanup-aliased`,()=>G.log.warn("openai-auth leaves its old files in OpenCode's config folder: they are the same files as its new ones",{paths:Y}));return}if(Q="remove-old-copies",await z.assertOwned(),!X.oldFilesRemoved)await GJ($,await JJ(Z),z,{log:G.log,keptVaultState:X.keptVaultState,steps:G.steps});Q="remove-old-temps",await ZJ(Z,z,B,G.steps),W=!0,Q="marker",await z.assertOwned(),await A$(J,{...X,oldFilesRemoved:!0}),Q="manifest",await I$($.stateHomeDir,z,G.steps)}catch(Y){if(Y instanceof X0)throw Y;n8($,G.log,Q,Y)}finally{for(let Y of B.reverse())await Y.release().catch(()=>{});if(W)await r8(Z,z,G.steps)}}async function PQ($,Z,J,X){try{await I$($.stateHomeDir,Z,J)}catch(z){g0(`${$.key}\x00manifest`,()=>X.warn(`openai-auth could not remove ${n2} from its state folder; it tries again at the next start`,{stateDir:$.stateHomeDir,errorClass:d0(z)}))}}async function I$($,Z,J){let X=m($,n2);if(!await F0(X))return;await J?.beforeRemove?.(X),await Z.assertOwned(),await gQ($)}async function r8($,Z,J){try{await J?.beforeRemove?.($.vault.old),await Z.assertOwned(),await c8($.vault.old)}catch{}}async function o8($,Z){let J=[];try{if(await F0($.configDir)){if(J.push(await K1("save",Z.state.old,F1)),await F0(Z.vault.old))J.push(await K1("claustrum-roster-write",j2(Z.vault.old,"opencode").rosterPath,F1));for(let X of Z.sessions)J.push(await K1(_$,X.old,F1))}return J}catch(X){for(let z of J.reverse())await z.release().catch(()=>{});throw X}}function b$($){let Z=m($.configDir,k4),J=m($.stateHomeDir,k4);return{state:{old:Z,next:J},vault:{old:x6(Z),next:x6(J)},sessions:[j$,F$].map((X)=>({old:m($.configDir,X),next:m($.stateHomeDir,X)}))}}var MQ=/^[0-9a-f]{64}$/;function t8($){return eB("sha256").update($).digest("hex")}function M1($){return{old:j2($.vault.old,"opencode").statePath,next:j2($.vault.next,"opencode").statePath}}var u8=M9("opencode"),CQ="opencode-enrollment-no-token.json";async function e8($){try{let Z=await R6($,u8);return Z.state==="blocked"&&Z.code==="missing_token"&&Z.proposedName===u8}catch{return!1}}async function TQ($,Z){let J=M1($);if(!Z.some((z)=>z.old===J.old))return;return await e8({statePath:J.next,tokenPath:m($.vault.next,CQ)})?t8(await S0(J.next)):void 0}async function LQ($,Z){if(!Z)return!1;try{return t8(await S0($))===Z}catch{return!1}}async function k$($,Z){if(!Z)return!1;let J=j2($.vault.old,"opencode");if(await LQ(J.statePath,Z))return!0;return e8(J)}async function GD($){let Z=t6(),J=b$(Z);if(D1($)!==D1(J.vault.next))return;let X=Z.stateHomeDir,z=await w4(m(X,n6),X);if(!z?.keptVaultState||z.oldDir!==Z.key)return;let G=M1(J).old;if(!await k$(J,z.keptVaultState))return;await p4(G).catch((B)=>{if(B.code!=="ENOENT")throw B}),await c8(J.vault.old).catch(()=>{})}function _Q($){return $.includes(".lock")||$.includes(".tmp")}var OQ=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/;async function $J($){let Z=j2($.vault.old,"opencode"),J=[$.state.old,...$.sessions.map((z)=>z.old),Z.rosterPath,Z.statePath,Z.tokenPath],X=[];for(let z of new Set(J.map(N1))){let G;try{G=await d8(z,{withFileTypes:!0})}catch(W){if(W.code==="ENOENT")continue;throw W}let B=J.filter((W)=>N1(W)===z).map((W)=>`${E$(W)}.`);for(let W of G)if(W.isFile()&&B.some((Q)=>W.name.startsWith(Q)&&OQ.test(W.name.slice(Q.length))))X.push(m(z,W.name))}return X}async function ZJ($,Z,J,X){for(let z of await $J($)){await X?.beforeRemove?.(z),await Z.assertOwned();for(let G of J)await G.assertOwned();await p4(z).catch((G)=>{if(G.code!=="ENOENT")throw G})}}async function C1($){let Z;try{Z=await d8($,{withFileTypes:!0})}catch(J){let X=J.code;if(X==="ENOENT"||X==="ENOTDIR")return[];throw J}return Z.filter((J)=>J.isFile()&&!_Q(J.name)).map((J)=>J.name).sort()}async function JJ($){let Z=[];if(await F0($.state.old))Z.push($.state);for(let J of await C1($.vault.old))Z.push({old:m($.vault.old,J),next:m($.vault.next,J)});for(let J of $.sessions)if(await F0(J.old))Z.push(J);return Z}async function SQ($){let Z=[];if(await F0($.state.next))Z.push($.state.next);for(let J of await C1($.vault.next))Z.push(m($.vault.next,J));for(let J of $.sessions)if(await F0(J.next))Z.push(J.next);return Z}async function XJ($,Z){let J=[[$.configDir,$.stateHomeDir],[Z.vault.old,Z.vault.next],[Z.state.old,Z.state.next],...Z.sessions.map((z)=>[z.old,z.next])];for(let z of await C1(Z.vault.old))J.push([m(Z.vault.old,z),m(Z.vault.next,z)]);let X=[];for(let[z,G]of J)if(await zJ(z,G))X.push(z);return X}async function zJ($,Z){let J=async(z)=>{try{let G=await s8(z,{bigint:!0});return G.ino===0n?void 0:`${G.dev}:${G.ino}`}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;throw G}},X=await J($);return X!==void 0&&X===await J(Z)}async function AQ($){let Z=await S0($.old),J=Z.toString("utf8");if(!Buffer.from(J,"utf8").equals(Z))throw new u4("not-utf8",`${$.old} is not UTF-8 text`);if(await T1($.next,J),!(await S0($.next)).equals(Z))throw new u4("copy-mismatch",`${$.next} does not match ${$.old}`)}async function GJ($,Z,J,X){let z=[],G=[],B=b$($),W=M1(B).old,Q=[...Z.filter((V)=>V.old!==W),...Z.filter((V)=>V.old===W)];for(let V of Q){if(await J.assertOwned(),V.old===W){if(await k$(B,X.keptVaultState))continue;if(G.length>0)continue;if(X.keptVaultState&&await EQ(V.old,V.next))continue}let H=V.old===B.state.old||i8(V.old,B.vault.old);if(!await IQ(V,$.stateHomeDir,H,()=>RQ(V.old,J,X.steps)))(H?G:z).push(V.old)}if(z.length>0)X.log.warn("openai-auth left old files in OpenCode's config folder; it no longer reads them",{configDir:$.configDir,kept:z});let[Y]=G;if(Y!==void 0)throw new R$(Y)}async function EQ($,Z){try{return(await S0($)).equals(await S0(Z))}catch{return!1}}async function RQ($,Z,J){await J?.beforeRemove?.($),await Z.assertOwned()}function p8($){let Z=$?.code;return process.platform==="win32"&&(Z==="EBUSY"||Z==="EPERM"||Z==="EACCES")}async function IQ($,Z,J,X){let z=performance.now();for(let G of VQ){if(G>0)await new Promise((W)=>setTimeout(W,G));let B;try{B=(await S0($.old)).equals(await S0($.next))}catch(W){if(W.code==="ENOENT"&&!await F0($.old))return!0;if(p8(W)){if(performance.now()-z>=f8)return!1;continue}if(J)throw P1(Z,$);return!1}if(!B){if(J)throw P1(Z,$);return!1}await X();try{return await p4($.old),!0}catch(W){if(W.code==="ENOENT")return!0;if(!p8(W)||performance.now()-z>=f8)return!1}}return!1}async function bQ($,Z,J,X,z){let G=(W)=>J.some((Q)=>o6(Q,W));if(!G(Z.state.old)&&await F0(Z.state.old))throw P1($.stateHomeDir,Z.state);if(!G(Z.vault.old)){let W=M1(Z).old;for(let Q of await C1(Z.vault.old)){let Y=m(Z.vault.old,Q);if(Y===W&&await k$(Z,X.keptVaultState))continue;if(!G(Y))throw P1($.stateHomeDir,{old:Y,next:m(Z.vault.next,Q)})}}let B=[];try{for(let W of Z.sessions)if(await F0(W.old))B.push(W.old)}catch{}if(B.length===0)return;g0(`${$.key}\x00reappeared`,()=>{l0.notice={text:`${v8} Old folder: ${$.configDir}`,shown:!1},z.warn(v8,{configDir:$.configDir,stateDir:$.stateHomeDir,found:B})})}async function w4($,Z){let J,X;for(let z=0;z<WQ;z++){if(z>0)await new Promise((G)=>setTimeout(G,YQ));try{J=await S0($,"utf8");break}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;X=G}}if(J===void 0)throw new X0(Z,d0(X));try{let z=JSON.parse(J);if(z&&typeof z==="object"&&!Array.isArray(z))return{version:1,...typeof z.oldDir==="string"?{oldDir:z.oldDir}:{},...z.oldFilesRemoved===!0?{oldFilesRemoved:!0}:{},...typeof z.keptVaultState==="string"&&MQ.test(z.keptVaultState)?{keptVaultState:z.keptVaultState}:{}}}catch{}throw new X0(Z,"malformed-marker",`openai-auth cannot start: ${$} is malformed. The old files are still in OpenCode's config folder. Delete layout.json, then restart OpenCode.`)}async function l8($,Z){let J=$.stateHomeDir;if(Z?.oldDir!==void 0&&Z.oldDir!==$.key)throw h8(J,$.key);let X;try{X=await S0(m(J,K$),"utf8")}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;throw new X0(J,d0(G))}let z;try{z=JSON.parse(X)?.configDir}catch{}if(z!==$.key)throw h8(J,$.key)}async function kQ($){let Z=m($.stateHomeDir,K$);if(await F0(Z))return;await T1(Z,`${JSON.stringify({version:1,configDir:$.key},null,2)}
|
|
73
|
+
`)}async function xQ($){let Z;try{Z=await S0(m($,n2),"utf8")}catch(J){if(J.code==="ENOENT")return new Set;throw J}try{let J=JSON.parse(Z);if(Array.isArray(J?.files))return new Set(J.files.filter((X)=>typeof X==="string"))}catch{}return new Set}async function yQ($,Z){await T1(m($,n2),`${JSON.stringify({version:1,files:Z},null,2)}
|
|
74
|
+
`)}async function gQ($){await p4(m($,n2)).catch((Z)=>{if(Z.code!=="ENOENT")throw Z})}async function A$($,Z){await T1($,`${JSON.stringify(Z,null,2)}
|
|
75
|
+
`)}async function T1($,Z){await BJ(N1($)),await P0($,null,{serialize:()=>Z,durable:!0,durability:"file-only-on-windows"})}async function BJ($){if(process.platform==="win32")return;await JQ($,{recursive:!0,mode:448}),await ZQ($,448)}async function K1($,Z,J){let X=performance.now();for(;;){let z=null;try{z=await K0({name:$,path:Z,ttlMs:a8,renew:!0})}catch(G){if(G.code!=="ENOENT")throw G}if(z)return z;if(performance.now()-X>=J)throw new u4("lock-timeout",`${$} lock at ${Z}`);await new Promise((G)=>setTimeout(G,QQ))}}async function F0($){try{return await s8($),!0}catch(Z){let J=Z.code;if(J==="ENOENT"||J==="ENOTDIR")return!1;throw Z}}
|
|
76
|
+
export{B4 as ka,u as la,qX as ma,R as na,jX as oa,j6 as pa,h0 as qa,E as ra,d5 as sa,dX as ta,M9 as ua,cX as va,x6 as wa,j2 as xa,oU as ya,sX as za,tU as Aa,eU as Ba,nX as Ca,y6 as Da,a5 as Ea,C9 as Fa,S9 as Ga,E9 as Ha,N2 as Ia,R9 as Ja,m2 as Ka,P4 as La,Dz as Ma,Tz as Na,Lz as Oa,V0 as Pa,D2 as Qa,_z as Ra,L4 as Sa,Az as Ta,Bj as Ua,Qj as Va,Wj as Wa,Yj as Xa,Vj as Ya,Hj as Za,rZ as _a,wz as $a,jj as ab,Fj as bb,lz as cb,Mj as db,Cj as eb,Tj as fb,$7 as gb,Sj as hb,AG as ib,gF as jb,wF as kb,uF as lb,bG as mb,pF as nb,lF as ob,dF as pb,cF as qb,iF as rb,rF as sb,oF as tb,xj as ub,sz as vb,fj as wb,vj as xb,R4 as yb,ej as zb,$F as Ab,ez as Bb,n9 as Cb,$G as Db,ZG as Eb,ZF as Fb,JG as Gb,GF as Hb,BF as Ib,QF as Jb,XG as Kb,WF as Lb,w2 as Mb,r9 as Nb,FG as Ob,UF as Pb,vG as Qb,c7 as Rb,tK as Sb,eG as Tb,eK as Ub,HB as Vb,g4 as Wb,qB as Xb,jB as Yb,PN as Zb,MN as _b,NB as $b,CN as ac,O0 as bc,TN as cc,LN as dc,_N as ec,G1 as fc,ON as gc,y4 as hc,z8 as ic,Z1 as jc,W8 as kc,J1 as lc,QN as mc,E8 as nc,uB as oc,lB as pc,dB as qc,xN as rc,cB as sc,yN as tc,gN as uc,pN as vc,XD as wc,zD as xc,GD as yc};
|