@cortexkit/opencode-openai-auth 1.8.3 → 1.8.4

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.
Files changed (37) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{codex-request-GJkvxv4S.d.ts → codex-request-C78nXs79.d.ts} +1 -1
  3. package/dist/{index-dw6yd976.js → index-1htk005d.js} +2 -2
  4. package/dist/{index-c50p5mem.js → index-5wgxt362.js} +1 -1
  5. package/dist/{index-fyrgwfx3.js → index-a5h82jha.js} +2 -2
  6. package/dist/{index-hpnj460b.js → index-byz2j6hz.js} +1 -1
  7. package/dist/{index-0v7ar02e.js → index-e7gekawr.js} +1 -1
  8. package/dist/{index-g556s1mz.js → index-hnmbhgk4.js} +2 -2
  9. package/dist/{index-rw932qm9.js → index-hvmj07f7.js} +21 -21
  10. package/dist/{index-z81cged1.js → index-k7zb6wa7.js} +2 -2
  11. package/dist/{index-b0s5cty6.js → index-kemp2vh4.js} +2 -2
  12. package/dist/{index-p8m4yh73.js → index-kphzmgq6.js} +1 -1
  13. package/dist/index-nsdjapq1.js +2 -0
  14. package/dist/{index-yt52fztj.js → index-pg5c6by3.js} +2 -2
  15. package/dist/{index-bej7x30p.js → index-t8248wa4.js} +7 -7
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +1 -1
  18. package/dist/rpc/port-file.js +1 -1
  19. package/dist/rpc/protocol.js +1 -1
  20. package/dist/rpc/rpc-client.js +1 -1
  21. package/dist/rpc/rpc-dir.js +1 -1
  22. package/dist/{sidebar-state-DkNebAiC.d.ts → sidebar-state-CrRiE9hw.d.ts} +3 -1
  23. package/dist/sidebar-state.d.ts +1 -1
  24. package/dist/sidebar-state.js +1 -1
  25. package/dist/{token-3vtr29vt.js → token-j2jmx8k7.js} +1 -1
  26. package/dist/token-util-7n2nfbyc.js +1 -0
  27. package/dist/tui-preferences.js +1 -1
  28. package/dist/tui.d.ts +1 -1
  29. package/dist/v2/server.d.ts +1 -1
  30. package/dist/v2/server.js +2 -2
  31. package/package.json +1 -1
  32. package/src/tui-compiled/raw/sidebar-state.js +10 -6
  33. package/src/tui-compiled/raw/tui.tsx +37 -27
  34. package/src/tui-compiled/runtime/sidebar-state.js +10 -6
  35. package/src/tui-compiled/runtime/tui.js +39 -55
  36. package/dist/index-03hs0rq7.js +0 -2
  37. package/dist/token-util-erhrf24m.js +0 -1
@@ -1,8 +1,8 @@
1
- import{$c as A7,Ad as q6,Bd as F6,Cd as K6,Dd as x1,Ec as hZ,Fc as x7,Gc as n5,Gd as E1,Hc as r4,Id as N0,Jc as b5,Kc as PZ,Kd as M0,Lc as H7,Ld as h1,Mc as CZ,Nc as o4,Nd as g1,Oc as t4,Od as RZ,Pc as e4,Qd as i5,Rc as f7,Sc as h7,Tc as E4,Td as D0,Uc as b4,Vc as g4,Xc as m7,Yc as w1,Zc as w7,Zd as v1,_c as O7,ce as S7,dd as C5,ed as T5,ee as I7,fe as R7,he as P0,ie as C0,ke as P5,ne as V7,qd as Q6,td as W6,ud as Y6,vd as H6,wd as L5,xd as V6,yd as U6,zd as j6}from"./index-b0s5cty6.js";import{Ae as AZ,Be as X4,Ce as L9,De as QZ,Fe as o1,Ge as z4,ze as J4}from"./index-fyrgwfx3.js";import{Qe as s7}from"./index-z81cged1.js";import{$e as s,Xe as w4,af as k7,cf as D$,df as u1,ef as P$,ff as TZ}from"./index-dw6yd976.js";import{if as z5,of as $4}from"./index-g556s1mz.js";class R extends Error{operation;rowId;phase;retryable;kind;committed;constructor(Z){super(Z.message??`${Z.operation} failed (${Z.kind}, ${Z.phase})`,Z.cause===void 0?void 0:{cause:Z.cause});this.name="PoolOperationError",this.operation=Z.operation,this.rowId=Z.rowId,this.phase=Z.phase,this.retryable=Z.retryable,this.kind=Z.kind,this.committed=Z.committed}}class r1 extends Error{operation;constructor(Z){super(`${Z} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=Z}}var iZ="identity-contradicted: ",U9="duplicate-identity";function kZ(Z,$,J){let X=Z.rosterRow($);if(!X)return;X.enabled=!1;let z=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");Z.setEntry($,{...z,disabledReason:G?z.disabledReason:J})}function N1(Z,$){let J=Z.rosterRow($);if(!J)return;J.enabled=!0;let X=Z.entry($);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,Z.setEntry($,z)}}function rZ(Z,$){let J=Z.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===$),X=[];for(let z of J.slice(1))kZ(Z,z.id,"duplicate-identity"),X.push(z.id);return X}function mZ(Z,$,J){let X=Z.rosterRow($);if(!X)return[];return X.accountId=J,rZ(Z,J)}import{setTimeout as O3}from"node:timers/promises";import{AsyncLocalStorage as W3}from"node:async_hooks";var u$=new W3;function p(Z){if(u$.getStore()!==void 0)throw new r1(Z)}function KZ(Z,$){return u$.run(Z,async()=>await $())}async function p$(Z,$,J,X,z){if(!$)return;try{await KZ(Z,()=>$(J,X))}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:Z,rowId:J,error:G instanceof Error?G.message:String(G)})}}var j9=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function Y3(Z,$,J){let X=(B)=>{try{let Q=J.onLockEvent?.({type:B,name:Z.name,path:Z.path});if(Q&&(typeof Q==="object"||typeof Q==="function")&&"then"in Q&&typeof Q.then==="function")Promise.resolve(Q).catch(()=>{})}catch{}},z={...$,...H3(Z)},G=performance.now();for(;;){let B=await QZ({name:Z.name,path:Z.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>X("contended"),...J.onRenewalTimer?{onRenewalTimer:(W)=>J.onRenewalTimer?.({name:Z.name,path:Z.path},W)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...J.onLockStep?{onStep:(W)=>J.onLockStep?.({name:Z.name,path:Z.path},W)}:{}});if(B){X("acquired");let W={name:Z.name,path:Z.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),X("released")}};try{await W.assertOwned()}catch(H){throw await W.release(),H}return W}let Q=z.timeoutMs-(performance.now()-G);if(Q<=0)throw new o1({target:Z.path,name:Z.name,timeoutMs:z.timeoutMs});let Y=Math.floor(Math.random()*(z.retryMs+1));await new Promise((W)=>setTimeout(W,Math.min(z.retryMs+Y,Q)))}}function H3(Z){let $={};if(Z.ttlMs!==void 0)$.ttlMs=Z.ttlMs;if(Z.timeoutMs!==void 0)$.timeoutMs=Z.timeoutMs;if(Z.retryMs!==void 0)$.retryMs=Z.retryMs;if(Z.renew!==void 0)$.renew=Z.renew;if(Z.renewIntervalMs!==void 0)$.renewIntervalMs=Z.renewIntervalMs;return $}class NZ{defaults;env;held=[];constructor(Z,$){this.defaults=Z,this.env=$}async acquire(Z){let $=await Y3(Z,this.defaults,this.env);return this.held.push($),await this.assertAll(),$}async assertAll(){for(let Z of this.held)await Z.assertOwned()}async releaseTo(Z){while(this.held.length>Z)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}function wZ(Z,$,J){if(J!==void 0)throw new R({operation:Z,rowId:$,kind:"row-staged",phase:Z==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${$} is reserved for roster publication`})}import{createHash as M1}from"node:crypto";var y="commonAuthPool",vZ=1,WZ="rows",t1="retiredEpochs",D1=1,q9=300000,E=y;function V3(Z){let $=JSON.parse(JSON.stringify(Z)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(C(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J($)}function uZ(Z){return M1("sha256").update(V3(Z)).digest("hex")}function l$(Z){if(!C(Z)||Object.keys(Z).length!==1||typeof Z.reservation!=="string"||!Z.reservation)return;return{reservation:Z.reservation}}function U3(Z){if(!C(Z)||typeof Z.reservation!=="string"||!Z.reservation||typeof Z.disabledReason!=="string")return;if(Object.keys(Z).some(($)=>!["reservation","label","disabledReason","providerState"].includes($)))return;if("label"in Z&&typeof Z.label!=="string")return;if("providerState"in Z&&(typeof Z.providerState!=="string"||!/^[a-f0-9]{64}$/.test(Z.providerState)))return;return Z}var d="commonAuthProviderState";function C(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var j3=new Set(["__proto__","constructor","prototype"]);function oZ(Z){if(typeof Z!=="string"||Z.length===0)return"id must be non-empty";if(Z.trim()!==Z)return"id must not carry surrounding whitespace";if(j3.has(Z))return"id is a reserved object key";return}function F9(Z){let $=typeof Z==="string"?Z.trim():"";if(!$)return!1;try{let J=new URL($);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function d$(Z){return Z.type==="oauth"?`oauth\x00${Z.refresh}`:`api\x00${Z.apiKey}`}function YZ(Z){return M1("sha256").update(d$(Z)).digest("hex")}function MZ(Z){return M1("sha256").update(`credential-stamp\x00${d$(Z)}`).digest("hex")}function OZ(Z){let $=Z.type==="oauth"?["oauth",typeof Z.access==="string"?Z.access:null,Z.refresh,typeof Z.expires==="number"&&Number.isFinite(Z.expires)?Z.expires:null]:["api",Z.apiKey,Z.baseURL.trim(),Z.authHeader??"authorization-bearer"];return M1("sha256").update(`credential-dispatch\x00${JSON.stringify($)}`).digest("hex")}function K9(Z,$,J,X={}){return{credentialEpoch:$,digest:MZ(Z),dispatch:OZ(Z),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function tZ(Z,$){let J=Z?.credentialBound?Z.credentialBound($):$;return M1("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function P1(Z,$,J,X){if(!$||J===void 0)return;if(!C(Z)||!Object.hasOwn(Z,d))return;let z=a(Z[E]);if(!z||z.providerState===void 0||z.digest!==MZ($)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function w(Z){return Number.isSafeInteger(Z)&&Z>=1}function a(Z){if(!C(Z))return;let $=Z.credentialEpoch;if(!w($))return;if(typeof Z.digest!=="string")return;if("dispatch"in Z&&typeof Z.dispatch!=="string")return;if("replace"in Z&&Z.replace!==!0)return;if("providerState"in Z&&typeof Z.providerState!=="string")return;let J="staged"in Z?U3(Z.staged):void 0;if("staged"in Z&&!J)return;let X={...J?{staged:J}:{},...typeof Z.dispatch==="string"?{dispatch:Z.dispatch}:{},...Z.replace===!0?{replace:!0}:{},...typeof Z.providerState==="string"?{providerState:Z.providerState}:{}};if(!("binding"in Z))return"dispatch"in Z||"replace"in Z||"providerState"in Z||"staged"in Z?void 0:{credentialEpoch:$,digest:Z.digest};let z=Z.binding;if(!C(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!F9(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:$,digest:Z.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 q3(Z,$,J){if(Z.identity!==J)return!1;if(Z.baseURL!==void 0&&($.type!=="api"||$.baseURL!==Z.baseURL))return!1;if(Z.authHeader!==void 0&&($.type!=="api"||$.authHeader!==Z.authHeader))return!1;return!0}function F3(Z,$,J,X){if(!Z)return"none";if(!C(X)||!Object.hasOwn(X,E))return"missing";let z=a(X[E]);if(!z)return"malformed";if(z.digest!==MZ(Z))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==$)return"mismatched";if(!z.binding||!q3(z.binding,Z,J))return"mismatched";if(z.dispatch!==OZ(Z))return"mismatched";return"bound"}function N9(Z){if(!Z.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in Z)return{status:"error",reason:"config file is not valid JSON"};let $=Z.value;if(!C($))return{status:"error",reason:"config root is not an object"};if("accounts"in $&&!Array.isArray($.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(y in $))return Array.isArray($.accounts)?{status:"pending-migration",config:$}:{status:"ready",exists:!0,config:$};let J=$[y];if(!C(J))return{status:"error",reason:`${y} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${y}.schemaVersion is invalid`};if(X>vZ)return{status:"error",reason:`${y}.schemaVersion ${X} is newer than ${vZ}`};if(WZ in J&&!C(J[WZ]))return{status:"error",reason:`${y}.${WZ} is not an object`};return{status:"ready",exists:!0,config:$}}function c$(Z){if(!Z.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in Z)return{status:"error",reason:"state file is not valid JSON"};if(!C(Z.value))return{status:"error",reason:"state root is not an object"};if("accounts"in Z.value&&!C(Z.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:Z.value}}function eZ(Z){return Array.isArray(Z.accounts)?Z.accounts:[]}function s$(Z){let $=Z[y];if(!C($))return{};let J=$[WZ];return C(J)?J:{}}function K3(Z){return C(Z.accounts)?Z.accounts:{}}function N3(Z){if(!C(Z))return"not an object";let $=oZ(Z.id);if($)return $;if(Z.type==="api")return F9(Z.baseURL)?void 0:"invalid baseURL";if(Z.type==="oauth")return;return"unknown type"}function M3(Z,$){if(!C(Z))return;let J=Z.credentialEpoch;if(!w(J))return;if("needsFirstReading"in Z&&typeof Z.needsFirstReading!=="boolean")return;if("disabledReason"in Z&&typeof Z.disabledReason!=="string")return;let X="quota"in Z&&$.decode?$.decode(Z.quota):Z.quota;if("quota"in Z&&!$.validate(X))return;if("staged"in Z&&!l$(Z.staged))return;return{credentialEpoch:J,needsFirstReading:Z.needsFirstReading===!0,...typeof Z.disabledReason==="string"?{disabledReason:Z.disabledReason}:{},..."quota"in Z?{quota:X}:{}}}function D3(Z,$){if(!C($))return;if(Z.type==="api"){let X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if(Z.corrupt===!0)return;let J=$.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof $.access==="string"?{access:$.access}:{},...typeof $.expires==="number"?{expires:$.expires}:{},...typeof $.lastRefreshedAt==="number"?{lastRefreshedAt:$.lastRefreshedAt}:{}}}function e1(Z,$){return eZ(Z).find((J)=>C(J)&&J.id===$)}function a$(Z){if(!C(Z[y]))Z[y]={};return Z[y]}function M9(Z){let $=a$(Z);if(!C($[WZ]))$[WZ]={};return $[WZ]}function DZ(Z,$){let J=s$(Z),X=Object.hasOwn(J,$)?J[$]:void 0;return C(X)?X:void 0}function Z5(Z,$,J){Object.defineProperty(M9(Z),$,{value:J,enumerable:!0,writable:!0,configurable:!0})}function n$(Z,$){let J=Z[y];if(!C(J))return;let X=J[t1];if(!C(X)||!Object.hasOwn(X,$))return;let z=X[$];return w(z)?z:void 0}function i$(Z,$){let J=DZ(Z,$)?.credentialEpoch;return w(J)?J:void 0}function $5(Z,$){return Math.max(n$(Z,$)??0,i$(Z,$)??0)+1}function r$(Z,$){let J=[...$];if(J.length===0)return;let X=a$(Z),z=C(X[t1])?X[t1]:{},G={},B=(Q,Y)=>Object.defineProperty(G,Q,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[Q,Y]of Object.entries(z))if(w(Y))B(Q,Y);for(let Q of J)B(Q,Math.max(n$(Z,Q)??0,i$(Z,Q)??1));X[t1]=G}function gZ(Z,$,J,X){let z=s$(Z),G=K3($),B=new Set,Q=[];for(let Y of eZ(Z)){let W=N3(Y),H=C(Y)&&typeof Y.id==="string"?Y.id:void 0,V=H===void 0?void 0:z[H],j=C(V)&&Object.hasOwn(V,"staged"),F=j?l$(V.staged):void 0;if(W||!C(Y)||H===void 0||B.has(H)){if(H!==void 0&&!B.has(H))B.add(H);if(H!==void 0)Q.push({id:H,type:C(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,H),candidate:!1,invalid:"roster",stamp:"none",...F?{staged:F}:{}});continue}B.add(H);let U=Y.type==="api"?"api":"oauth",q=Object.hasOwn(z,H),K=q?M3(z[H],J):void 0,N=D3(Y,G[H]),D=Y.enabled!==!1,O=K?K.credentialEpoch:q?void 0:1,L=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,M={id:H,type:U,enabled:D,needsFirstReading:K?K.needsFirstReading:U==="oauth",hasEntry:q,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},...L!==void 0?{identity:L}:{},...N?{credential:N,fingerprint:YZ(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...F?{staged:F}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...P3(G[H],N,O,L,X),stamp:F3(N,O,L,G[H])};if(q&&!K)M.invalid="entry";else M.candidate=D&&N!==void 0&&!j;Q.push(M)}return Q}function P3(Z,$,J,X,z){if(!C(Z)||!Object.hasOwn(Z,d))return{};let G=P1(Z,$,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let B=Z[d];if(!z?.validate(B))return{providerStateDropped:"invalid"};if(tZ(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function v(Z){return Z.identity??Z.id}function C1(Z,$){if(Z===void 0||Z>$+q9)return $;return Math.max($,Z+1)}function D9(Z,$){return C1(Z,$)>$+q9}function Z1(Z){let{id:$,credential:J,identity:X,label:z,addedAt:G}=Z;return{id:$,...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 o$(Z,$){if(Z.type==="api")return{apiKey:Z.apiKey};return{...Z.access!==void 0?{access:Z.access}:{},refresh:Z.refresh,...Z.expires!==void 0?{expires:Z.expires}:{},...$!==void 0?{lastRefreshedAt:$}:{}}}function t$(Z,$){if(Z.type==="api")return{...Z,baseURL:Z.baseURL.trim(),authHeader:Z.authHeader??"authorization-bearer"};return{...Z,...$!==void 0?{lastRefreshedAt:$}:{}}}function e$(Z,$={}){if(!C(Z))return"credential must be an object";if(Z.type==="oauth"){if(typeof Z.refresh!=="string"||!Z.refresh.trim())return"oauth credential needs a refresh token";return}if(Z.type==="api"){if(typeof Z.apiKey!=="string"||!Z.apiKey.trim())return"api credential needs an api key";if(Z.apiKey.trim()!==Z.apiKey)return"api key must not carry surrounding whitespace";if(!($.baseURLOptional&&Z.baseURL===void 0)&&!F9(Z.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var J5="transition",Z4="transitionMark";function C3(Z){if(!C(Z))return;let $=Z[J5];if(!C($))return;if(typeof $.mark!=="string"||$.mark.length===0)return;if($.enabled===!0)return{mark:$.mark,enabled:!0};if($.enabled===!1&&typeof $.reason==="string")return{mark:$.mark,enabled:!1,reason:$.reason};return}function T1(Z,$,J){if(J.enabled)N1(Z,$);else kZ(Z,$,J.reason??"");if(!Z.rosterRow($))return;let X=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0};if(Z.setEntry($,{...X,[Z4]:J.mark}),!J.enabled)return;let z=Z.rows().find((G)=>G.id===$);if(z?.type==="oauth"&&z.identity!==void 0)rZ(Z,z.identity)}function T3(Z,$){if(Z.type!=="api")return Z;return{...Z,...$.baseURL!==void 0?{baseURL:$.baseURL}:{},...$.authHeader!==void 0?{authHeader:$.authHeader}:{}}}function L3(Z){if(!Z.binding)return!1;return Z.replace===!0||Z.dispatch===void 0}function _3(Z,$,J,X={}){let z=C($.accounts)?$.accounts:{},G=new Map;for(let B of gZ(Z,$,J)){if(B.invalid||B.staged||!B.credential)continue;let Q=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!C(Q))continue;let Y=a(Q[E]);if(!Y?.binding)continue;if(Y.digest!==MZ(B.credential))continue;let W=B.credentialEpoch??1;if(Y.credentialEpoch>W){if(!L3(Y))continue;if(X.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==OZ(T3(B.credential,Y.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===W&&Y.dispatch!==void 0&&Y.dispatch===OZ(B.credential)&&Y.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===W&&Y.binding.identity===B.identity){if(X.requireCredentialStamps&&Y.dispatch!==OZ(B.credential))continue;let H=C3(Q[E]);if(H&&DZ(Z,B.id)?.[Z4]!==H.mark)G.set(B.id,{kind:"transition",transition:H})}}return G}function P9(Z,$,J,X){let G={...Z.entry($)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(iZ))delete G.disabledReason;Z.setEntry($,G);let B=Z.rosterRow($);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 C9(Z,$,J,X={}){let z=_3(Z,$,J,X);if(z.size===0)return{config:Z,torn:[]};let G=structuredClone(Z),B={rows:()=>gZ(G,$,J),rosterRow:(Q)=>e1(G,Q),entry:(Q)=>DZ(G,Q),setEntry:(Q,Y)=>Z5(G,Q,Y)};for(let[Q,Y]of z)if(Y.kind==="replace")P9(B,Q,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[Q,Y]of z)if(Y.kind==="identity")mZ(B,Q,Y.identity);else if(Y.kind==="transition")T1(B,Q,Y.transition);else if(Y.stamp.binding.identity!==void 0)rZ(B,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function T9(Z,$,J,X={}){let{config:z,torn:G}=C9(Z,$,J,X),B=gZ(z,$,J,X.providerState);for(let Q of B){if(G.includes(Q.id))Q.torn=!0,Q.candidate=!1;if(X.requireCredentialStamps&&Q.stamp!=="bound")Q.unbound=!0,Q.candidate=!1}return B}async function X5(Z){try{return await $4(Z,z5)}catch($){if($.code==="ENOENT")return;throw $}}function _9(Z){if(Z===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse(Z)}}catch($){return{exists:!0,parseError:$}}}async function G4(Z){return N9(_9(await X5(Z)))}async function n(Z){for(let $=0;$<3;$++){let J=await X5(Z.configPath),X=await X5(Z.statePath),z=await X5(Z.configPath);if(J!==z){if($<2)await O3(2+Math.floor(Math.random()*4));continue}let G=N9(_9(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=c$(_9(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:T9(G.config,B.state,Z.codec,{requireCredentialStamps:Z.requireCredentialStamps===!0,...Z.providerState?{providerState:Z.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function HZ(Z,$,J,X="before-first-write"){if(Z.status==="error"&&Z.kind==="snapshot-contended")return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:Z.reason});return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:X,retryable:!1,kind:Z.status==="pending-migration"?"pending-migration":"load-error",message:Z.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${Z.file} file cannot be loaded: ${Z.reason}`})}class B4{ctx;snapshot;locks;progress;info;config;state;constructor(Z,$,J,X,z){this.ctx=Z,this.snapshot=$,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone($.config),this.state=structuredClone($.state)}rows(){return T9(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row(Z){return this.rows().find(($)=>$.id===Z)}reservation(Z){if(this.rosterRow(Z)){let J=this.entry(Z);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let $=this.stateAccount(Z)?.[E];return C($)&&Object.hasOwn($,"staged")?$.staged:void 0}assertNotStaged(Z){wZ(this.info.operation,Z,this.reservation(Z))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow(Z){return this.roster(),e1(this.config,Z)}dropRosterRows(Z){let $=this.roster(),J=$.filter((X)=>!(C(X)&&X.id===Z));return this.config.accounts=J,$.length-J.length}entries(){return M9(this.config)}entry(Z){return this.entries(),DZ(this.config,Z)}setEntry(Z,$){Z5(this.config,Z,$)}async completeTorn(){let{config:Z,torn:$}=C9(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if($.length===0)return;this.config=Z,await this.commitConfig({counted:!1})}stateAccount(Z){let $=C(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn($,Z)?$[Z]:void 0;return C(J)?J:void 0}dropStateAccount(Z){if(C(this.state.accounts)&&Object.hasOwn(this.state.accounts,Z))delete this.state.accounts[Z]}setStateAccount(Z,$){if(!C(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,Z,{value:$,enumerable:!0,writable:!0,configurable:!0})}async commitConfig(Z={}){let $=this.roster(),J=new Set;for(let Y of $)if(C(Y)&&typeof Y.id==="string")J.add(Y.id);let X=new Set;for(let Y of eZ(this.snapshot.config))if(C(Y)&&typeof Y.id==="string"&&!J.has(Y.id))X.add(Y.id);for(let Y of Object.keys(this.entries()))if(!J.has(Y))X.add(Y);r$(this.config,X);let z=this.entries(),G={};for(let[Y,W]of Object.entries(z))if(J.has(Y))Object.defineProperty(G,Y,{value:W,enumerable:!0,writable:!0,configurable:!0});let B=this.config[y],Q={...this.config,version:D1,accounts:$,[y]:{...B,schemaVersion:vZ,[WZ]:G}};await this.write(this.ctx.configPath,Q,"config",Z.counted??!0,Z.durable??!1,()=>{if(Z.publicationDecision)this.markPublicationDecision();for(let Y of X)this.ctx.removedIds.add(Y);this.config=Q}),this.config=Q}async commitState(Z,$={}){let J={...this.state,version:D1,accounts:C(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,$.durable??!1),this.state=J,Z)this.progress.committed=Z}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await L9(this.ctx.statePath)}catch(Z){throw new R({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:Z})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await L9(this.ctx.configPath)}async write(Z,$,J,X=!0,z=!1,G){await X4(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 Q4(Z,$){let J=new NZ(Z.lockDefaults,Z.lockEnv),X={writes:0};try{for(let Q of Z.storeLocks)await J.acquire(Q);let z=await n(Z);if(z.status==="error")throw HZ(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[Q,Y]of Object.entries(z.config))if(!$.includes(Q))G[Q]=Y;G.version=D1,G[y]={schemaVersion:vZ,[WZ]:{}};let B={operation:"initialize",rowId:void 0};return await AZ(Z.configPath,G,{beforeRename:async()=>{await Z.onStep?.("before-config-write",B),await J.assertAll()}}),X.writes++,await Z.onStep?.("after-config-write",B),"initialized"}catch(z){throw fZ(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function h(Z,$,J,X,z,G={}){let B=$.held.length;try{for(let W of Z.storeLocks)await $.acquire(W);let Q=await n(Z);if(Q.status!=="ready")throw HZ(Q,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let Y=new B4(Z,Q,$,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))Y.assertNotStaged(X.rowId);if(G.completeTorn??!0)await Y.completeTorn();return await z(Y)}finally{await $.releaseTo(B)}}function fZ(Z,$,J,X){let z=$==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if($==="publishRoster"&&X.publicationDecided)return new R({operation:$,...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:Z});if($==="publishRoster"&&Z instanceof J4)return new R({operation:$,...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:Z});if(Z instanceof R){if(Z.phase===z&&Z.rowId===J&&Z.operation===$&&Z.committed===G)return Z;return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:Z.kind==="after-persist-hook"?Z.phase:z,retryable:Z.retryable,kind:Z.kind,...Z.committed??G?{committed:Z.committed??G}:{},message:Z.message,...Z.cause!==void 0?{cause:Z.cause}:{}})}let B={operation:$,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:Z};if(Z instanceof z4)return new R({...B,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${$} lost a lease after its first write; the intermediate stays on disk`:`${$} lost a lease before writing; nothing was written`});if(Z instanceof o1)return new R({...B,retryable:!0,kind:"lock-contention",message:Z.message});return new R({...B,retryable:!1,kind:"unexpected",message:Z instanceof Error?Z.message:String(Z)})}async function l(Z,$,J,X,z){let G=new NZ(Z.lockDefaults,Z.lockEnv),B={writes:0};try{return await z(G,B)}catch(Q){let Y=fZ(Q,$,J,B);if(Y.kind!=="after-persist-hook")await p$($,X,J,Y,Z.logger);throw Y}finally{await G.releaseAll()}}function r(Z,$){return{...Z.rowLockOptions,name:`row-${encodeURIComponent(v($))}`,path:Z.ctx.statePath}}async function VZ(Z,$,J){let X=await n(Z.ctx);if(X.status!=="ready")throw HZ(X,$,J);let z=X.rows.find((W)=>W.id===J),G=DZ(X.config,J),B=X.state.accounts,Q=C(B)&&Object.hasOwn(B,J)?B[J]:void 0,Y=C(Q)?Q[E]:void 0;if(z&&!["enable","disable"].includes($)&&G&&Object.hasOwn(G,"staged"))wZ($,J,G.staged);if(!z&&C(Y)&&Object.hasOwn(Y,"staged"))wZ($,J,Y.staged);if(!z)throw e($,J);return{result:X,row:z}}function e(Z,$){return new R({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${$} in the pool`})}function c(Z,$){if($.unbound)throw P(Z,$.id,"unbound-credential",`row ${$.id}'s credential is not the one this store stamped for it (stamp ${$.stamp}); replace it with fresh material`)}function P(Z,$,J,X,z=!1){return new R({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function O9(Z,$){if(!w($?.credentialEpoch))throw P("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function L1(Z,$,J){if(!J)throw e("pull",Z);if(J.invalid)throw P("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!J.credential)throw P("pull",Z,"no-credential",`row ${Z} holds no credential`);if(c("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==$.credentialEpoch||J.identity!==$.identity)throw new R({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${Z} was issued for a credential the row no longer holds`})}function _1(Z,$,J,X){let z=Z.codec.merge(J,X);if(!Z.codec.validate(z))throw P("pull",$,"invalid-quota","the quota codec rejected the merged map");return z}async function G5(Z,$,J,X){let{ctx:z}=Z,G=new NZ(z.lockDefaults,z.lockEnv),B={writes:0};try{O9($,J),await h(z,G,B,{operation:"pull",rowId:$},async(Q)=>{Q.assertNotStaged($);let Y=Q.row($);L1($,J,Y);let W=Q.entry($);if(!W)throw e("pull",$);let H=_1(z,$,W.quota,X);Q.setEntry($,{...W,quota:H,needsFirstReading:!1}),await Q.commitConfig()},{completeTorn:!1})}catch(Q){throw fZ(Q,"pull",$,B)}finally{await G.releaseAll()}}function SZ(Z,$,J,X,z="the provider state"){if(!Z)throw P($,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 P($,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!Z.validate(G))throw P($,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function O1(Z,$,J,X,z){if(X===void 0||!Z?.merge)return{kind:"set",value:z};return{kind:"set",value:SZ(Z,$,J,Z.merge(structuredClone(X),structuredClone(z)),"the merged provider state")}}function W4(Z,$,J,X,z){let G=Z?.onReplace,B=G?G($.providerState===void 0?void 0:structuredClone($.providerState),{id:$.id,credentialEpoch:J,...$.identity!==void 0?{previousIdentity:$.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:SZ(Z,"replace",$.id,B,"the provider state onReplace returned")}}function Y4(Z,$,J,X,z){if($.kind==="set")return tZ(Z,$.value);if($.kind==="clear")return;return P1(J,X?.credential,z,X?.identity)}async function H4(Z,$,J,X,z={}){p("updateProviderState");let{ctx:G}=Z,B="updateProviderState";return l(G,B,$,z.onFailure,async(Q,Y)=>{let W=G.providerState;if(!W)throw P(B,$,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw P(B,$,"invalid-input","a mutator is required");let H=C(J)?J.credentialEpoch:void 0;if(!w(H))throw P(B,$,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await VZ(Z,B,$);await Q.acquire(r(Z,V));for(let j of z.extraLocks??[])await Q.acquire(j);return h(G,Q,Y,{operation:B,rowId:$},async(j)=>{let F=j.row($);if(!F)throw e(B,$);if(v(F)!==v(V))throw P(B,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0);if(F.invalid)throw P(B,$,"invalid-row",`row ${$} failed validation`);if(!F.credential)throw P(B,$,"no-credential",`row ${$} holds no credential`);if(c(B,F),(F.credentialEpoch??1)!==H||F.identity!==J.identity)throw P(B,$,"attribution",`the provider state for ${$} was read for a credential or account the row no longer holds`,!0);let q=await A9(j,W,B,F,X);if(q.kind!=="changed")return{id:$,outcome:"unchanged",...q.kind==="unchanged"&&q.value!==void 0?{providerState:q.value}:{}};return j.setStateAccount($,q.account),await j.commitState(),q.value===void 0?{id:$,outcome:"cleared"}:{id:$,outcome:"updated",providerState:q.value}})})}var V4=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function A9(Z,$,J,X,z,G=!1){let{id:B,credential:Q}=X;if(!Q)throw P(J,B,"no-credential",`row ${B} holds no credential`);let Y=X.credentialEpoch??1,W=Z.stateAccount(B),H=W?.[E],V=a(H);if(!C(H)||!V?.binding||V.digest!==MZ(Q)||V.credentialEpoch!==Y||V.binding.identity!==X.identity)throw P(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 j=X.providerState===void 0?void 0:structuredClone(X.providerState),F=await KZ(J,()=>z(j,X));if(G&&F===V4)return{kind:"declined"};let U=F===void 0?void 0:SZ($,J,B,F,"the provider state the mutator returned"),q=W!==void 0&&Object.hasOwn(W,d);if(U===void 0?!q:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let K={...W};if(U===void 0){delete K[d];let N={...H};delete N.providerState,K[E]=N}else{K[d]=U;let N=tZ($,U);if(V.providerState!==N)K[E]={...H,providerState:N}}return{kind:"changed",...U!==void 0?{value:U}:{},account:K}}import{randomUUID as U4}from"node:crypto";async function Y5(Z,$,J){if(!J)return;let X=Z.rows().map((G)=>{let{id:B,type:Q,label:Y,enabled:W,disabledReason:H,identity:V,credentialEpoch:j,stamp:F,staged:U,torn:q,invalid:K}=G;return{id:B,type:Q,label:Y,enabled:W,disabledReason:H,identity:V,credentialEpoch:j,stamp:F,staged:U,torn:q,invalid:K}}),z=await KZ(Z.info.operation,()=>J({id:$,row:X.find((G)=>G.id===$),rows:X,config:structuredClone(Z.snapshot.config)}));if(z!==void 0)throw P(Z.info.operation,$,"row-protected",z)}var A3=["access","refresh","expires","lastRefreshedAt","apiKey"];function S3(Z){return{baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function I3(Z,$,J){if(J.type!=="api")return J;let X=Z.rosterRow($);if(!C(X)){if(J.baseURL===void 0)throw P(Z.info.operation,$,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=Z.row($)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:S3(X),B=J.baseURL?.trim()??G.baseURL,Q=J.authHeader??G.authHeader;if(B!==G.baseURL||Q!==G.authHeader)throw P(Z.info.operation,$,"endpoint-mismatch",`row ${$} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:B,authHeader:Q}}function j4(Z,$,J,X){let z=Z.rosterRow($),G=Z.row($),B=X??(G?G.identity:C(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 B5(Z,$,J,X,z={}){let G=I3($,J,X),B=$.stateAccount(J),Q=z.providerState??{kind:"keep"},Y=$.row(J)?.credentialEpoch??$.entry(J)?.credentialEpoch,W=typeof Y==="number"?Y:1,H=Y4(Z.ctx.providerState,Q,B,B&&Object.hasOwn(B,d)?$.row(J):void 0,W),V=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??C1(V,Z.ctx.now()):void 0,F={...B??{}};for(let K of A3)delete F[K];if(z.clearErrors)delete F.lastRefreshError,delete F.lastQuotaRefreshError,delete F.quota;if(Q.kind==="clear")delete F[d];else if(Q.kind==="set")F[d]=Q.value;let U=t$(G,j),q={...F,...o$(G,j),[E]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[J5]:z.transition}:{},...K9(U,W,z.binding??j4($,J,U,z.identity),{replace:z.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:U,account:q}}async function Q5(Z,$,J){return Z.setStateAccount($,J.account),await Z.commitState(J.stored),J.stored}async function H5(Z,$,J,X,z={}){return Q5($,J,B5(Z,$,J,X,z))}async function R3(Z,$,J){if(!$.credential||$.stamp!=="bound")return;let X=Z.stateAccount($.id),z=P1(X,$.credential,$.credentialEpoch??1,$.identity);Z.setStateAccount($.id,{...X??{},[E]:K9($.credential,$.credentialEpoch??1,j4(Z,$.id,$.credential,J),z!==void 0?{providerState:z}:{})}),await Z.commitState()}function I9(Z,$,J){let X=Z==="add"?oZ($):void 0;if(X)throw P(Z,$,"invalid-input",X);let z=e$(J,{baseURLOptional:Z==="rotate"});if(z)throw P(Z,$,"invalid-input",z)}function V5(Z,$,J,X){if(!J)throw e(Z,$);if(J.invalid)throw P(Z,$,"invalid-row",`row ${$} failed validation`);if(X&&X.type!==J.type)throw P(Z,$,"type-mismatch",`row ${$} holds a ${J.type} credential`);return J}function J1(Z,$,J){if(J!==void 0&&!w(C(J)?J.credentialEpoch:void 0))throw P(Z,$,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function U5(Z,$,J,X){if(!J)throw e(Z,$);if(J.invalid)throw P(Z,$,"invalid-row",`row ${$} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw P(Z,$,"attribution",`the ${Z} of ${$} was issued for a credential or account the row no longer holds`,!0)}function W5(Z,$){return P(Z,$,"identity-mismatch",`row ${$} is recorded for another account; a credential of a different account is a replacement`)}function A1(Z,$){return P(Z,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0)}function E3(Z,$,J,X){let{id:z,credential:G,identity:B}=J;if(!Z.ctx.requireCredentialStamps||$.rosterRow(z)||!$1($.state,z))return;let Q=()=>{throw P("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=$.stateAccount(z),W=a(Y?.[E]);if(!W?.binding||W.dispatch===void 0||W.replace)return Q();if(G.type==="api"&&(W.binding.baseURL===void 0||W.binding.authHeader===void 0))return Q();let H=G.type==="api"?{...G,baseURL:W.binding.baseURL,authHeader:W.binding.authHeader}:G,[V]=gZ({accounts:[Z1({id:z,credential:H,identity:W.binding.identity,addedAt:0})],[y]:{rows:{[z]:{credentialEpoch:$5($.config,z)}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return Q();if(B!==void 0&&B!==V.identity)return Q();if(MZ(G)!==W.digest)return Q();if(G.type==="api"){if(G.baseURL.trim()!==W.binding.baseURL)return Q();if((G.authHeader??"authorization-bearer")!==W.binding.authHeader)return Q()}else if(OZ(G)!==W.dispatch)return Q();if(W.providerState!==void 0&&V.providerState===void 0)return Q();if(X!==void 0&&tZ(Z.ctx.providerState,X)!==W.providerState)return Q();return V}function b3(Z,$,J,X){let{id:z,credential:G,identity:B,label:Q}=J,Y=$.rosterRow(z),W=()=>{throw P("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},H=$.stateAccount(z),V=a(H?.[E]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return W();if(Y&&(Y.type!==G.type||Y.label!==Q||Y.accountId!==B))return W();if(j.reservation!==J.stage?.reservation||j.label!==Q||j.disabledReason!==J.disabled?.reason||V.binding.identity!==B)return W();let F=X===void 0?void 0:uZ(X),U=H?.[d],q=U===void 0?void 0:uZ(U);if(j.providerState!==F||j.providerState!==q)return W();if(MZ(G)!==V.digest||OZ(G)!==V.dispatch)return W();let K=Y?$.config:{accounts:[{...Z1({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[y]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},N=gZ(K,$.state,Z.ctx.codec,Z.ctx.providerState).find((D)=>D.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==j.label||N.identity!==V.binding.identity||N.disabledReason!==j.disabledReason||N.staged?.reservation!==j.reservation)return W();if(Y)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if($5($.config,z)!==V.credentialEpoch)return W();return $.roster().push({...Z1({id:z,credential:G,identity:B,label:Q,addedAt:Z.ctx.now()}),enabled:!1}),$.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),$.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function q4(Z,$,J={}){p("add");let{ctx:X}=Z,{id:z,credential:G,identity:B,label:Q}=$,Y=$.stage!==void 0||$.disabled!==void 0,W=await l(X,"add",z,J.onFailure,async(H,V)=>{I9("add",z,G);let j=J.onExisting??"rotate";if($.stage!==void 0&&j==="rotate")throw P("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||$.stage!==void 0&&(Q!==void 0&&typeof Q!=="string"||B!==void 0&&(typeof B!=="string"||!B))||$.disabled!==void 0&&(!C($.disabled)||typeof $.disabled.reason!=="string")||$.stage!==void 0&&(!C($.stage)||typeof $.stage.reservation!=="string"||!$.stage.reservation||!$.disabled)||j==="stage-duplicate"&&(!$.disabled||!$.stage))throw P("add",z,"invalid-input","staging requires a reservation and a disabled reason");let F=$.providerState===void 0?void 0:SZ(X.providerState,"add",z,$.providerState);if(await H.acquire(r(Z,{id:z,identity:B})),G.type==="oauth")await H.acquire(J.providerLock??Z.providerLock);for(let U of J.extraLocks??[])await H.acquire(U);return h(X,H,V,{operation:"add",rowId:z},async(U)=>{await Y5(U,z,J.protect);let q=C(U.state.accounts)?U.state.accounts:{},K=Object.entries(q).find(([b,g])=>{if(b===z||U.rosterRow(b)||!C(g))return!1;let K1=g[E];if(!C(K1)||!Object.hasOwn(K1,"staged"))return!1;return G.type==="oauth"?g.refresh===G.refresh:typeof g.apiKey==="string"&&g.apiKey.trim()===G.apiKey.trim()});if(K)throw P("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 P("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if($.stage&&j!=="rotate"&&(U.rosterRow(z)||$1(U.state,z)))return b3(Z,U,$,F);if(j==="rotate"){U.assertNotStaged(z);let b=U.rows().find((g)=>g.fingerprint===YZ(G));if(b)U.assertNotStaged(b.id)}if(j==="refuse"){let b=U.rows().find((yZ)=>yZ.fingerprint===YZ(G)||yZ.id===z&&yZ.credential),g=C(U.state.accounts)?U.state.accounts:{},K1=Object.entries(g).find(([,yZ])=>{if(!C(yZ))return!1;if(G.type==="oauth")return yZ.refresh===G.refresh;return typeof yZ.apiKey==="string"&&yZ.apiKey.trim()===G.apiKey.trim()})?.[0],w$=b?.id??K1??z;if(b||K1!==void 0||$1(U.state,z))throw P("add",w$,"credential-exists",`row ${w$} already holds this secret or id`)}if(j==="stage-duplicate"&&(U.rosterRow(z)||$1(U.state,z)))throw P("add",z,"id-exists",`row ${z} already exists`);let N=E3(Z,U,$,F),D=U.rows(),O=YZ(G),L=j==="rotate"&&!N&&D.find((b)=>b.invalid===void 0&&b.fingerprint===O);if(L){if(U.assertNotStaged(L.id),c("add",L),B!==void 0&&L.identity!==void 0&&B!==L.identity)throw W5("add",L.id);let b=B5(Z,U,L.id,G,{...F!==void 0?{providerState:O1(X.providerState,"add",L.id,L.providerState,F)}:{}});await U.completeTorn(),U.assertNotStaged(L.id);let g=await Q5(U,L.id,b);return{id:L.id,outcome:"rotated",credential:g,credentialEpoch:L.credentialEpoch??1}}let M=D.find((b)=>b.id===z);if(M){if(M.invalid)throw P("add",z,"invalid-row",`row ${z} is invalid`);if(M.credential)throw P("add",z,"id-exists",`row ${z} already holds a credential`);if(c("add",M),M.type!==G.type)throw P("add",z,"type-mismatch",`row ${z} is a ${M.type} row`);if(B!==void 0&&M.identity!==void 0&&B!==M.identity)throw W5("add",z);if(!M.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let b=B5(Z,U,z,G,{clearErrors:!0,...F!==void 0?{providerState:{kind:"set",value:F}}:{}});await U.completeTorn();let g=await Q5(U,z,b);if(!M.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:g,credentialEpoch:M.credentialEpoch??1}}let T=$5(U.config,z);if(!w(T))throw P("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let A=N?.identity??B;U.roster().push(Z1({id:z,credential:G,...A!==void 0?{identity:A}:{},...Q!==void 0?{label:Q}:{},addedAt:X.now()})),U.setEntry(z,{credentialEpoch:T,needsFirstReading:G.type==="oauth",...$.stage?{staged:{reservation:$.stage.reservation}}:{}});let _="added";if($.disabled)kZ(U,z,$.disabled.reason),_="added-disabled";if(!$.disabled&&A!==void 0&&G.type==="oauth"){if(D.find((g)=>g.invalid===void 0&&g.type==="oauth"&&g.enabled&&g.identity===A))kZ(U,z,U9),_="added-disabled"}if(N?.credential)return await U.commitConfig(),{id:z,outcome:_,credential:N.credential,credentialEpoch:N.credentialEpoch??T};U.dropStateAccount(z);let I=B5(Z,U,z,G,{...$.stage&&$.disabled?{staged:{reservation:$.stage.reservation,disabledReason:$.disabled.reason,...Q!==void 0?{label:Q}:{},...F!==void 0?{providerState:uZ(F)}:{}}}:{},...F!==void 0?{providerState:{kind:"set",value:F}}:{}});if(j==="rotate")await U.completeTorn();let x=await Q5(U,z,I);return await U.commitConfig(),{id:z,outcome:_,credential:x,credentialEpoch:T}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(W.outcome==="added"||W.outcome==="completed"))Z.firePull(W.id,"add");return W}async function F4(Z,$,J,X={},z={}){p("replace");let{ctx:G}=Z,B=await l(G,"replace",$,z.onFailure,async(Q,Y)=>{I9("replace",$,J),J1("replace",$,z.attribution);let W=X.providerState===void 0?void 0:SZ(G.providerState,"replace",$,X.providerState),{row:H}=await VZ(Z,"replace",$);if(await Q.acquire(r(Z,H)),J.type==="oauth")await Q.acquire(z.providerLock??Z.providerLock);for(let V of z.extraLocks??[])await Q.acquire(V);return h(G,Q,Y,{operation:"replace",rowId:$},async(V)=>{if(z.attribution!==void 0)U5("replace",$,V.row($),z.attribution),await V.completeTorn();let j=V5("replace",$,V.row($),J);if(v(j)!==v(H))throw A1("replace",$);let F=V.entry($)?.credentialEpoch,U=(typeof F==="number"?F:1)+1;if(!w(U))throw P("replace",$,"invalid-row",`row ${$}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let q=W4(G.providerState,j,U,X.identity,W),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(P9(V,$,U,K),X.identity!==void 0)rZ(V,X.identity);let N=await H5(Z,V,$,J,{clearErrors:!0,binding:K,providerState:q});return await V.commitConfig(),{id:$,credential:N,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")Z.firePull($,"replace");return B}async function K4(Z,$,J,X={},z={}){p("rotate");let{ctx:G}=Z;return l(G,"rotate",$,z.onFailure,async(B,Q)=>{I9("rotate",$,J),J1("rotate",$,z.attribution);let Y=X.providerState===void 0?void 0:SZ(G.providerState,"rotate",$,X.providerState),{row:W}=await VZ(Z,"rotate",$);if(await B.acquire(r(Z,W)),X.identity!==void 0&&J.type==="oauth")await B.acquire(z.providerLock??Z.providerLock);for(let H of z.extraLocks??[])await B.acquire(H);return h(G,B,Q,{operation:"rotate",rowId:$},async(H)=>{if(z.attribution!==void 0)U5("rotate",$,H.row($),z.attribution),await H.completeTorn();let V=V5("rotate",$,H.row($),J);if(v(V)!==v(W))throw A1("rotate",$);if(c("rotate",V),X.identity!==void 0&&V.identity!==void 0&&X.identity!==V.identity)throw W5("rotate",$);let j=X.identity!==void 0&&V.identity===void 0?X.identity:void 0,F=await H5(Z,H,$,J,{identity:j,...Y!==void 0?{providerState:O1(G.providerState,"rotate",$,V.providerState,Y)}:{}}),U=!1;if(!V.hasEntry)H.setEntry($,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),U=!0;if(X.identity!==void 0&&V.identity!==X.identity)mZ(H,$,X.identity),U=!0;if(U)await H.commitConfig();return{id:$,credential:F}},{completeTorn:z.attribution===void 0})})}async function N4(Z,$,J,X,z){p($);let{ctx:G}=Z,B=G.providerState,Q=z.attribution,Y=z.providerState;return l(G,$,J,z.onFailure,async(W,H)=>{if(J1($,J,Q),Y!==void 0){if(typeof Y!=="function")throw P($,J,"invalid-input","the provider-state mutator must be a function");if(Q===void 0)throw P($,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw P($,J,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await VZ(Z,$,J);await W.acquire(r(Z,V));for(let j of z.extraLocks??[])await W.acquire(j);return h(G,W,H,{operation:$,rowId:J},async(j)=>{await Y5(j,J,z.protect),j.assertNotStaged(J);let F=j.row(J),U=X.enabled?V5("enable",J,F):F;if(!U||!j.rosterRow(J))throw e($,J);if(v(U)!==v(V))throw A1($,J);if(Q!==void 0)U5($,J,U,Q);if(X.enabled&&U.disabledReason?.startsWith(iZ))throw P("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let q=!X.enabled||!U.enabled||U.disabledReason!==void 0;if(X.enabled&&q&&U.type==="oauth"){let L=U.identity===void 0?void 0:j.rows().find((M)=>M.id!==J&&M.invalid===void 0&&M.type==="oauth"&&M.enabled&&M.identity===U.identity);if(L)throw P("enable",J,"duplicate-identity",`row ${L.id} is enabled with the same identity as row ${J}`)}if(Y===void 0||B===void 0){if(await j.completeTorn(),!q)return{id:J};if(X.enabled)N1(j,J);else kZ(j,J,X.reason);return await j.commitConfig(),{id:J}}if(!U.credential)throw P($,J,"no-credential",`row ${J} holds no credential`);c($,U);let K=await A9(j,B,$,U,Y,!0);if(K.kind==="declined")return{id:J,declined:!0};await j.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(q){if(X.enabled)N1(j,J);else kZ(j,J,X.reason);await j.commitConfig()}return N}if(!q)return j.setStateAccount(J,K.account),await j.commitState(),N;let D=X.enabled?{mark:U4(),enabled:!0}:{mark:U4(),enabled:!1,reason:X.reason},O=K.account[E];return j.setStateAccount(J,{...K.account,[E]:{...O,[J5]:D}}),await j.commitState(),T1(j,J,D),await j.commitConfig(),N},{completeTorn:!1})})}function M4(Z,$,J,X={}){return N4(Z,"disable",$,{enabled:!1,reason:J},X)}function D4(Z,$,J={}){return N4(Z,"enable",$,{enabled:!0},J)}async function P4(Z,$,J={}){p("remove");let{ctx:X}=Z;return l(X,"remove",$,J.onFailure,async(z,G)=>{if(typeof $!=="string"||$.length===0)throw P("remove",$,"invalid-input","id must be non-empty");let B=J.attribution;if(J1("remove",$,B),J.staged!==void 0&&(!C(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw P("remove",$,"invalid-input","a staged removal needs a reservation");let Q=await n(X);if(Q.status!=="ready")throw HZ(Q,"remove",$);let Y=Q.rows.find((H)=>H.id===$);if(!Y&&!$1(Q.state,$))throw e("remove",$);let W=v(Y??{id:$});await z.acquire(r(Z,Y??{id:$}));for(let H of J.extraLocks??[])await z.acquire(H);return h(X,z,G,{operation:"remove",rowId:$},async(H)=>{let V=H.reservation($);if(V!==void 0){if(!C(V)||!J.staged||V.reservation!==J.staged.reservation)throw P("remove",$,"row-staged",`row ${$} is reserved for roster publication`)}else if(J.staged)throw P("remove",$,"attribution",`row ${$} is no longer reserved`);let j=H.row($),F=$1(H.state,$);if(!j&&!F)throw e("remove",$);if(v(j??{id:$})!==W)throw A1("remove",$);if(B!==void 0)if(j)j5($,j,B);else y3(Z,H,$,B);let U=J.protect;if(U){let q={row:j,config:H.snapshot.config,state:H.snapshot.state},K=await KZ("remove",()=>U($,q));if(K!==void 0)throw P("remove",$,"row-protected",K)}if(j){if(B===void 0)await H.completeTorn();H.dropRosterRows($),await H.commitConfig()}if(F)H.dropStateAccount($),await H.commitState();return{id:$,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function j5(Z,$,J,X="remove"){if(U5(X,Z,$,J),$.torn)throw P(X,Z,"attribution",`row ${Z} is between the writes of another operation; retry once it completes`,!0);if($.stamp!=="bound")throw P(X,Z,"unbound-credential",`row ${Z}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function y3(Z,$,J,X){let z=()=>P("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=$.stateAccount(J),B=a(G?.[E]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let Q;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();Q={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")Q={type:"oauth",refresh:G.refresh};else throw z();let[Y]=gZ({accounts:[Z1({id:J,credential:Q,identity:B.binding.identity,addedAt:0})],[y]:{rows:{[J]:{credentialEpoch:B.credentialEpoch}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(B.credentialEpoch!==X.credentialEpoch||B.binding.identity!==X.identity)throw P("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function $1(Z,$){let J=Z.accounts;return C(J)&&Object.hasOwn(J,$)}function S9(Z){return C(Z)&&typeof Z.id==="string"?Z.id:void 0}function k3(Z,$){if(!Array.isArray($))return"ids must be an array of roster ids";let J=new Set;for(let G of Z){let B=S9(G);if(B!==void 0)J.add(B)}let X=new Set;for(let G of $){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 v3(Z,$){let J=new Map;for(let G of Z){let B=S9(G);if(B===void 0)continue;let Q=J.get(B);if(Q)Q.push(G);else J.set(B,[G])}let X=$.flatMap((G)=>J.get(G)??[]),z=0;return Z.map((G)=>S9(G)===void 0?G:X[z++])}async function C4(Z,$,J={}){p("reorder");let{ctx:X}=Z,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Q of J.extraLocks??[])await G.acquire(Q);return h(X,G,B,{operation:"reorder",rowId:void 0},async(Q)=>{let Y=Q.roster(),W=k3(Y,$);if(W)throw new R({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:W});let H=[...$],V=v3(Y,H);if(V.every((j,F)=>j===Y[F]))return{ids:H,outcome:"unchanged"};return Q.config.accounts=V,await Q.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function T4(Z,$,J,X,z={}){return p("recordIdentity"),l(Z.ctx,"recordIdentity",$,z.onFailure,async(G,B)=>{if(typeof J!=="string"||J.length===0)throw P("recordIdentity",$,"invalid-input","identity must be non-empty");let Q=C(X)?X.credentialEpoch:void 0;if(!w(Q))throw P("recordIdentity",$,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await VZ(Z,"recordIdentity",$);await G.acquire(r(Z,Y)),await G.acquire(z.providerLock??Z.providerLock);for(let W of z.extraLocks??[])await G.acquire(W);return h(Z.ctx,G,B,{operation:"recordIdentity",rowId:$},async(W)=>{let H=V5("recordIdentity",$,W.row($));if(v(H)!==v(Y))throw A1("recordIdentity",$);if(c("recordIdentity",H),(H.credentialEpoch??1)!==Q)throw P("recordIdentity",$,"attribution",`the identity for ${$} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==J)throw W5("recordIdentity",$);if(H.identity===void 0)await R3(W,H,J);let V=mZ(W,$,J);return await W.commitConfig(),{id:$,disabled:V}})})}function _4(Z){let $=Z[y];return C($)&&C($.publications)?$.publications:{}}function O4(Z,$){let J=_4(Z);if(!Object.hasOwn(J,$))return;let X=J[$];if(!C(X)||X.operationId!==$||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)=>!C(z)||typeof z.id!=="string"||!w(z.credentialEpoch))||X.finalized.some((z)=>!C(z)||typeof z.id!=="string"||!w(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw P("publishRoster",$,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function A4(Z,$){let J=await n(Z.ctx);if(J.status!=="ready")throw HZ(J,"publishRoster",$);return O4(J.config,$)}function g3(Z,$){let J=()=>{throw P("publishRoster",$?.operationId??"","invalid-input","the publication plan is invalid")};if(!C($)||typeof $.operationId!=="string"||!$.operationId||!Array.isArray($.remove)||!Array.isArray($.finalize)||!Array.isArray($.order))J();let X=new Set;for(let z of[...$.remove,...$.finalize]){if(!C(z)||typeof z.id!=="string"||oZ(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),J1("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of $.remove)if(Z.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();for(let z of $.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))J();if($.order.some((z)=>typeof z!=="string"||oZ(z))||new Set($.order).size!==$.order.length)J()}function S4(Z,$){Z.entries();let J=Z.config[y],X={..._4(Z.config)};Object.defineProperty(X,$.operationId,{value:$,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function f3(Z,$,J){let X=new Set;for(let B of eZ(Z.config)){if(!C(B)||typeof B.id!=="string")continue;if(X.has(B.id))throw P("publishRoster",$.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(B.id)}let z=new Set($.remove.map((B)=>B.id)),G=J.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==$.order.length||$.order.some((B)=>!G.some((Q)=>Q.id===B))||G.some((B)=>!$.order.includes(B.id)))throw P("publishRoster",$.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function L4(Z,$){await Z.assertAll();for(let X of $.removed)if(a(Z.stateAccount(X.id)?.[E])?.credentialEpoch===X.credentialEpoch&&!Z.rosterRow(X.id))Z.dropStateAccount(X.id);for(let X of $.finalized){let z=Z.stateAccount(X.id),G=a(z?.[E]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let B={...z[E]};delete B.staged,Z.setStateAccount(X.id,{...z,[E]:B})}}await Z.commitState(void 0,{durable:!0});let J={...$,phase:"cleaned"};return S4(Z,J),await Z.commitConfig({durable:!0}),J}async function I4(Z,$,J={}){return p("publishRoster"),l(Z.ctx,"publishRoster",$?.operationId??"",J.onFailure,async(X,z)=>{if(!C($)||typeof $.operationId!=="string"||!$.operationId)throw P("publishRoster",$?.operationId??"","invalid-input","the publication needs an operation id");$=structuredClone($);let G=uZ($),B=[...Array.isArray($.remove)?$.remove:[],...Array.isArray($.finalize)?$.finalize:[]].filter((Q)=>C(Q)&&typeof Q.id==="string");for(let Q=0;;Q++){let Y=await n(Z.ctx);if(Y.status!=="ready")throw HZ(Y,"publishRoster",$.operationId);let W=new Map(B.map(({id:V})=>[V,v(Y.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(W.values())].sort())await X.acquire(r(Z,{id:V}));await X.acquire(J.providerLock??Z.providerLock);for(let V of J.extraLocks??[])await X.acquire(V);let H=await h(Z.ctx,X,z,{operation:"publishRoster",rowId:$.operationId},async(V)=>{let j=V.rows();if(B.some(({id:M})=>v(j.find((T)=>T.id===M)??{id:M})!==W.get(M)))return;let F=O4(V.config,$.operationId);if(F){if(F.planDigest!==G)throw P("publishRoster",$.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(F.phase==="cleaned")return{outcome:"already-cleaned",receipt:F};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await L4(V,F)}}g3(Z,$);let U=f3(V,$,j),q=[];for(let M of $.remove){V.assertNotStaged(M.id);let T=j.find((A)=>A.id===M.id);if(!T)throw P("publishRoster",M.id,"attribution","the removed row no longer exists");if(j5(M.id,T,M.attribution,"publishRoster"),!T.credential||M.fingerprint!==void 0&&YZ(T.credential)!==M.fingerprint)throw P("publishRoster",M.id,"attribution","the removed secret no longer matches");q.push(T)}let K=[];for(let M of $.finalize){let T=j.find((g)=>g.id===M.id),A=a(V.stateAccount(M.id)?.[E]);if(!T||T.staged?.reservation!==M.reservation||A?.staged?.reservation!==M.reservation||T.enabled)throw P("publishRoster",M.id,"row-staged","the finalized row is not disabled under this reservation");let _=V.stateAccount(M.id),I=V.rosterRow(M.id),x=_?.[d],b=x===void 0?void 0:uZ(x);if(!A?.staged||A.staged.label!==I?.label||A.staged.disabledReason!==T.disabledReason||A.staged.providerState!==b)throw P("publishRoster",M.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");j5(M.id,T,M.attribution,"publishRoster"),K.push(T)}let N=U.find((M)=>M.torn);if(N)throw P("publishRoster",$.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 M of U){if(!($.finalize.find((A)=>A.id===M.id)?.enabled??M.enabled)||M.type!=="oauth"||M.identity===void 0)continue;if(D.has(M.identity))throw P("publishRoster",M.id,"invalid-input","the final enabled roster repeats a known identity");D.add(M.identity)}for(let M of U)if(M.identity!==void 0&&M.fingerprint!==void 0&&U.some((T)=>T.id!==M.id&&T.identity!==void 0&&T.identity!==M.identity&&T.fingerprint===M.fingerprint))throw P("publishRoster",M.id,"attribution","the resulting pool gives the same secret different known identities");for(let M of K)if(M.identity!==void 0&&q.some((T)=>T.identity!==void 0&&T.identity!==M.identity&&T.fingerprint===M.fingerprint))throw P("publishRoster",M.id,"attribution","the staged secret belonged to a different known identity");await Y5(V,$.operationId,J.protect);let O={operationId:$.operationId,planDigest:G,phase:"committed",removed:q.map((M)=>({id:M.id,credentialEpoch:M.credentialEpoch??1})),finalized:$.finalize.map((M,T)=>({id:M.id,credentialEpoch:K[T]?.credentialEpoch??1,reservation:M.reservation,enabled:M.enabled}))};for(let M of $.remove)V.dropRosterRows(M.id);for(let M of $.finalize){let T=V.rosterRow(M.id);T.enabled=M.enabled;let A={...V.entry(M.id)};if(delete A.staged,M.enabled)delete A.disabledReason;else A.disabledReason=M.disabledReason;V.setEntry(M.id,A)}let L=V.roster().filter((M)=>!C(M)||typeof M.id!=="string"||j.find((T)=>T.id===M.id)?.invalid==="roster");return V.config.accounts=[...$.order.map((M)=>V.rosterRow(M)),...L],S4(V,O),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await L4(V,O)}},{completeTorn:!1});if(H)return H;if(await X.releaseAll(),Q>=1)throw P("publishRoster",$.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class R9{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor(Z,$,J,X,z){this.rt=Z,this.hook=$,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire(Z,$){if(!this.hook)return;if($==="load"){if(this.firedAtLoad.has(Z))return;this.firedAtLoad.add(Z)}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 NZ(X.lockDefaults,X.lockEnv),G={writes:0};try{let B=await h(X,z,G,{operation:"pull",rowId:Z},async(W)=>{if(W.reservation(Z)!==void 0)return;await W.completeTorn();let H=W.row(Z);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)c("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let V=W.row(Z);if(!V?.credential||V.credentialEpoch===void 0)return;return{id:Z,credential:V.credential,credentialEpoch:V.credentialEpoch,...V.identity!==void 0?{identity:V.identity}:{},reason:$}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete(Z);return}await X.hold?.("pull-before-request",Z);let Q;try{Q=await this.hook?.(B)}catch(W){throw new R({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await(J.publishQuota??((W,H,V)=>G5(J,W,H,V)))(Z,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(B){this.firedAtLoad.delete(Z);let Q=fZ(B,"pull",Z,G);if(this.onFailure)try{await this.onFailure(Z,Q)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:Z,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:Z,kind:Q.kind})}finally{await z.releaseAll()}}}var R4=100,q5=128;class E9{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=b4){this.rt=Z,this.timeoutMs=$,this.clock=J,this.logger=Z.ctx.logger??s("store")}async record(Z,$,J){try{this.assertOpen(Z),O9(Z,$);let X=structuredClone({id:Z,attribution:$,observation:J}),{row:z,result:G}=await VZ(this.rt,"pull",Z);L1(Z,X.attribution,z),_1(this.rt.ctx,Z,this.overlayRow({...z,quota:DZ(G.config,Z)?.quota}).quota,X.observation),await this.room(Z),this.assertOpen(Z);let B=this.pending.get(Z)??[];if(B.push(X),this.pending.set(Z,B),B.length>=q5)this.flushNow();else this.schedule(R4)}catch(X){throw fZ(X,"pull",Z,{writes:0})}}queued(Z){return this.pending.get(Z)?.length??0}async room(Z){if(this.queued(Z)<q5)return;let{ctx:$}=this.rt,J=Math.max(0,...$.storeLocks.map((z)=>z.timeoutMs??$.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued(Z)>=q5){this.assertOpen(Z),this.flushNow();let z=X-performance.now();if(z<=0)throw P("pull",Z,"lock-contention",`pool quota queue for ${Z} is full (${q5} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let B=()=>{clearTimeout(Q),this.wake.delete(B),G()},Q=setTimeout(B,z);this.wake.add(B)})}}assertOpen(Z){if(this.closed)throw P("pull",Z,"invalid-input","pool quota writer is closed")}overlayRow(Z){let $=Z;for(let J of this.pending.get(Z.id)??[])try{L1(Z.id,J.attribution,Z),$={...$,quota:_1(this.rt.ctx,Z.id,$.quota,J.observation),needsFirstReading:!1}}catch{}return $}overlay(Z){return Z.map(($)=>this.overlayRow($))}schedule(Z){if(this.running||this.timer||!this.pending.size||this.stopped)return;let $=this.closed?0:(this.committedAt??-1/0)+E4-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 Z=[...this.pending.values()].flat(),$={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new NZ($.lockDefaults,$.lockEnv);return this.running=(async()=>{try{await h($,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let B of Z){let{id:Q,attribution:Y,observation:W}=B,H=JSON.stringify([Q,Y.credentialEpoch,Y.identity]);try{z.assertNotStaged(Q),L1(Q,Y,z.row(Q))}catch(F){if(!(F instanceof R))throw F;if(!this.warned.has(H))this.warned.add(H),this.warn("pool quota publication dropped; account binding changed",{id:Q,kind:F.kind});continue}let V=z.entry(Q);if(!V)continue;let j;try{j=_1($,Q,V.quota,W)}catch(F){let U=`codec:${H}`;if(!this.warned.has(U))this.warned.add(U),this.warn("pool quota publication dropped; the quota codec refused it",{id:Q,error:F instanceof Error?F.message:String(F)});continue}z.setEntry(Q,{...V,quota:j,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set(Z);for(let[z,G]of this.pending){let B=G.filter((Q)=>!X.has(Q));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()):R4;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)=>{$=()=>{if(!this.pending.size)X()},this.wake.add($),$()});try{this.flush(),await Promise.race([J,new Promise((X)=>{Z=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout(Z),this.cancelTimer(),this.wake.delete($),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 h3}from"node:crypto";function b9(Z,$){if(wZ("refresh",Z,$?.staged),!$)throw P("refresh",Z,"unknown-row",`no row ${Z} in the pool`);if($.invalid)throw P("refresh",Z,"invalid-row",`row ${Z} is invalid`);if($.type!=="oauth"||$.credential?.type!=="oauth")throw P("refresh",Z,"no-credential",`row ${Z} holds no OAuth credential`);if(!$.enabled)throw P("refresh",Z,"row-disabled",`row ${Z} is disabled`);return $}function y4(Z){return P("refresh",Z,"refresh-stamp-ahead",`row ${Z}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function k4(Z,$,J,X={}){p("refresh");let{ctx:z}=Z;return l(z,"refresh",$,X.onFailure,async(G,B)=>{let{row:Q}=await VZ(Z,"refresh",$);b9($,Q);let Y=await X.refuse?.(Q);if(Y!==void 0)return{status:"refused",rowId:$,reason:Y};let W=v(Q),H;for(let U=0;;U++){await G.acquire(r(Z,{id:$,identity:W===$?void 0:W})),await G.acquire(X.providerLock??Z.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await h(z,G,{writes:0},{operation:"refresh",rowId:$},async(N)=>{let D=b9($,N.row($));if(c("refresh",D),!D.hasEntry)N.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),D=b9($,N.row($));if(v(D)!==W)return{keyNow:v(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:$,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),U>=1)throw P("refresh",$,"row-key-changed",`row ${$}'s wire identity changed twice while its lock was held`,!0);W=K.keyNow;continue}H=K;break}if(D9(H.credential.lastRefreshedAt,z.now()))throw y4($);await z.hold?.("refresh-before-provider",$),await G.assertAll();let V;try{V=await J(H.credential,H.row)}catch(U){throw new R({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw P("refresh",$,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:SZ(z.providerState,"refresh",$,V.providerState,"the provider state the provider returned"),F=await h(z,G,B,{operation:"refresh",rowId:$},async(U)=>{let q=U.row($),K=U.entry($);if(!q||q.invalid||!K||K.credentialEpoch!==H.credentialEpoch||q.identity!==H.identity)throw new R({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${$} changed credential while its refresh was in flight; the rotation is discarded`});c("refresh",q);let N=await X.refuse?.(q);if(N!==void 0)return{refused:N};let D=z.now(),O=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(D9(O,D))throw y4($);let L={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},M=q.identity!==void 0&&V.identity!==void 0&&q.identity!==V.identity?{expectedIdentity:q.identity,returnedIdentity:V.identity}:void 0,T=M?{mark:h3(),enabled:!1,reason:`${iZ}${JSON.stringify(M)}`}:void 0,A=q.identity===void 0&&V.identity?V.identity:void 0,_=await H5(Z,U,$,L,{stamp:C1(O,D),transition:T,identity:A,...j!==void 0?{providerState:O1(z.providerState,"refresh",$,q.providerState,j)}:{}});if(T!==void 0)T1(U,$,T),await U.commitConfig();let I=q.identity;if(A!==void 0)mZ(U,$,A),I=A,await U.commitConfig();return{stored:_,identity:I,contradiction:M,refused:void 0}});if(F.refused!==void 0)return{status:"refused",rowId:$,reason:F.refused};if(F.contradiction!==void 0)return{status:"identity-contradicted",rowId:$,...F.contradiction,credential:F.stored};if(X.onPersisted)try{let U=X.onPersisted;await KZ("refresh",()=>U($,F.stored))}catch(U){throw new R({operation:"refresh",rowId:$,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:$,credential:F.stored,...F.identity!==void 0?{identity:F.identity}:{}}})}import{isDeepStrictEqual as x3}from"node:util";var K5=Object.freeze(["version","accounts",y]);function y9(Z){let $={};for(let[J,X]of Object.entries(Z))if(!K5.includes(J))F5($,J,X);return $}function F5(Z,$,J){Object.defineProperty(Z,$,{value:J,enumerable:!0,writable:!0,configurable:!0})}function m3(Z,$){let J={};for(let[X,z]of Object.entries(Z))if(K5.includes(X))F5(J,X,z);else if(Object.hasOwn($,X))F5(J,X,$[X]);for(let[X,z]of Object.entries($))if(!Object.hasOwn(Z,X))F5(J,X,z);return J}function v4(Z){return new R({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:Z})}var w3=new g4;async function f4(Z){let $=async([X=Z.ctx.configPath]=[])=>{let z=await G4(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:y9(z.config)}},J=z5?await $():await w3.read([Z.ctx.configPath],$);return structuredClone(J)}async function h4(Z,$,J={}){p("updateSettings");let{ctx:X}=Z,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Y of J.extraLocks??[])await G.acquire(Y);let Q=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let Y=await n(X);if(Y.status!=="ready")throw HZ(Y,"updateSettings",void 0);let W=y9(Y.config),H=structuredClone(W),V=await KZ("updateSettings",()=>$(H)),j=V===void 0?H:V;if(!C(j))throw v4("the settings mutator must produce an object");let F=K5.filter((K)=>Object.hasOwn(j,K));if(F.length>0)throw v4(`settings cannot set the pool-owned key(s) ${F.join(", ")}`);if(x3(j,W))return{settings:W,outcome:"unchanged"};let U=m3(Y.config,j),q={operation:"updateSettings",rowId:void 0};return await AZ(X.configPath,U,{beforeRename:async()=>{await X.onStep?.("before-config-write",q),await G.assertAll()}}),B.writes++,await X.onStep?.("after-config-write",q),{settings:y9(U),outcome:"updated"}}finally{await G.releaseTo(Q)}})}var x4=new Map;function u3(Z){let $=x4.get(Z);if(!$)$={removedIds:new Set,firedAtLoad:new Set},x4.set(Z,$);return $}function m4(Z){if(Z.status==="ready")return{status:"ready",schemaVersion:vZ,rows:Z.rows};if(Z.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(Z.config.accounts)?Z.config.accounts:[]};return Z}function S1(Z){let $=u3(Z.configPath),J={...j9,...Z.lockOptions},X={provider:Z.provider,configPath:Z.configPath,statePath:Z.statePath,codec:Z.quota,...Z.providerState?{providerState:Z.providerState}:{},now:Z.now??Date.now,storeLocks:Z.storeLocks??[{name:"save",path:Z.configPath},{name:"save",path:Z.statePath}],lockDefaults:J,lockEnv:{...Z.onLockEvent?{onLockEvent:Z.onLockEvent}:{},...Z.onLockStep?{onLockStep:Z.onLockStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}},removedIds:$.removedIds,requireCredentialStamps:Z.requireCredentialStamps===!0,requireRemovedFingerprint:Z.requireRemovedFingerprint===!0,...Z.logger?{logger:Z.logger}:{},...Z.onStep?{onStep:Z.onStep}:{},...Z.hold?{hold:Z.hold}:{}},z=new R9(()=>G,Z.pull,Z.onPullFailure,$.firedAtLoad,Z.logger),G={ctx:X,providerLock:Z.providerLock??{name:`provider-${encodeURIComponent(Z.provider)}`,path:Z.statePath},rowLockOptions:Z.rowLockOptions??{},firePull:(W,H)=>z.fire(W,H)},B=Z.coalesceQuota?new E9(G,Z.quotaDrainTimeoutMs,Z.quotaCommitTimer):void 0,Q=(W,H,V)=>B?B.record(W,H,V):G5(G,W,H,V);G.publishQuota=Q;let Y=(W)=>{if(W.status==="ready"&&B)return{...W,rows:B.overlay(W.rows)};return W};return{async load(){let W=Y(await n(X));if(W.status==="ready"){for(let H of W.rows)if((H.candidate||H.torn&&H.enabled)&&H.type==="oauth"&&H.needsFirstReading)z.fire(H.id,"load")}return m4(W)},async read(){return m4(Y(await n(X)))},async initialize(W={}){return{status:await Q4(X,W.dropKeys??[])}},add:(W,H)=>q4(G,W,H),publishRoster:(W,H)=>I4(G,W,H),publication:(W)=>A4(G,W),replace:(W,H,V,j)=>F4(G,W,H,V,j),rotate:(W,H,V,j)=>K4(G,W,H,V,j),updateProviderState:(W,H,V,j)=>H4(G,W,H,V,j),disable:(W,H,V)=>M4(G,W,H,V),enable:(W,H)=>D4(G,W,H),remove:(W,H)=>P4(G,W,H),reorder:(W,H)=>C4(G,W,H),readSettings:()=>f4(G),updateSettings:(W,H)=>h4(G,W,H),recordIdentity:(W,H,V,j)=>T4(G,W,H,V,j),refresh:(W,H,V)=>k4(G,W,H,V),recordQuota:Q,close:()=>B?.close()??Promise.resolve(),dispose:()=>B?.close()??Promise.resolve(),requestReading:(W)=>z.fire(W,"admission"),pullsSettled:()=>z.settled()}}var p3=[/\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 g9(Z={}){let{redactStrings:$}=w4({...Z,extraValuePatterns:[...p3,...Z.extraValuePatterns??[]]});return(J)=>$(J)}class u extends Error{code;constructor(Z,$,J){super($,J);this.name="CommandError",this.code=Z}}var u4=/^[a-z][a-z0-9-]{0,63}$/,k9={code:"action-failed",text:"That action failed."},l3=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 I1(Z){if(Z instanceof u)return{code:u4.test(Z.code)?Z.code:k9.code,text:Z.message};if(Z instanceof R)return{code:`pool-${Z.kind}`,text:l3.has(Z.kind)?Z.message:`The account pool could not do that (${Z.kind}).`};return k9}var p4="This cannot be undone. Continue?",d3=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function c3(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");return d3.has($)||$.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function s3(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function v9(Z,$,J){if(typeof Z==="string"){let z=J.redact(Z);if(z!==Z)J.redacted.push($);return z}if(Array.isArray(Z))return Z.map((z,G)=>v9(z,`${$}[${G}]`,J));if(!s3(Z))return Z;let X={};for(let[z,G]of Object.entries(Z)){if(c3(z)){J.dropped.push(`${$}.${z}`);continue}Object.defineProperty(X,z,{value:v9(G,`${$}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function l4(Z,$,J){let X={redact:J.redact,dropped:[],redacted:[]},z=v9(Z,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:$,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:$,fields:X.redacted});return z}function a3(Z){return{value:String(Z.value),label:String(Z.label)}}function n3(Z){switch(Z.kind){case"choice":return{kind:"choice",id:Z.id,label:Z.label,choices:(Z.choices??[]).map(a3),...Z.value!==void 0?{value:Z.value}:{}};case"toggle":return{kind:"toggle",id:Z.id,label:Z.label,value:Z.value===!0};case"number":return{kind:"number",id:Z.id,label:Z.label,...Z.value!==void 0?{value:Z.value}:{},...Z.min!==void 0?{min:Z.min}:{},...Z.max!==void 0?{max:Z.max}:{},...Z.required?{required:!0}:{}};case"text":return{kind:"text",id:Z.id,label:Z.label,...Z.value!==void 0&&!Z.masked?{value:Z.value}:{},...Z.placeholder!==void 0?{placeholder:Z.placeholder}:{},...Z.masked?{masked:!0}:{},...Z.required?{required:!0}:{}}}}function f9(Z){if(Z.irreversible===!0)return{message:Z.confirm||p4,irreversible:!0};if(Z.confirm)return{message:Z.confirm,irreversible:!1};return}function d4(Z){let $=f9(Z);return{id:Z.id,label:Z.label,...Z.description!==void 0?{description:Z.description}:{},...Z.group!==void 0?{group:String(Z.group)}:{},knobs:(Z.knobs??[]).map(n3),...$?{confirm:$}:{}}}function i3(Z){return{id:Z.id,...Z.label!==void 0?{label:Z.label}:{},enabled:Z.enabled,type:Z.type,...Z.identity!==void 0?{identity:Z.identity}:{}}}function r3(Z){return{id:Z.id,label:Z.label,...Z.detail!==void 0?{detail:Z.detail}:{},...Z.group!==void 0?{group:String(Z.group)}:{},...Z.status!==void 0?{status:String(Z.status)}:{},...Z.account?{account:i3(Z.account)}:{},...Z.facts!==void 0?{facts:Z.facts}:{},actions:(Z.actions??[]).map(d4)}}function o3(Z){let{content:$}=Z;return{id:Z.id,slot:Z.slot,title:Z.title,lines:($.lines??[]).map(String),items:($.items??[]).map(r3),actions:($.actions??[]).map(d4),...$.facts!==void 0?{facts:$.facts}:{}}}function c4(Z,$,J){return{command:Z,title:$,sections:J.map(o3)}}function s4(Z,$,J,X){return l4({command:Z,menu:c4(Z,$,J)},Z,X)}function a4(Z,$,J,X,z){return l4({command:Z,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:u4.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:c4(Z,$,J)},Z,z)}var Z6="disabled from the command menu";function t3(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function IZ(Z){return t3(Z)?{...Z}:{}}function e3(Z){if(Z.status!=="ready")return[];let $=new Set;return Z.rows.filter((J)=>{if($.has(J.id))return!1;return $.add(J.id),!0})}function Z8(Z,$){return Z.label??$??Z.id}function N5(Z,$){return hZ(Z.quota)?CZ(Z.quota,$):void 0}function $6(Z,$){return`${Z} ${$}${Z===1?"":"s"}`}var R1="Actions";function $8(Z){if(Z.status==="pending-migration")return"The account pool has not been migrated yet.";if(Z.status==="error")return`The ${Z.file} file cannot be read: ${Z.reason}`;return}function n4(Z,$){switch($.outcome){case"added":return`Added ${Z}.`;case"added-disabled":return`Added ${Z}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${Z}.`;case"rotated":return`${Z} was already in the pool; its credential was updated.`;case"exists":return`${Z} was already in the pool; its credential is unchanged.`}}function i4(Z){return I1(Z).text}async function J8(Z){let{store:$}=Z,J=await $.read(),X=await $.readSettings(),z=await Z.routing?.vaultOrder?.();return{load:J,rows:e3(J),settings:X.status==="error"?{}:X.settings,...z?{vault:z}:{}}}function M5(Z,$){let J=$.accounts?.describeIdentity?$.accounts.describeIdentity(Z):Z.identity;return{account:{id:Z.id,...Z.label!==void 0?{label:Z.label}:{},enabled:Z.enabled,type:Z.type,...J!==void 0?{identity:J}:{}},name:Z8(Z,J)}}function X8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=$.rows.map((V)=>V.id),B=$8($.load),Q=$.rows.filter((V)=>V.enabled).length,Y=$.rows.map((V,j)=>{let{account:F,name:U}=M5(V,Z),q=[V.type==="api"?"API key":"OAuth",...F.identity!==void 0?[F.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),K=V.invalid?"invalid":V.enabled?"enabled":"disabled",N=[];if(!V.invalid&&V.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(V.id,Z6,z),`Disabled ${U}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(V.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(j+1)}],run:async({values:D})=>{let O=Number(D.position),L=G.filter((T)=>T!==V.id);return L.splice(O-1,0,V.id),(await J.reorder(L,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(V.id,{...z,...Z.accounts?.protect?{protect:Z.accounts.protect}:{}}),`Removed ${U}.`}}),{id:V.id,label:U,detail:q,group:"Accounts",status:K,account:F,actions:N}}),W=Z.accounts?.login,H=[];if(W&&!B)H.push({id:"add",label:W.label??"Add account",group:R1,knobs:W.knobs??[],run:async({values:V,invocation:j})=>{let F=await W.run(V,j);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 n4(F.account.label??U.id,U)}return F.completion.then(async(U)=>{if(!U){j.notify("Login cancelled.","warning");return}let q=await J.add(U,z);j.notify(n4(U.label??q.id,q))},(U)=>{j.notify(`Adding the account failed: ${i4(U)}`,"error")}).catch((U)=>{j.notify(`Adding the account failed: ${i4(U)}`,"error")}),F.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[$.rows.length===0?"No accounts yet":`${$6($.rows.length,"account")}, ${Q} enabled`],items:B?[]:Y,actions:H}}}function z8(Z,$){let J=Z.quota?.scope??"all",X=Z.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(H,V)=>{if(Z.quota?.check)await Z.quota.check(H,V);else{for(let j of H)Z.store.requestReading(j);await Z.store.pullsSettled()}},B=$.rows.filter((H)=>H.candidate),Q=B.map((H)=>{let{account:V,name:j}=M5(H,Z),F=N5(H,J);return{id:H.id,label:j,group:z,status:PZ(F,{now:X,form:"compact"}),detail:PZ(F,{now:X,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([H.id],U),`Checked quota for ${j}.`}}]}}),Y=$.rows.filter((H)=>!H.candidate).map((H)=>{let{name:V}=M5(H,Z),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",F=PZ(N5(H,J),{now:X,form:"compact"});return`${V} (${j}): ${F}`}),W=[];if(B.length>0)W.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:R1,run:async({invocation:H})=>{let V=B.map((j)=>j.id);return await G(V,H),`Checked quota for ${$6(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:$.rows.length===0?["No accounts yet"]:Y,items:Q,actions:W}}}async function G8(Z,$){try{return await Z.reorder($)}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 h9(Z){return new u("vault-invalid-order",Z)}function B8(Z){let $=Z.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>$.filter((z)=>z.id===X||z.label===X);return{ids:$.map((X)=>X.id),nameOf:(X)=>$.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let 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 h9(`"${G}" is not a vault account.`);if(B.length>1)throw h9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let Q=B[0].id;if(z.includes(Q))throw h9(`"${G}" names an account already in the order.`);z.push(Q)}return z}}}function Q8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...Z.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=IZ($.settings.routing).mode,Q=typeof B==="string"&&G.some((K)=>K.value===B)?B:"ordered",Y=t4(Q),W=$.vault?B8($.vault):void 0,H=W?W.ids:$.rows.map((K)=>K.id),V=(K)=>W?W.nameOf(K):K,j=e4(H,Y.placement,Z.routing?.formerMainId??o4),U=[`Mode: ${G.find((K)=>K.value===Q)?.label??Q}`];if(H.length>0)U.push(`${W?"Vault account order":"Roster order"}: ${H.map(V).join(", ")}`);if(Y.mode==="ordered"&&j.join()!==H.join())U.push(`Tried in order: ${j.map(V).join(", ")}`);let q=[{id:"mode",label:"Change mode",group:R1,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:Q}],run:async({values:K})=>{let N=String(K.mode);return await J.updateSettings((D)=>{D.routing={...IZ(D.routing),mode:N};return},z),`Routing mode set to ${G.find((D)=>D.value===N)?.label??N}.`}}];if(H.length>1)q.push({id:"order",label:"Set order",group:R1,knobs:[{kind:"text",id:"order",label:W?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:W?H.map(W.entryOf).join(", "):H.join(", "),required:!0}],run:async({values:K})=>{let D=String(K.order).split(W?/[,\n]+/:/[\s,]+/).map((L)=>L.trim()).filter((L)=>L.length>0),O=$.vault&&W?await G8($.vault,W.resolve(D)):await J.reorder(D,z);return O.outcome==="unchanged"?"The order is unchanged.":`Order set to ${O.ids.map(V).join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:U,actions:q}}}function W8(Z,$){if(Z.limits?.labels)return[...Z.limits.labels];let J=Z.quota?.scope??"all",X=[];for(let z of $.rows)for(let G of N5(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function Y8(Z,$){let J=Z.quota?.scope??"all",X=new Map;for(let z of $.rows)for(let G of N5(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,r4(G));return(z)=>X.get(z)??z}function H8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=IZ($.settings.killswitch),B=G.enabled===!0,Q=IZ(G.accounts),Y=W8(Z,$),W=Y8(Z,$),H=B?"on":"off",V=$.rows.map((j)=>{let{account:F,name:U}=M5(j,Z),q=IZ(Q[j.id]),K=Y.filter((N)=>typeof q[N]==="number");return{id:j.id,label:U,group:`Floors · killswitch ${H}`,status:K.length===0?"no floors":K.map((N)=>`${W(N)} ≥${q[N]}%`).join(" · "),account:F,actions:[{id:"floors",label:"Set floors",knobs:Y.map((N)=>({kind:"number",id:N,label:`Minimum % left for ${W(N)}`,min:0,max:100,...typeof q[N]==="number"?{value:q[N]}:{}})),run:async({values:N})=>{return await J.updateSettings((D)=>{let O=IZ(D.killswitch),L=IZ(O.accounts),M=IZ(L[j.id]);for(let T of Y){let A=N[T];if(typeof A==="number")M[T]=A;else if(A===null)delete M[T]}if(Object.keys(M).length>0)L[j.id]=M;else delete L[j.id];if(Object.keys(L).length>0)O.accounts=L;else delete O.accounts;D.killswitch=O;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${H}`],items:V,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:R1,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:j})=>{let F=j.enabled===!0;return await J.updateSettings((U)=>{U.killswitch={...IZ(U.killswitch),enabled:F};return},z),`Killswitch ${F?"on":"off"}.`}}]}}}async function J6(Z){let $=await J8(Z);return[X8(Z,$),z8(Z,$),Q8(Z,$),H8(Z,$)]}var V8=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),x9=["accounts","quota","routing","limits"];function X6(Z,$){let{sessionId:J}=Z,X=Z.notify.bind(Z);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X($(String(z))):X($(String(z)),G)})}function U8(Z,$){switch(Z.kind){case"choice":{let J=$??Z.value;if(typeof J==="string"&&Z.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${Z.label}.`}}case"toggle":{let J=$??Z.value;return typeof J==="boolean"?{value:J}:{problem:`${Z.label} must be on or off.`}}case"number":{let J=$===void 0?Z.value??null:$;if(J===null||J==="")return Z.required?{problem:`${Z.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${Z.label} needs a number.`};if(Z.min!==void 0&&X<Z.min)return{problem:`${Z.label} must be at least ${Z.min}.`};if(Z.max!==void 0&&X>Z.max)return{problem:`${Z.label} must be at most ${Z.max}.`};return{value:X}}case"text":{let J=$===void 0?Z.value??null:$;if(J===null||J==="")return Z.required?{problem:`${Z.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${Z.label} must be text.`}}}}function j8(Z,$){let J={};for(let X of Z){let z=$&&Object.hasOwn($,X.id)?$[X.id]:void 0,G=U8(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function q8(Z,$){let J=Z.find((z)=>z.id===$.sectionId);if(!J)return;return($.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===$.itemId)?.actions)?.find((z)=>z.id===$.actionId)}function pZ(Z){let $=Z.logger??s("commands"),J=g9(Z.redaction),X={logger:$,redact:J},z=Z.now??Date.now,G=Z.extras??[],B=Z.replace??{},Q=x9.filter((j)=>!B[j]);for(let j of x9)if(B[j]&&Z[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let Y=Z.store;if(Q.length>0&&!Y)throw Error(`a store is required for the built-in ${Q.join(", ")} section${Q.length>1?"s":""}`);let W=new Set;for(let j of G){if(V8.has(j.id)||W.has(j.id))throw Error(`extra section id ${j.id} is taken`);W.add(j.id)}async function H(j,F,U,q){try{return{id:j,slot:F,title:U.title,content:await U.build(q)}}catch(K){return $.warn("command menu section failed to build",{command:Z.command,section:j,error:J(K instanceof Error?K.message:String(K))}),{id:j,slot:F,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let F=Y&&Q.length>0?await J6({store:Y,now:z,...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.accounts?{accounts:Z.accounts}:{},...Z.quota?{quota:Z.quota}:{},...Z.routing?{routing:Z.routing}:{},...Z.limits?{limits:Z.limits}:{}}):[],U=[];for(let q of x9){let K=B[q];if(K)U.push(await H(q,q,K,j));else{let N=F.find((D)=>D.slot===q);if(N)U.push(N)}}if(Z.cache)U.push(await H("cache","cache",Z.cache,j));if(Z.diagnostics)U.push(await H("diagnostics","diagnostics",Z.diagnostics,j));for(let q of G)U.push(await H(q.id,"extra",q,j));return U}return{command:Z.command,async open(j){let F=X6(j,J);return s4(Z.command,Z.title,await V(F),X)},async apply(j,F){let U=X6(F,J),q=async(L)=>a4(Z.command,Z.title,await V(U),L,X),K=j.command===Z.command?q8(await V(U),j):void 0;if(!K)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=f9(K);if(N&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let D=j8(K.knobs??[],j.values);if("problem"in D)return q({ok:!1,code:"invalid-input",text:D.problem});let O;try{let L=await K.run({values:D.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:U});O=typeof L==="string"?{ok:!0,text:L}:{ok:L.ok,text:L.text,...L.ok?{}:{code:L.code??"refused"}}}catch(L){let M=I1(L);$.warn("command menu action failed",{command:Z.command,section:j.sectionId,action:j.actionId,code:M.code,error:J(L instanceof Error?L.message:String(L))}),O={ok:!1,...M}}return q(O)}}}function F8(Z){return Z===null||typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"&&Number.isFinite(Z)}function K8(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $=Z;if(typeof $.command!=="string"||typeof $.sectionId!=="string"||typeof $.actionId!=="string")return;if($.itemId!==void 0&&typeof $.itemId!=="string")return;if($.sessionId!==void 0&&typeof $.sessionId!=="string")return;if($.confirmed!==void 0&&typeof $.confirmed!=="boolean")return;let J={};if($.values!==void 0){if($.values===null||typeof $.values!=="object"||Array.isArray($.values))return;for(let[X,z]of Object.entries($.values)){if(!F8(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:$.command,sectionId:$.sectionId,actionId:$.actionId,...typeof $.itemId==="string"?{itemId:$.itemId}:{},...$.values!==void 0?{values:J}:{},...$.confirmed===!0?{confirmed:!0}:{},...typeof $.sessionId==="string"?{sessionId:$.sessionId}:{}}}function k(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}import{statSync as D8}from"node:fs";import{rm as B6}from"node:fs/promises";import{dirname as P8,join as N6}from"node:path";import{resolveClaustrumConnectionPath as C8}from"@cortexkit/claustrum-client";function z6(Z,$){if(!Z)return;let J=Z.rawUsedPercent??Z.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:$,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...typeof Z.windowMinutes==="number"&&Number.isFinite(Z.windowMinutes)&&Z.windowMinutes>0&&{windowMinutes:Z.windowMinutes}}}function m9(Z){if(!k(Z)||typeof Z.minor!=="number"||!Number.isSafeInteger(Z.minor)||typeof Z.exponent!=="number"||!Number.isInteger(Z.exponent))return;let $=Z.minor/10**Z.exponent;return Number.isFinite($)?$:void 0}function N8(Z){let $=m9(Z.total),J=m9(Z.remaining);if($===void 0||J===void 0||$<0||J<0)return;let X=$-J,z=Z.spendable===!1,G=$>0?X/$*100:z?100:0;return{limit:$,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...k(Z.total)&&typeof Z.total.unit==="string"&&{unit:Z.total.unit}}}function M8(Z,$){if(!k(Z))return;let J=m9(Z.remaining);return{hasCredits:!0,unlimited:typeof Z.unlimited==="boolean"?Z.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...Z.spendable===!1&&{overageLimitReached:!0},checkedAt:$}}function w9(Z,$){if(Z.insulaCreditsUnlimitedUnstated&&Z.credits&&Z.credits.balance===void 0&&k($)&&k($.credits)&&$.credits.unlimited===!0)return{...Z,credits:{...Z.credits,unlimited:!0}};return Z}function G6(Z,$){let J=z6(Z.usage?.primary,$.fetchedAt);if(!J||!Number.isFinite($.fetchedAt))return;let X=z6(Z.usage?.secondary,$.fetchedAt),z=Array.isArray(Z.spend)?Z.spend.find((W)=>k(W)&&W.id==="individual_limit"):void 0,G=k(z)?N8(z):void 0,B=Array.isArray(Z.spend)?Z.spend.find((W)=>k(W)&&W.id==="credits"):void 0,Q=M8(B,$.fetchedAt),Y=k(Z.savedResets)?Z.savedResets.availableCount:void 0;return{primary:J,...Q&&{credits:Q},...Q&&k(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function u9(Z){return`ck auth grant --principal enrolled:${Z} --selector-kind category --selector openai-native --operation read`}var p9="ck auth reclassify --from-registry";function D5(Z,$){if($===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($.grants===0)return`The vault has no grant letting ${Z} read OpenAI accounts. Grant it with \`${u9(Z)}\`.`;return`The vault's grant for ${Z} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${p9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var UZ=s("vault"),T8="openai-auth",M6={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},L8={opencode:"OpenCode",pi:"Pi"};function l9(Z){return W6(T8,Z)}function _5(Z){return N6(P8(Z),"openai-auth-vault")}function X1(Z,$){return{...H6({stateDir:Z,host:$}),rosterPath:N6(Z,`${$}-roster.json`)}}var D6=2000,SB=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],_8={"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 ${p9} 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 IB(Z,$){if(Z!=="vault-no-grant")return _8[Z];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: ${u9($)}`}function RB(Z){let $=Z.snapshot();if($===void 0)return"vault-unreachable";if($.rows.length===0){let J=Z.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function O8(Z){let $=C5(Z);return $?T5($):void 0}class P6 extends F6{#$;constructor(Z,$){super(Z);this.#$=$}refresh(){let Z=super.refresh();return this.#$(Z),Z}}class A8{host;name;paths;#$;#Z;#Q=new Map;#W=new Map;#U=new Map;#j;#J;#Y;#z;#q=!1;#F=!1;#H=Promise.withResolvers();#K="unknown";#V;constructor(Z){this.#$=Z,this.host=Z.host,this.name=l9(Z.host),this.paths=X1(Z.stateDir,Z.host),this.#Z=new P6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:M6,connect:()=>this.#C(),isCustodyActive:()=>this.#L(),...Z.reservedRouteIds?{reservedRouteIds:Z.reservedRouteIds}:{},parseIdentity:O8,insula:{provider:"codex",normalize:G6},...Z.now?{now:Z.now}:{},...Z.pollIntervalMs!==void 0?{pollIntervalMs:Z.pollIntervalMs}:{},...Z.setTimeoutImpl?{setTimeoutImpl:Z.setTimeoutImpl}:{},...Z.clearTimeoutImpl?{clearTimeoutImpl:Z.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onError:($)=>this.#X("vault roster refresh failed",$),logger:{...UZ,warn:($,J)=>{if($!=="skipped insula provider poll")UZ.warn($,J)}}},($)=>this.#_($))}#N(){return(this.#$.connectionFile??C8)()}#M(){return{connectionFile:this.#N(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(Z)=>UZ.debug("vault transport error",{errorClass:Z})}}#C(){return(this.#$.connectScoped?.()??K6(this.#M())).then((Z)=>{return this.#j=Z.insula!==void 0,Z})}#G(Z,$,J){let X=this.#U.get(Z);if(X?.source===$&&X.reason===J)return;this.#U.set(Z,{source:$,reason:J}),UZ.info("vault background quota source changed",{routeId:Z,source:$,reason:J})}#T(){return this.#$.connectEnrollment?.()??Y6(this.#M())}#X(Z,$){this.#J=TZ($),UZ.warn(Z,{host:this.host,error:this.#J})}#B(){return[this.paths.tokenPath,this.paths.statePath].map((Z)=>{try{let $=D8(Z);return`${$.ino}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let Z=this.#B(),$=await V6(this.paths,this.name);if(Z===this.#B())return this.#K=$,this.#V=Z,$;return"unreadable"}enrolled(){return this.#V!==this.#B()||this.#K!=="local"}async#L(){if(this.#V!==this.#B())await this.authority();return this.enrolled()}start(){if(this.#q||this.#F)return;this.#q=!0,this.#Z.start()}#_(Z){if(this.#z===Z)return;this.#z=Z,Z.finally(()=>{if(this.#z===Z)this.#z=void 0;this.#H.resolve()}).catch(()=>{})}#D(){return this.#Z.refresh()}firstRoster(){return this.#H.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let Z=this.#z;if(Z)await Z.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#z??this.#D()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let Z=this.#z;if(Z)await Z.catch(()=>{return});let $=await this.#D();return this.#J=void 0,$}catch(Z){return this.#X("vault roster refresh failed",Z),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}watchState(){return this.#Z.watchState()}keptReceiptState(){return this.#Z.keptReceiptState()}grantReach(){return this.#Z.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((Z)=>Z.accountIdentity!==void 0?[Z.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let Z=new Map((this.snapshot()?.rows??[]).map(($)=>[$.routeId,$]));return this.#Z.routingRows().map(($)=>{let J=Z.get($.id)?.accountIdentity;return{id:$.id,credentialId:Z.get($.id)?.credentialId,kind:$.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...$.quota!==void 0?{quota:$.quota}:{}}})}owns(Z){return(this.snapshot()?.rows??[]).some(($)=>$.routeId===Z)}async send(Z,$,J){let X=!1;try{return await this.#Z.send(Z,(z)=>{return X=!0,$(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.#Z.authorize(Z,$.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure(Z,$){if($!==401)return;try{await this.#Z.reportFailure(Z,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot(Z,$,J,X){let z=P5($,(this.#$.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#Z.recordQuota(Z,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}pollQuota(Z,$=!0){let J=this.#W.get(Z);if(J)return J;let X=this.#O(Z,$).finally(()=>{this.#W.delete(Z)});return this.#W.set(Z,X),X}async#O(Z,$){if($){await this.authority(),await this.#Z.refreshInsulaQuota();let J=(await q6(this.paths.rosterPath))?.rows.find((Q)=>Q.routeId===Z),X,z=await this.#Z.pollInsulaQuotaForRoute(Z,async()=>{this.#G(Z,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#P(Z,$);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let Q=P5(w9(z,this.routes().find((W)=>W.id===Z)?.quota),z.primary.checkedAt,!0);if(!Q)return this.#G(Z,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota(Z,J.accountIdentity,Q))return this.#G(Z,"insula",null),{ok:!0};return this.#G(Z,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#Z.lookupInsulaQuotaForRoute(Z),B=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G(Z,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#P(Z,$)}async#P(Z,$){let J,X=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send(Z,async(G,B)=>{try{let Q=$?void 0:await this.#Z.cachedInsulaQuota(B);if(Q!==void 0){let W=P5(w9(Q,this.routes().find((H)=>H.id===Z)?.quota),Q.primary.checkedAt,!0);if(!W)throw Error("unusable insula reading");return await this.#Z.recordQuota(Z,W,B),new Response(null,{status:200})}let Y=await E1({accessToken:G,fetchImpl:X,now:this.#$.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:Z,logger:UZ});return await this.recordSnapshot(Z,Y,!0,B),J=void 0,new Response(null,{status:200})}catch(Q){J=TZ(Q);let Y=Q?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw Q}},{site:"quota"}).catch((G)=>{J=TZ(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading(Z){let $=this.#Q.get(Z);if($)return $;let J=this.pollQuota(Z,!1).catch((X)=>{UZ.warn("vault quota poll failed",{routeId:Z,error:TZ(X)})}).finally(()=>{this.#Q.delete(Z)});return this.#Q.set(Z,J),J}async pollStale(Z){let $=(this.#$.now??Date.now)(),J=[];for(let X of this.routes()){let z=S8(X.quota);if(z!==void 0&&$-z<Z)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder(Z){if(await this.authority()!=="vault")throw Error("Vault order can only be changed in vault mode.");return this.#Z.reorder(Z)}async decline(Z){await this.#Z.decline(Z),UZ.info("vault account declined",{routeId:Z})}async accept(Z){await this.#Z.accept(Z),UZ.info("vault account accepted",{routeId:Z})}async status(){await this.authority();let Z;try{Z=await L5(this.paths,this.name)}catch(J){this.#X("vault enrollment state unreadable",J),Z={state:"blocked",proposedName:this.name,code:J instanceof Q6?J.kind:"unreadable-state"}}let $=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:$!==void 0,accounts:$?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){let Z=await this.#T().catch(($)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${TZ($)}. Is the vault running?`)});try{let $=new U6({client:Z,paths:this.paths,proposedName:this.name,...this.#$.now?{now:this.#$.now}:{}}),J=await $.status();if(J.state==="denied"||J.state==="blocked")await $.resetTerminal();let X=await $.reconcile();if(UZ.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{Z.close()}}waitForApproval(Z={}){return this.#Y??=(async()=>{let $=Z.sleep??((G)=>new Promise((B)=>setTimeout(B,G))),J=Z.pollIntervalMs??2000,X=Date.now()+(Z.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if(Z.onPending?.(z),Date.now()>=X)return z;await $(J),z=await this.connectStep()}return z})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){await B6(this.paths.tokenPath,{force:!0}),await B6(this.paths.statePath,{force:!0}),await this.#$.afterDisconnect?.(),await this.authority(),this.#J=void 0,UZ.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(Z){if(this.serves())j6({mode:"custody",auth:Z,provider:"openai"})}close(){this.#F=!0,this.#H.resolve(),this.#Z.close()}}function S8(Z){if(!Z)return;let $=CZ(Z).limits.map((J)=>J.checkedAt);return $.length>0?Math.max(...$):void 0}function O5(Z,$){if($.state!=="pending")return[];if(!$.requestId)return[`The vault did not take the enrollment request yet${$.retryCode?` (${$.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${$.requestId} for ${Z} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${$.requestId}`,"and let it read your OpenAI accounts with:",` ck auth grant --principal enrolled:${Z} --selector-kind category --selector ${M6.category} --operation read`]}function C6(Z,$,J){let X=`${L8[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 d9(Z,$){if(($.state==="blocked"||$.state==="unavailable")&&$.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($.state){case"approved":{let J=Z.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${Z.name}. It serves ${J} OpenAI account${J===1?"":"s"} to this host${J===0?`. ${D5(Z.name,Z.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 (${$.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...O5(Z.name,$),"Still waiting. The request stays open: run Connect again after approving it."].join(`
2
- `)};default:return{ok:!1,text:`Enrollment is ${$.state}.`}}}var c9="/backend-api/wham/rate-limit-reset-credits",I8=`https://chatgpt.com${c9}`,S6=`${c9}/consume`,R8=`https://chatgpt.com${S6}`,E8=300000,b8=60000,y8=15000,k8=60000;function z1(Z){return{configPath:Z.configPath,statePath:Z.statePath}}class ZZ extends Error{kind;cooldownUntil;constructor(Z,$,J){super($);this.name="ResetRedemptionError",this.kind=Z,this.cooldownUntil=J}}class lZ extends Error{kind;status;constructor(Z,$,J){super($);this.name="ResetCreditError",this.kind=Z,this.status=J}}function I6(Z,$,J){return{authorization:`Bearer ${Z}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":$}}function S5(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function R6(Z){if(!Z)return;return{...Z.inFlight?{inFlight:{...Z.inFlight}}:{},...Z.lastOutcome?{lastOutcome:{...Z.lastOutcome}}:{},...Z.cooldownUntil!==void 0?{cooldownUntil:Z.cooldownUntil}:{}}}function I5(Z){if(!S5(Z)||typeof Z.redeemRequestId!=="string"||Z.redeemRequestId.length===0||typeof Z.creditId!=="string"||Z.creditId.length===0||typeof Z.startedAt!=="number"||!Number.isFinite(Z.startedAt)||Z.chatgptAccountId!==void 0&&(typeof Z.chatgptAccountId!=="string"||Z.chatgptAccountId.length===0))return;return{redeemRequestId:Z.redeemRequestId,creditId:Z.creditId,startedAt:Z.startedAt,...typeof Z.chatgptAccountId==="string"?{chatgptAccountId:Z.chatgptAccountId}:{},...E6(Z.rejectedStatus)?{rejectedStatus:Z.rejectedStatus}:{},...typeof Z.unknownAnswers==="number"&&Number.isSafeInteger(Z.unknownAnswers)&&Z.unknownAnswers>0?{unknownAnswers:Z.unknownAnswers}:{}}}function E6(Z){return typeof Z==="number"&&Z>=400&&Z<500&&Z!==408&&Z!==409&&Z!==425&&Z!==429}function A5(Z){return Z.kind==="http_error"&&E6(Z.status)}function b6(Z,$){return Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$||Z.rejectedStatus!==void 0}function v8(Z,$){if(Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$)throw new ZZ("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function y6(Z){return Boolean(Z&&Object.hasOwn(Z,"inFlight"))}function k6(Z,$){return $-Z.startedAt<E8}function G1(Z,$){if(!RZ($))return;return Z.reset?.[$]}function v6(Z){if(!Z.reset)Z.reset=Object.create(null);return Z.reset}function g6(Z,$,J){if(!RZ($))return;let X=v6(Z),z=X[$]??{},G=z.lastOutcome;delete z.inFlight,z.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[$]=z}function f6(Z,$){let J=R6(Z),X=I5(Z?.inFlight);if(y6(Z)&&!X)return{kind:"corrupt",beforeState:J};if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>$)return{kind:"cooldown",beforeState:J,cooldownUntil:Z.cooldownUntil};if(X&&k6(X,$))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 g8(Z,$){if(!RZ($))return{kind:"fresh",beforeState:void 0};let J=await Z.loadAccountsFn(z1(Z));return f6(J?G1(J,$):void 0,Z.now())}async function f8(Z,$){let J;if(await Z.mutateAccountsFn((X)=>{let z=Z.now(),G=G1(X,$);if(J=f6(G,z),J.kind==="corrupt")g6(X,$,z);return X},z1(Z)),!J)throw Error("corrupt reset state mutation did not run");return J}async function h8(Z,$,J,X){if(!RZ($))return{kind:"fresh",beforeState:void 0};let z;if(await Z.mutateAccountsFn((G)=>{let B=Z.now(),Q=G1(G,$),Y=R6(Q),W=I5(Q?.inFlight);if(y6(Q)&&!W)return g6(G,$,B),z={kind:"corrupt",beforeState:Y},G;if(Q?.cooldownUntil!==void 0&&Q.cooldownUntil>B)return z={kind:"cooldown",beforeState:Y,cooldownUntil:Q.cooldownUntil},G;if(W&&k6(W,B))return z={kind:"claim",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;if(W&&!b6(W,X))return z={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;let H=R5(J);if(!H)return z={kind:"fresh",beforeState:Y},G;let V={redeemRequestId:Z.randomUUID(),creditId:H.id,startedAt:B,...X===void 0?{}:{chatgptAccountId:X}},j=v6(G);return j[$]={...Q,inFlight:V},z={kind:"claim",beforeState:Y,claim:{inFlight:V,selectedCredit:H}},G},z1(Z)),!z)throw Error("reset claim mutation did not run");return z}async function x8(Z,$,J,X,z){if(!RZ($))return;if(!n9(X.kind))return m8(Z,$,J,X,z);await Z.mutateAccountsFn((G)=>{let B=G1(G,$),Q=I5(B?.inFlight);if(!B||!Q||Q.redeemRequestId!==J.redeemRequestId||Q.creditId!==J.creditId)return G;let Y=Z.now();if(delete B.inFlight,B.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")B.cooldownUntil=Y+k8;else delete B.cooldownUntil;return G},z1(Z));return}function T6(Z,$){let J=I5(Z?.inFlight);return J&&J.redeemRequestId===$.redeemRequestId&&J.creditId===$.creditId?J:void 0}async function m8(Z,$,J,X,z){let G=A5(X)?X.status:void 0;if(!(J.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===J.rejectedStatus){let Y=await Z.loadAccountsFn(z1(Z));return T6(Y?G1(Y,$):void 0,J)}let Q;return await Z.mutateAccountsFn((Y)=>{Q=void 0;let W=G1(Y,$),H=T6(W,J);if(!W||!H)return Y;let V={...H};if(V.chatgptAccountId===void 0&&z!==void 0)V.chatgptAccountId=z;if(G===void 0)delete V.rejectedStatus,V.unknownAnswers=(H.unknownAnswers??0)+1;else if((H.unknownAnswers??0)===(J.unknownAnswers??0))V.rejectedStatus=G;return W.inFlight=V,Q=V,Y},z1(Z)),Q}function b1(Z,$){if(!Z||Z.usedPercent<100)return!1;if(!Z.resetsAt)return!0;let J=Date.parse(Z.resetsAt);return!Number.isFinite(J)||J>$}function s9(Z,$,J){if(!($||b1(Z.primary,J)||b1(Z.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function L6(Z,$){let J=Z[$];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function w8(Z){if(!S5(Z))return;let $=L6(Z,"granted_at"),J=L6(Z,"reset_type");if(typeof Z.id!=="string"||typeof Z.status!=="string"||typeof Z.expires_at!=="string"||Number.isNaN(Date.parse(Z.expires_at))||typeof Z.is_supported_by_plan!=="boolean"||$===null||J===null)return;return{id:Z.id,status:Z.status,...$===void 0?{}:{grantedAt:$},expiresAt:Z.expires_at,...J===void 0?{}:{resetType:J},isSupportedByPlan:Z.is_supported_by_plan}}async function a9(Z,$,J){let X;try{X=await Z(I8,{method:"GET",headers:I6($,c9,J),signal:AbortSignal.timeout(y8)})}catch{throw new lZ("http_error","reset credit list request failed")}if(!X.ok)throw new lZ("http_error",`reset credit list request failed: ${X.status}`,X.status);let z;try{z=await X.json()}catch{throw new lZ("invalid_response","reset credit list response was not valid JSON",X.status)}if(!S5(z))throw new lZ("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((B)=>{let Q=w8(B);return Q===void 0?[]:[Q]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function R5(Z){return[...Z].filter(h6).sort(($,J)=>Date.parse($.expiresAt)-Date.parse(J.expiresAt))[0]}function h6(Z){return Z.status==="available"&&Z.isSupportedByPlan&&Z.resetType==="codex_rate_limits"}function x6(Z){return Z.filter(h6).length}function n9(Z){return Z==="reset"||Z==="already_redeemed"||Z==="nothing_to_reset"||Z==="no_credit"}async function u8(Z,$,J,X,z){let G;try{G=await Z(R8,{method:"POST",headers:{...I6($,S6,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:X}),signal:AbortSignal.timeout(b8)})}catch(W){return{kind:"ambiguous",raw:W}}let B;try{B=await G.text()}catch(W){return G.ok?{kind:"ambiguous",raw:W}:{kind:"http_error",raw:W,status:G.status}}let Q=B,Y=!1;try{Q=JSON.parse(B),Y=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Q,status:G.status};if(!Y||!S5(Q)||!n9(Q.code))return{kind:"ambiguous",raw:Q};return{kind:Q.code,raw:Q}}function _6(Z){if(Z.kind==="cooldown")throw new ZZ("cooldown_active","reset credit redemption is cooling down",Z.cooldownUntil);throw Error(`unexpected reset state decision: ${Z.kind}`)}function O6(){throw new ZZ("expired_unreconciled","the previous reset attempt outcome is unknown")}function A6(Z,$){return{target:Z,selectedCredit:void 0,beforeState:$,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function p8(Z){if(Z.kind==="reset"||Z.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if(Z.kind==="nothing_to_reset"||Z.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(A5(Z))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 l8(Z,$){if(Z)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($)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 m6(Z,$){if(!RZ($.accountKey))throw new ZZ("invalid_account_key","the reset account key is reserved");let J=await Z.resolveTarget($.accountKey);if(J.chatgptAccountId!==$.expectedChatgptAccountId)throw new ZZ("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=J.chatgptAccountId,z=J.accountKey==="main"?void 0:X,G=await g8(Z,$.accountKey);if(G.kind==="corrupt"){if(G=await f8(Z,$.accountKey),G.kind==="corrupt")return A6(J,G.beforeState)}if(G.kind==="cooldown")_6(G);let B;if(G.kind==="claim")B=G.claim;else if(G.kind==="expired_unreconciled"&&($.retry||!b6(G.claim.inFlight,X))){if(!$.retry)O6();B=G.claim}else{if($.retry)throw new ZZ("retry_without_inflight","there is no active reset credit redemption to retry");let[j,F]=await Promise.all([Z.fetchUsage(J),a9(Z.fetchImpl,J.accessToken,z)]),U=s9(j,Z.hasActiveRateLimitMark($.accountKey),Z.now());if(!U.ok)throw new ZZ("not_exhausted",U.reason);if(!R5(F.credits))throw new ZZ("no_eligible_credit","no eligible reset credit was returned");let q=await h8(Z,$.accountKey,F.credits,X);if(q.kind==="corrupt")return A6(J,q.beforeState);if(q.kind==="cooldown")_6(q);if(q.kind==="expired_unreconciled")O6();if(q.kind!=="claim")throw new ZZ("no_eligible_credit","no eligible reset credit was available while claiming");B=q.claim}v8(B.inFlight,X);let Q=await u8(Z.fetchImpl,J.accessToken,z,B.inFlight.creditId,B.inFlight.redeemRequestId),Y,W=!1;try{Y=await x8(Z,$.accountKey,B.inFlight,Q,X)}catch{W=!0}let H=W&&n9(Q.kind),V=A5(Q)&&!W&&Y?.rejectedStatus!==void 0;return{target:J,selectedCredit:B.selectedCredit,beforeState:G.beforeState,outcome:Q,retrySafety:H?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":A5(Q)&&!V?l8(W,Y):p8(Q),...V?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}async function w6(Z){let $=[];for(let J of Z)try{$.push(...await J.run())}catch(X){$.push({code:"doctor-check-failed",message:`Check ${J.id} failed: ${X instanceof Error?X.message:String(X)}`})}return{findings:$}}function u6(Z,$){let J=[Z];if($.findings.length===0)return J.push("No problems found."),J;for(let X of $.findings){let z=X.repair?" (repair available)":"";J.push(`- ${X.message}${z}`)}return J}async function p6(Z,$){let J={applied:[],declined:[],failed:[]};for(let X of $.findings){let z=X.repair;if(!z)continue;if(!await Z.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}),Z.print(`Repair failed: ${z.label}: ${G instanceof Error?G.message:String(G)}`)}}return J}function i9(Z){let $=Z.title??"Auth doctor";return{id:"doctor",label:Z.label??"Auth doctor",hint:"check accounts and offer repairs",async run(J){let X=await w6(Z.checks);for(let B of u6($,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 p6(J,X);J.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as d8}from"node:child_process";function d6(Z,$=process.platform,J=d8){try{if($==="win32"){let z=`Start-Process '${Z.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($==="darwin"?"open":"xdg-open",[Z],{stdio:"ignore"});return X.on("error",()=>{}),X.unref(),X.pid!==void 0}catch{return!1}}function l6(Z,$){if(Z.print(""),Z.print("Open this URL in your browser and complete sign-in:"),Z.print(""),Z.print($.url),Z.print(""),$.instructions)Z.print($.instructions),Z.print("")}async function E5(Z,$){let J=new AbortController,X=await Z.begin({headless:!1,signal:J.signal});X.completion.catch(()=>{}),l6($,X);let z=!1;try{z=await(Z.openBrowser??d6)(X.url)!==!1}catch{z=!1}if(!z)J.abort(),$.print("Could not open a browser. Switching to device authorization."),$.print(""),X=await Z.begin({headless:!0}),l6($,X);return X.completion}var S={hide:"\x1B[?25l",show:"\x1B[?25h",up:(Z=1)=>`\x1B[${Z}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 r9(Z){let $=Z.toString(),J=[];for(let X=0;X<$.length;){let z=$[X];if(z==="\x1B"){let G=$.slice(X,X+3),B=G[1]==="["||G[1]==="O"?G[2]:void 0;if(B&&"ABCD".includes(B)){let Y={A:"up",B:"down",C:"right",D:"left"}[B];if(Y)J.push(Y);X+=3}else if(X+1===$.length){if(X===0)J.push("escape-start");X+=1}else if(($[X+1]==="["||$[X+1]==="O")&&X+2>=$.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 c6=`${String.fromCharCode(27)}\\[[0-9;]*m`,c8=new RegExp(c6,"g"),s8=new RegExp(`^${c6}`);function s6(Z){return Z.replace(c8,"")}function dZ(Z,$){if($<=0)return"";if(s6(Z).length<=$)return Z;let J=$>=3?"...":".".repeat($),X=Math.max(0,$-J.length),z="",G=0,B=0;while(G<Z.length&&B<X){if(Z[G]==="\x1B"){let Q=Z.slice(G).match(s8);if(Q){z+=Q[0],G+=Q[0].length;continue}}z+=Z[G],G+=1,B+=1}return z.includes("\x1B[")?`${z}${S.reset}${J}`:z+J}function o9(){return{input:process.stdin,output:process.stdout,signals:process}}function cZ(Z){return Z.input.isTTY===!0}function t9(Z,$=""){Z.output.write(`${$}
4
- `)}var a8=50;function n8(Z){if(Z==="red")return S.red;if(Z==="cyan")return S.cyan;return""}async function B1(Z,$,J){if(!cZ(Z))throw Error("Interactive select requires a TTY terminal");if($.length===0)throw Error("No menu items provided");let{input:X,output:z,signals:G}=Z,B=0,Q=null,Y=!1,W=0,H=()=>{let V=z.columns??80,j=z.rows??24,F=W;if(J.clearScreen)z.write(S.clearScreen+S.moveTo(1,1));else if(F>0)z.write(S.up(F));let U=0,q=(T)=>{z.write(`${S.clearLine}${T}
5
- `),U+=1},K=J.lines??[],N=1+(J.subtitle?3:0)+K.length+(K.length?1:0),D=Math.max(1,Math.min($.length,j-N-2-1)),O=Math.max(0,Math.min(B-Math.floor(D/2),Math.max(0,$.length-D))),L=$.slice(O,O+D);if(q(`${S.dim}┌ ${S.reset}${dZ(J.message,Math.max(1,V-4))}`),J.subtitle)q(`${S.dim}│${S.reset}`),q(`${S.cyan}◆${S.reset} ${dZ(J.subtitle,Math.max(1,V-4))}`),q("");for(let T of K)q(`${S.cyan}│${S.reset} ${dZ(T,Math.max(1,V-4))}`);if(K.length)q(`${S.cyan}│${S.reset}`);for(let T=0;T<L.length;T++){let A=L[T];if(!A)continue;let _=O+T===B,I=n8(A.color),x=I?`${_?"":S.dim}${I}${A.label}${S.reset}`:_?A.label:`${S.dim}${A.label}${S.reset}`;if(A.hint)x+=` ${S.dim}${A.hint}${S.reset}`;x=dZ(x,Math.max(1,V-8)),q(_?`${S.cyan}│${S.reset} ${S.green}●${S.reset} ${x}`:`${S.cyan}│${S.reset} ${S.dim}○${S.reset} ${x}`)}let M=L.length<$.length?` (${O+1}-${O+L.length}/${$.length})`:"";q(`${S.cyan}│${S.reset} ${S.dim}${dZ(`Up/Down to select | Enter: confirm | Esc: back${M}`,Math.max(1,V-6))}${S.reset}`),q(`${S.cyan}└${S.reset}`);for(let T=U;T<F;T++)q("");W=U};return new Promise((V)=>{let j=X.isRaw??!1,F=()=>{if(Y)return;if(Y=!0,Q)clearTimeout(Q);X.removeListener("data",K);try{X.setRawMode(j),X.pause(),z.write(S.show)}catch{}G?.removeListener("SIGINT",q),G?.removeListener("SIGTERM",q)},U=(N)=>{F(),V(N)},q=()=>U(null),K=(N)=>{for(let D of r9(N)){if(Y)break;if(Q)clearTimeout(Q),Q=null;switch(D){case"up":B=(B-1+$.length)%$.length,H();break;case"down":B=(B+1)%$.length,H();break;case"enter":U($[B]?.value??null);break;case"escape":U(null);break;case"escape-start":Q=setTimeout(()=>U(null),a8);break;default:break}}};G?.once("SIGINT",q),G?.once("SIGTERM",q);try{X.setRawMode(!0)}catch{F(),V(null);return}X.resume(),z.write(S.hide),H(),X.on("data",K)})}async function e9(Z,$,J=!1){if(!cZ(Z))return!1;return await B1(Z,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:$})??!1}function a6(Z){let $=cZ(Z);return{terminal:Z,interactive:$,print:(J)=>t9(Z,J),confirm:(J,X)=>e9(Z,J,X),select:async(J,X)=>$&&J.length>0?B1(Z,J,X):null}}function i8(Z,$){if(Z.print($.title),$.subtitle)Z.print($.subtitle);for(let J of $.status??[])Z.print(` ${J}`);Z.print(""),Z.print("Actions:");for(let J of $.actions)Z.print(J.hint?` - ${J.label} (${J.hint})`:` - ${J.label}`);return Z.print(""),Z.print("This menu needs an interactive terminal to choose an action; nothing was changed."),{status:"not-interactive"}}async function y1(Z){let $=Z.terminal??o9(),J=a6($);if(!J.interactive)return i8(J,Z);if(Z.actions.length===0)return J.print("No actions are available."),{status:"cancelled"};let X=await B1($,Z.actions.map((z)=>({label:z.label,value:z,color:z.destructive?"red":"cyan",...z.hint?{hint:z.hint}:{}})),{message:Z.title,subtitle:Z.subtitle??"Select an account action",...Z.status?{lines:Z.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 i6="disabled from the auth menu",n6=8;async function LZ(Z){let $=await Z.read();if($.status==="ready")return{rows:$.rows};if($.status==="pending-migration")return{rows:[],problem:"The account store has not been migrated yet."};return{rows:[],problem:`The account store could not be read (${$.file}: ${$.reason}).`}}async function r8(Z){let{rows:$}=await LZ(Z);return $.some((J)=>J.credential!==void 0)}function J$(Z){let $=[];if(Z.label)$.push(Z.label);if(Z.invalid)$.push(`invalid ${Z.invalid}`);else if(!Z.enabled)$.push(Z.disabledReason?`disabled: ${Z.disabledReason}`:"disabled");else $.push("enabled");if(!Z.credential&&!Z.invalid)$.push("no credential");return $.join(", ")}function o8(Z){if(Z.problem)return[Z.problem];if(Z.rows.length===0)return["No accounts yet."];let $=Z.rows.slice(0,n6).map((X)=>`${X.id}: ${J$(X)}`),J=Z.rows.length-n6;if(J>0)$.push(`... and ${J} more`);return $}function t8(Z){return Z instanceof Error?Z.message:String(Z)}async function X$(Z,$,J){if($.length===0)return Z.print("There are no accounts."),null;return Z.select($.map((X)=>({label:X.id,value:X,hint:J$(X)})),{message:J})}function e8(Z,$){let J=new Set($.map((X)=>X.id));if(Z.id&&!J.has(Z.id))return Z.id;for(let X=1;;X++){let z=`account-${X}`;if(!J.has(z))return z}}function r6(Z,$=Date.now()){let J=hZ(Z.quota)?CZ(Z.quota):void 0,X=b5(J,{now:$,form:"full"});return(X.length>0?X:[PZ(J,{now:$})]).map((z)=>` ${z}`)}function o6(Z){return{id:"add-account",label:"Add account",hint:"sign in to another account",async run($){let J=Z.login;if(!J)throw Error("No login is configured");let X=await E5(J,$),{rows:z}=await LZ(Z.store),G=(Z.newAccountId??e8)(X,z),B=await Z.store.add({id:G,credential:X.credential,...X.identity!==void 0?{identity:X.identity}:{},...X.label!==void 0?{label:X.label}:{}},Z.extraLocks?{extraLocks:Z.extraLocks}:{});if(B.outcome==="rotated")$.print(`That sign-in is already account ${B.id}; its credential was updated.`);else if(B.outcome==="added-disabled")$.print(`Added account ${B.id}, disabled: another enabled account is the same provider account.`);else if(B.outcome==="completed")$.print(`Finished adding account ${B.id}.`);else $.print(`Added account ${B.id}.`)}}}function t6(Z){return{id:"reauthenticate",label:"Re-authenticate account",hint:"sign an account in again",async run($){let J=Z.login;if(!J)throw Error("No login is configured");let{rows:X}=await LZ(Z.store),z=await X$($,X,"Re-authenticate which account?");if(!z)return;let G=await E5(J,$);if(G.identity!==void 0&&z.identity!==void 0&&G.identity!==z.identity){$.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 Z.store.replace(z.id,G.credential,B!==void 0?{identity:B}:{},Z.extraLocks?{extraLocks:Z.extraLocks}:{}),$.print(`Updated the sign-in of account ${z.id}.`)}}}function e6(Z){return{...Z.protect?{protect:Z.protect}:{},...Z.extraLocks?{extraLocks:Z.extraLocks}:{}}}function Z7(Z){return Z instanceof R&&Z.kind==="row-protected"?Z.message:void 0}function $7(Z){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run($){let{rows:J}=await LZ(Z.store),X=await X$($,J,"Remove which account?");if(!X)return;if(!await $.confirm(`Remove account ${X.id}?`)){$.print("Cancelled; nothing was changed.");return}try{await Z.store.remove(X.id,e6(Z))}catch(z){let G=Z7(z);if(G===void 0)throw z;$.print(`Account ${X.id} was kept: ${G}`);return}$.print(`Removed account ${X.id}.`)}}}function Z$(Z){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run($){let{rows:J}=await LZ(Z.store),X=await X$($,J,"Enable or disable which account?");if(!X)return;let z=Z.extraLocks?{extraLocks:Z.extraLocks}:{};if(X.enabled){await Z.store.disable(X.id,Z.disableReason??i6,z),$.print(`Disabled account ${X.id}.`);return}try{await Z.store.enable(X.id,z)}catch(G){if(G instanceof R&&G.kind==="duplicate-identity"){$.print(`Account ${X.id} stays disabled: another enabled account is the same provider account.`);return}throw G}$.print(`Enabled account ${X.id}.`)}}}function J7(Z){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run($){let J=await LZ(Z.store);if(J.problem){$.print(J.problem);return}if(J.rows.length===0)$.print("No accounts yet.");for(let X of J.rows)$.print(`${X.id}: ${J$(X)}`)}}}function $$(Z){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run($){let J=await LZ(Z.store);if(J.problem){$.print(J.problem);return}let X=new Map,z=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 Q=await z(B);await Z.store.recordQuota(B.id,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(Q){X.set(B.id,t8(Q))}}let G=await LZ(Z.store);if(G.rows.length===0)$.print("No accounts yet.");for(let B of G.rows){$.print(`${B.id}:`);let Q=X.get(B.id);if(Q)$.print(` quota check failed: ${Q}`);for(let Y of r6(B,(Z.now??Date.now)()))$.print(Y)}}}}function X7(Z){return{id:"delete-all",label:"Delete all accounts",destructive:!0,confirm:"Delete every account? Accounts the plugin keeps are not deleted.",async run($){let J=await LZ(Z.store);if(J.problem){$.print(J.problem);return}let X=[],z=[];for(let G of J.rows)try{await Z.store.remove(G.id,e6(Z)),X.push(G.id)}catch(B){let Q=Z7(B);if(Q===void 0)throw B;z.push(`${G.id} (${Q})`)}if($.print(`Deleted ${X.length} account(s).`),z.length>0)$.print(`Kept: ${z.join(", ")}.`)}}}async function z$(Z){return z7(Z,await Z.custody?.()===!0)}function z7(Z,$){let J=Z.doctor?.length?[i9({checks:Z.doctor})]:[],X=[...Z.extraActions??[]];if($)return[J7(Z),Z$(Z),$$(Z),...J,...X];return[...Z.login?[o6(Z),t6(Z)]:[],$7(Z),Z$(Z),$$(Z),...J,...X,X7(Z)]}async function Z2(Z){let $=await Z.custody?.()===!0,J=z7(Z,$),[X,z]=await Promise.all([LZ(Z.store),Z.status?.()??[]]);return y1({title:Z.title,subtitle:$?"Accounts come from the vault; select an action":"Select an account action",status:[...z,...o8(X)],actions:J,...Z.terminal?{terminal:Z.terminal}:{}})}function G7(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function B7(Z){return Z!==void 0}function $2(Z){return async($)=>{if(!B7($))return Z.login();if(!await Z.hasCredential())return Z.login($);return await Z.openMenu($),G7()}}function $Z(Z){return Z.authority!=="local"}async function i(Z){return{authority:await Z.authority(),status:await Z.status(),identities:Z.identities(),routes:new Set(Z.routes().map(($)=>$.id))}}async function y5(Z){let $;try{return await Promise.race([Promise.resolve().then(()=>Z.refresh()).then(()=>{return},(J)=>J instanceof Error?J.message:String(J)),new Promise((J)=>{$=setTimeout(()=>J("Vault roster refresh did not finish within the roster wait budget."),D6)})])}finally{clearTimeout($)}}function jZ(Z){return Z.email||Z.label||Z.routeId}function Q7(Z,$){let J=CZ(hZ(Z.quota)?Z.quota:void 0),X=b5(J,{now:$});return(X.length>0?X:[PZ(J,{now:$})]).map((z)=>` ${z}`)}var k1="Accounts are managed in the vault with ck. Disconnect to use local accounts.",sZ="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function W7(Z){let $=[...Z.label?[Z.label]:[],Z.invalid?`invalid ${Z.invalid}`:Z.enabled?"enabled":`disabled${Z.disabledReason?`: ${Z.disabledReason}`:""}`];return`${Z.id}: ${$.join(", ")}`}async function J2(Z,$){let J=await y5($),X=await i($),{status:z}=X,G=$Z(X)?void 0:await Z.store.read(),B=await z$(Z),Q=new Set(["check-quotas",...(Z.extraActions??[]).map((H)=>H.id)]),Y=B.filter((H)=>!$Z(X)||Q.has(H.id)).map((H)=>({...H,run:async(V)=>{if(!Q.has(H.id)&&$Z(await i($))){V.print(sZ);return}await $.authority(),await H.run(V)}})),W=Y.find((H)=>H.id==="check-quotas");if(W)W.run=async(H)=>{await y5($);let V=await i($),j=$Z(V)?void 0:await Z.store.read();if(!j)H.print(k1);else if(j.status!=="ready")H.print("The local account store could not be read.");else for(let q of j.rows){H.print(W7(q));try{if(Z.pollQuota&&q.credentialEpoch!==void 0){let D=await Z.pollQuota(q);await Z.store.recordQuota(q.id,{credentialEpoch:q.credentialEpoch,...q.identity!==void 0?{identity:q.identity}:{}},D)}}catch(D){H.print(` quota check failed: ${D instanceof Error?D.message:String(D)}`)}let K=await Z.store.read(),N=K.status==="ready"?K.rows.find((D)=>D.id===q.id):void 0;for(let D of Q7(N??q,(Z.now??Date.now)()))H.print(D)}let F=V.routes;for(let q of $.snapshot()?.rows??[]){if(H.print(`Vault ${jZ(q)}: ${q.enabled?q.state:"declined"}`),!F.has(q.routeId)){H.print(" quota check skipped: account is not enabled and active");continue}let K=await $.pollQuota(q.routeId);if(!K.ok)H.print(` quota check failed: ${K.error??"vault unavailable"}`);let N=$.snapshot()?.rows.find((D)=>D.routeId===q.routeId);for(let D of Q7({quota:N?.quota},(Z.now??Date.now)()))H.print(D)}let U=await $.status();if(U.lastError)H.print(`Claustrum vault unreachable: ${U.lastError}`)};return y1({title:Z.title,subtitle:"Select an account action",status:[...await Z.status?.()??[],...J?[`Last error: ${J}`]:[],...z.lastError?[`Claustrum vault unreachable: ${z.lastError}`]:[],...z.accounts.map((H)=>`Vault ${jZ(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!G?[k1]:G.status==="ready"?G.rows.map((H)=>W7(H)):["The local account store could not be read."]],actions:Y,...Z.terminal?{terminal:Z.terminal}:{}})}function Y7(Z){return k(Z)?{...Z}:{}}function G$(Z,$){let J=hZ($)?H7($.credits):void 0;return J?`${Z} · prepaid ${J}`:Z}function U7(Z,$){return{...Z,sections:Z.sections.map((J)=>J.id!=="quota"?J:{...J,items:J.items.map((X)=>X.detail===void 0?X:{...X,detail:G$(X.detail,$.get(X.id))})})}}function k5(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 Q=await Z.apply({command:Z.command,sectionId:$,...X?{itemId:X}:{},actionId:J.id,values:G,confirmed:!0},B);return{ok:Q.ok,text:Q.text,...Q.code?{code:Q.code}:{}}}}}function B$(Z,$){return new Proxy(Z,{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((W)=>({...W,label:W.label??W.id}))};if(!$)return B;let Q=await i($);if(!$Z(Q))return B;let Y=[...Q.status.accounts.map((W)=>({id:W.routeId,label:jZ(W),type:"oauth",enabled:W.enabled,identity:W.accountIdentity,quota:W.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:Y}};if(X==="readSettings")return async()=>{let G=await J.readSettings();if(G.status==="error"||!$)return G;let B=await i($),Q=Y7(G.settings.killswitch);if(!$Z(B)||!G.settings.killswitch)return G;let Y=Y7(Q.accounts);for(let W of B.status.accounts)Y[W.routeId]=v1({version:1,accounts:[],...G.settings},W.routeId);return{...G,settings:{...G.settings,killswitch:{...Q,accounts:Y}}}};let z=Reflect.get(J,X);return typeof z==="function"?z.bind(J):z}})}function Q$(Z,$,J={}){let X=pZ(Z),z=(W)=>pZ({command:Z.command,title:Z.title,store:B$(Z.store,$),accounts:Z.accounts,quota:Z.quota,limits:Z.limits,routing:{...Z.routing,formerMainId:W??"",vaultOrder:async()=>{let H=await i($);if(!$Z(H))return;return{rows:H.status.accounts.map((V)=>({id:V.routeId,label:jZ(V)})),reorder:async(V)=>{if(!$Z(await i($)))throw new u("vault-local-action",sZ);return $.reorder(V)}}}},...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.now?{now:Z.now}:{}}),G=async(W,H)=>{let V=await i($),j=$Z(V),F=V7(V.status.accounts.map((_)=>({id:_.routeId,credentialId:_.credentialId}))),U=j?z(F):X,K=(await U.open(H)).menu.sections.find((_)=>_.id===W);if(!K)throw new u("unavailable","The account menu is unavailable.");if(!j)return{lines:K.lines,items:K.items.map((_)=>({..._,actions:_.actions.map((I)=>k5(U,W,I,_.id))})),actions:K.actions.map((_)=>k5(U,W,_))};let N=new Map(V.status.accounts.map((_)=>[_.routeId,_])),D=(Z.now??Date.now)(),O=(_)=>({id:"check",label:_?"Check this account":"Check now",group:"Actions",run:async()=>{let x=[...(await i($)).routes].filter((b)=>!_||b===_);if(_&&x.length===0)throw new u("unavailable","This vault account cannot be checked right now.");for(let b of x){let g=await $.pollQuota(b);if(!g.ok)throw new u("quota-check-failed",`${b}: ${g.error??"vault unavailable"}`)}return`Checked quota for ${x.length} account${x.length===1?"":"s"}.`}});if(W==="quota"){let _=(I,x)=>PZ(CZ(I.quota,Z.quota?.scope),{now:D,form:x});return{lines:V.status.accounts.filter((I)=>!V.routes.has(I.routeId)).map((I)=>`${jZ(I)} (${I.enabled?I.state:"disabled"}): ${G$(_(I,"compact"),I.quota)}`),items:V.status.accounts.filter((I)=>V.routes.has(I.routeId)).map((I)=>({id:I.routeId,label:jZ(I),group:"Accounts",status:_(I,"compact"),detail:G$(_(I,"full"),I.quota),actions:[O(I.routeId)]})),actions:V.routes.size>0?[O()]:[]}}let L=K.items.map((_)=>{let I=N.get(_.id),x=I&&W==="accounts"?`Vault · ${I.credentialType==="oauth"?"login":"API key"} · ${I.state} · ${I.enabled?"enabled":"declined"}`:_.detail;return{id:_.id,label:_.label,detail:x,group:_.group,status:I&&W==="accounts"?I.enabled?I.state:"disabled":_.status,..._.facts?{facts:_.facts}:{},actions:I&&W!=="limits"?[]:_.actions.map((b)=>k5(U,W,b,_.id))}}),M=K.actions.filter((_)=>V.status.accounts.length>0&&(W==="limits"||W==="routing"&&(_.id==="mode"||_.id==="order"))).map((_)=>k5(U,W,_)),T=K.actions.find((_)=>_.id==="mode")?.knobs.find((_)=>_.id==="mode"),A=W==="routing"&&F===null&&T?.kind==="choice"&&(T.value==="main-first"||T.value==="fallback-first");return{lines:W==="accounts"?[...V.status.discovered?[`${V.status.accounts.length} vault account${V.status.accounts.length===1?"":"s"}`,`${V.routes.size} can route`]:["Connected · waiting for the vault's first answer"],k1]:[...K.lines,...A?["No default vault account, so this mode orders like Ordered"]:[]],items:L,actions:M}},B=pZ({...Z,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(W)=>G("accounts",W)},quota:{title:"Quota",build:(W)=>G("quota",W)},routing:{title:"Routing",build:(W)=>G("routing",W)},limits:{title:"Limits",build:(W)=>G("limits",W)}},extras:Z.extras?.map((W)=>W.id!=="reset"?W:{...W,build:async(H)=>{let V=await i($);if($Z(V))return{lines:[k1]};return W.build(H)}})}),Q=async()=>{if(!$Z(await i($)))return{menu:X,error:void 0};let W=J.refresh===!1?void 0:await y5($);return{menu:B,error:W}},Y=async(W,H)=>{let V=await W.menu.open(H);if(W.error)V.menu.sections.find((F)=>F.id==="vault")?.lines.push(`Last error: ${W.error}`);return V};return{command:Z.command,open:async(W)=>Y(await Q(),W),apply:async(W,H)=>{let V=await Q(),{menu:j}=V;if(j===B&&(W.sectionId==="accounts"||W.sectionId==="reset"||W.sectionId==="quota"&&(await i($)).routes.size===0||W.sectionId==="limits"&&W.itemId!==void 0&&!(await i($)).status.accounts.some((F)=>F.routeId===W.itemId)))return{...await Y(V,H),ok:!1,code:"vault-local-action",text:sZ};if(J.refuseApply)return{...await Y(V,H),ok:!1,...J.refuseApply};return j.apply(W,H)}}}var f1="openai",N7="OpenAI accounts",xZ="main",M7="that account is already your main account, so it was not added again",XZ=s("commands"),D7=new Set(["__proto__","constructor","prototype"]);function X2(Z,$){let J={version:1,accounts:[],killswitch:Z},X=k(Z.accounts)?Object.keys(Z.accounts):[],z={};for(let Q of new Set([xZ,...$,...X])){if(D7.has(Q))continue;let Y=v1(J,Q===xZ?void 0:Q);z[Q]={primary:Y.primary,secondary:Y.secondary}}let G=v1(J,void 0),B={...Z};return delete B.main,B.accounts=z,B.defaults={primary:G.primary,secondary:G.secondary},B.schema=h1,B}function z2(Z,$){let J=k(Z.accounts)?{...Z.accounts}:{};for(let z of new Set([xZ,...$])){if(D7.has(z)||Object.hasOwn(J,z))continue;J[z]={primary:g1.primary,secondary:g1.secondary}}let X=k(Z.defaults)?Z.defaults:{primary:g1.primary,secondary:g1.secondary};return{...Z,accounts:J,defaults:X,schema:h1}}function j7(Z,$){let J=!1;if(k(Z.cachekeep))Z.cacheKeep={...Z.cachekeep,...k(Z.cacheKeep)?Z.cacheKeep:{}},delete Z.cachekeep,J=!0;let X=Z.killswitch;if(k(X)&&X.schema!==h1)Z.killswitch=X2(X,$),J=!0;return J}async function q7(Z){let $=await Z.read();return $.status==="ready"?$.rows.map((J)=>J.id):[]}function H$(Z){let $=async()=>{let X=await Z.readSettings();if(X.status==="error")return X;let z=structuredClone(X.settings);return j7(z,await q7(Z)),{...X,settings:z}},J=async(X,z)=>{let G=await q7(Z);return Z.updateSettings(async(B)=>{j7(B,G);let Q=await X(B)??B;if(k(Q.killswitch)&&Q.killswitch.schema!==h1)Q.killswitch=z2(Q.killswitch,G);return Q},z)};return new Proxy(Z,{get(X,z){if(z==="readSettings")return $;if(z==="updateSettings")return J;let G=Reflect.get(X,z,X);return typeof G==="function"?G.bind(X):G}})}function G2(Z,$){let J=(Y,W)=>$.rowLocks?$.rowLocks(Y):W,X=(Y,W)=>{let H=J(Y,W?.extraLocks);return{...W??{},...H?{extraLocks:H}:{}}},z=(Y,W,H,V)=>Z.replace(Y,W,H,X(Y,V)),Q={add:async(Y,W)=>{let H=await Z.read(),j=(H.status==="ready"?H.rows:[]).filter((K)=>K.type==="oauth"&&!K.invalid),F=Y.identity?j.find((K)=>K.identity===Y.identity):void 0;if(F?.id===xZ)throw new u("main-account",M7);let U=F??j.find((K)=>K.id===Y.id&&K.id!==xZ);if(!U||Y.credential.type!=="oauth")return Z.add(Y,W);let q=await z(U.id,Y.credential,Y.identity!==void 0?{identity:Y.identity}:{},W?.extraLocks?{extraLocks:W.extraLocks}:void 0);return XZ.info("account signed in again",{id:U.id}),{id:q.id,outcome:"rotated",credential:q.credential,credentialEpoch:q.credentialEpoch}},replace:z,enable:(Y,W)=>Z.enable(Y,X(Y,W)),disable:(Y,W,H)=>Z.disable(Y,W,X(Y,H)),remove:(Y,W)=>Z.remove(Y,X(Y,W))};return new Proxy(Z,{get(Y,W){if(Object.hasOwn(Q,W))return Q[W];let H=Reflect.get(Y,W,Y);return typeof H==="function"?H.bind(Y):H}})}async function vQ(Z,$,J){await H$(Z).updateSettings((X)=>{J(X);return},$?{extraLocks:$}:{})}var B2=["version","accounts","commonAuthPool"];function gQ(Z,$){return async(J)=>{let X;if(await H$(Z).updateSettings((z)=>{let G={...z,version:1,accounts:[]},B=J(G)??G;X=B;let Q={...B};for(let Y of B2)delete Q[Y];return Q},$?{extraLocks:$}:{}),!X)throw Error("the settings write did not run");return X}}var Q2="migration";function F7(Z){let $=["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.",Z.length>0?"These processes still hold the move back:":"No running process holds the move back."],J={command:f1,title:N7,sections:[{id:Q2,slot:"extra",title:"Accounts are moving",lines:$,items:Z.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 Y$(J)}var W2=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function Y2(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");if(W2.has($))return!0;return $.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function W$(Z,$,J){if(Array.isArray(Z))return Z.map((z,G)=>W$(z,`${$}[${G}]`,J));if(!k(Z))return Z;let X={};for(let[z,G]of Object.entries(Z)){if(Y2(z)){J.push(`${$}.${z}`);continue}X[z]=W$(G,`${$}.${z}`,J)}return X}function Y$(Z){let $=[],J=W$(Z,"menu",$);if($.length>0)XZ.warn("credential-shaped field stripped before RPC",{fields:$});return J}function H2(Z){return{id:Z.id,credential:{type:"oauth",refresh:Z.refresh,...Z.access!==void 0?{access:Z.access}:{},...Z.expires!==void 0?{expires:Z.expires}:{}},...Z.accountId!==void 0?{identity:Z.accountId}:{},...Z.label!==void 0?{label:Z.label}:{}}}function V2(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 Z.begin({...X!==void 0?{label:X}:{},headless:z}),B=z?`Open this verification URL:
1
+ import{$c as S7,Ad as F6,Bd as K6,Cd as N6,Dd as D6,Ed as x1,Fc as fZ,Gc as w7,Hc as i5,Hd as E1,Ic as t4,Jd as M0,Kc as y5,Lc as PZ,Ld as P0,Mc as U7,Md as f1,Nc as CZ,Oc as e4,Od as g1,Pc as Z6,Pd as RZ,Qc as $6,Rd as r5,Sc as x7,Tc as m7,Uc as y4,Ud as C0,Vc as k4,Wc as f4,Yc as u7,Zc as w1,_c as p7,_d as v1,ad as I7,de as R7,ed as T5,fd as _5,fe as E7,ge as b7,ie as T0,je as _0,le as C5,oe as j7,rd as Y6,ud as H6,vd as V6,wd as U6,xd as L5,yd as j6,zd as q6}from"./index-kemp2vh4.js";import{Ae as z4,Be as AZ,Ce as G4,De as L9,Ee as QZ,Ge as t1,He as B4}from"./index-a5h82jha.js";import{Re as n7}from"./index-k7zb6wa7.js";import{Ye as p4,af as s,bf as g7,df as P$,ef as u1,ff as C$,gf as TZ}from"./index-1htk005d.js";import{jf as G5,pf as X4}from"./index-hnmbhgk4.js";class R extends Error{operation;rowId;phase;retryable;kind;committed;constructor(Z){super(Z.message??`${Z.operation} failed (${Z.kind}, ${Z.phase})`,Z.cause===void 0?void 0:{cause:Z.cause});this.name="PoolOperationError",this.operation=Z.operation,this.rowId=Z.rowId,this.phase=Z.phase,this.retryable=Z.retryable,this.kind=Z.kind,this.committed=Z.committed}}class o1 extends Error{operation;constructor(Z){super(`${Z} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=Z}}var rZ="identity-contradicted: ",j9="duplicate-identity";function kZ(Z,$,J){let X=Z.rosterRow($);if(!X)return;X.enabled=!1;let z=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");Z.setEntry($,{...z,disabledReason:G?z.disabledReason:J})}function N1(Z,$){let J=Z.rosterRow($);if(!J)return;J.enabled=!0;let X=Z.entry($);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,Z.setEntry($,z)}}function oZ(Z,$){let J=Z.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===$),X=[];for(let z of J.slice(1))kZ(Z,z.id,"duplicate-identity"),X.push(z.id);return X}function mZ(Z,$,J){let X=Z.rosterRow($);if(!X)return[];return X.accountId=J,oZ(Z,J)}import{setTimeout as I3}from"node:timers/promises";import{AsyncLocalStorage as V3}from"node:async_hooks";var l$=new V3;function p(Z){if(l$.getStore()!==void 0)throw new o1(Z)}function KZ(Z,$){return l$.run(Z,async()=>await $())}async function d$(Z,$,J,X,z){if(!$)return;try{await KZ(Z,()=>$(J,X))}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:Z,rowId:J,error:G instanceof Error?G.message:String(G)})}}var q9=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function U3(Z,$,J){let X=(B)=>{try{let Q=J.onLockEvent?.({type:B,name:Z.name,path:Z.path});if(Q&&(typeof Q==="object"||typeof Q==="function")&&"then"in Q&&typeof Q.then==="function")Promise.resolve(Q).catch(()=>{})}catch{}},z={...$,...j3(Z)},G=performance.now();for(;;){let B=await QZ({name:Z.name,path:Z.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>X("contended"),...J.onRenewalTimer?{onRenewalTimer:(W)=>J.onRenewalTimer?.({name:Z.name,path:Z.path},W)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...J.onLockStep?{onStep:(W)=>J.onLockStep?.({name:Z.name,path:Z.path},W)}:{}});if(B){X("acquired");let W={name:Z.name,path:Z.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),X("released")}};try{await W.assertOwned()}catch(H){throw await W.release(),H}return W}let Q=z.timeoutMs-(performance.now()-G);if(Q<=0)throw new t1({target:Z.path,name:Z.name,timeoutMs:z.timeoutMs});let Y=Math.floor(Math.random()*(z.retryMs+1));await new Promise((W)=>setTimeout(W,Math.min(z.retryMs+Y,Q)))}}function j3(Z){let $={};if(Z.ttlMs!==void 0)$.ttlMs=Z.ttlMs;if(Z.timeoutMs!==void 0)$.timeoutMs=Z.timeoutMs;if(Z.retryMs!==void 0)$.retryMs=Z.retryMs;if(Z.renew!==void 0)$.renew=Z.renew;if(Z.renewIntervalMs!==void 0)$.renewIntervalMs=Z.renewIntervalMs;return $}class NZ{defaults;env;held=[];constructor(Z,$){this.defaults=Z,this.env=$}async acquire(Z){let $=await U3(Z,this.defaults,this.env);return this.held.push($),await this.assertAll(),$}async assertAll(){for(let Z of this.held)await Z.assertOwned()}async releaseTo(Z){while(this.held.length>Z)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}function wZ(Z,$,J){if(J!==void 0)throw new R({operation:Z,rowId:$,kind:"row-staged",phase:Z==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${$} is reserved for roster publication`})}import{createHash as D1}from"node:crypto";var y="commonAuthPool",vZ=1,WZ="rows",e1="retiredEpochs",M1=1,F9=300000,E=y;function q3(Z){let $=JSON.parse(JSON.stringify(Z)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(C(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J($)}function uZ(Z){return D1("sha256").update(q3(Z)).digest("hex")}function c$(Z){if(!C(Z)||Object.keys(Z).length!==1||typeof Z.reservation!=="string"||!Z.reservation)return;return{reservation:Z.reservation}}function F3(Z){if(!C(Z)||typeof Z.reservation!=="string"||!Z.reservation||typeof Z.disabledReason!=="string")return;if(Object.keys(Z).some(($)=>!["reservation","label","disabledReason","providerState"].includes($)))return;if("label"in Z&&typeof Z.label!=="string")return;if("providerState"in Z&&(typeof Z.providerState!=="string"||!/^[a-f0-9]{64}$/.test(Z.providerState)))return;return Z}var d="commonAuthProviderState";function C(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var K3=new Set(["__proto__","constructor","prototype"]);function tZ(Z){if(typeof Z!=="string"||Z.length===0)return"id must be non-empty";if(Z.trim()!==Z)return"id must not carry surrounding whitespace";if(K3.has(Z))return"id is a reserved object key";return}function K9(Z){let $=typeof Z==="string"?Z.trim():"";if(!$)return!1;try{let J=new URL($);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function s$(Z){return Z.type==="oauth"?`oauth\x00${Z.refresh}`:`api\x00${Z.apiKey}`}function YZ(Z){return D1("sha256").update(s$(Z)).digest("hex")}function DZ(Z){return D1("sha256").update(`credential-stamp\x00${s$(Z)}`).digest("hex")}function OZ(Z){let $=Z.type==="oauth"?["oauth",typeof Z.access==="string"?Z.access:null,Z.refresh,typeof Z.expires==="number"&&Number.isFinite(Z.expires)?Z.expires:null]:["api",Z.apiKey,Z.baseURL.trim(),Z.authHeader??"authorization-bearer"];return D1("sha256").update(`credential-dispatch\x00${JSON.stringify($)}`).digest("hex")}function N9(Z,$,J,X={}){return{credentialEpoch:$,digest:DZ(Z),dispatch:OZ(Z),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function eZ(Z,$){let J=Z?.credentialBound?Z.credentialBound($):$;return D1("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function P1(Z,$,J,X){if(!$||J===void 0)return;if(!C(Z)||!Object.hasOwn(Z,d))return;let z=a(Z[E]);if(!z||z.providerState===void 0||z.digest!==DZ($)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function w(Z){return Number.isSafeInteger(Z)&&Z>=1}function a(Z){if(!C(Z))return;let $=Z.credentialEpoch;if(!w($))return;if(typeof Z.digest!=="string")return;if("dispatch"in Z&&typeof Z.dispatch!=="string")return;if("replace"in Z&&Z.replace!==!0)return;if("providerState"in Z&&typeof Z.providerState!=="string")return;let J="staged"in Z?F3(Z.staged):void 0;if("staged"in Z&&!J)return;let X={...J?{staged:J}:{},...typeof Z.dispatch==="string"?{dispatch:Z.dispatch}:{},...Z.replace===!0?{replace:!0}:{},...typeof Z.providerState==="string"?{providerState:Z.providerState}:{}};if(!("binding"in Z))return"dispatch"in Z||"replace"in Z||"providerState"in Z||"staged"in Z?void 0:{credentialEpoch:$,digest:Z.digest};let z=Z.binding;if(!C(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!K9(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:$,digest:Z.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 N3(Z,$,J){if(Z.identity!==J)return!1;if(Z.baseURL!==void 0&&($.type!=="api"||$.baseURL!==Z.baseURL))return!1;if(Z.authHeader!==void 0&&($.type!=="api"||$.authHeader!==Z.authHeader))return!1;return!0}function D3(Z,$,J,X){if(!Z)return"none";if(!C(X)||!Object.hasOwn(X,E))return"missing";let z=a(X[E]);if(!z)return"malformed";if(z.digest!==DZ(Z))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==$)return"mismatched";if(!z.binding||!N3(z.binding,Z,J))return"mismatched";if(z.dispatch!==OZ(Z))return"mismatched";return"bound"}function D9(Z){if(!Z.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in Z)return{status:"error",reason:"config file is not valid JSON"};let $=Z.value;if(!C($))return{status:"error",reason:"config root is not an object"};if("accounts"in $&&!Array.isArray($.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(y in $))return Array.isArray($.accounts)?{status:"pending-migration",config:$}:{status:"ready",exists:!0,config:$};let J=$[y];if(!C(J))return{status:"error",reason:`${y} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${y}.schemaVersion is invalid`};if(X>vZ)return{status:"error",reason:`${y}.schemaVersion ${X} is newer than ${vZ}`};if(WZ in J&&!C(J[WZ]))return{status:"error",reason:`${y}.${WZ} is not an object`};return{status:"ready",exists:!0,config:$}}function a$(Z){if(!Z.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in Z)return{status:"error",reason:"state file is not valid JSON"};if(!C(Z.value))return{status:"error",reason:"state root is not an object"};if("accounts"in Z.value&&!C(Z.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:Z.value}}function Z1(Z){return Array.isArray(Z.accounts)?Z.accounts:[]}function n$(Z){let $=Z[y];if(!C($))return{};let J=$[WZ];return C(J)?J:{}}function M3(Z){return C(Z.accounts)?Z.accounts:{}}function P3(Z){if(!C(Z))return"not an object";let $=tZ(Z.id);if($)return $;if(Z.type==="api")return K9(Z.baseURL)?void 0:"invalid baseURL";if(Z.type==="oauth")return;return"unknown type"}function C3(Z,$){if(!C(Z))return;let J=Z.credentialEpoch;if(!w(J))return;if("needsFirstReading"in Z&&typeof Z.needsFirstReading!=="boolean")return;if("disabledReason"in Z&&typeof Z.disabledReason!=="string")return;let X="quota"in Z&&$.decode?$.decode(Z.quota):Z.quota;if("quota"in Z&&!$.validate(X))return;if("staged"in Z&&!c$(Z.staged))return;return{credentialEpoch:J,needsFirstReading:Z.needsFirstReading===!0,...typeof Z.disabledReason==="string"?{disabledReason:Z.disabledReason}:{},..."quota"in Z?{quota:X}:{}}}function T3(Z,$){if(!C($))return;if(Z.type==="api"){let X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if(Z.corrupt===!0)return;let J=$.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof $.access==="string"?{access:$.access}:{},...typeof $.expires==="number"?{expires:$.expires}:{},...typeof $.lastRefreshedAt==="number"?{lastRefreshedAt:$.lastRefreshedAt}:{}}}function Z5(Z,$){return Z1(Z).find((J)=>C(J)&&J.id===$)}function i$(Z){if(!C(Z[y]))Z[y]={};return Z[y]}function M9(Z){let $=i$(Z);if(!C($[WZ]))$[WZ]={};return $[WZ]}function MZ(Z,$){let J=n$(Z),X=Object.hasOwn(J,$)?J[$]:void 0;return C(X)?X:void 0}function $5(Z,$,J){Object.defineProperty(M9(Z),$,{value:J,enumerable:!0,writable:!0,configurable:!0})}function r$(Z,$){let J=Z[y];if(!C(J))return;let X=J[e1];if(!C(X)||!Object.hasOwn(X,$))return;let z=X[$];return w(z)?z:void 0}function o$(Z,$){let J=MZ(Z,$)?.credentialEpoch;return w(J)?J:void 0}function J5(Z,$){return Math.max(r$(Z,$)??0,o$(Z,$)??0)+1}function t$(Z,$){let J=[...$];if(J.length===0)return;let X=i$(Z),z=C(X[e1])?X[e1]:{},G={},B=(Q,Y)=>Object.defineProperty(G,Q,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[Q,Y]of Object.entries(z))if(w(Y))B(Q,Y);for(let Q of J)B(Q,Math.max(r$(Z,Q)??0,o$(Z,Q)??1));X[e1]=G}function gZ(Z,$,J,X){let z=n$(Z),G=M3($),B=new Set,Q=[];for(let Y of Z1(Z)){let W=P3(Y),H=C(Y)&&typeof Y.id==="string"?Y.id:void 0,V=H===void 0?void 0:z[H],j=C(V)&&Object.hasOwn(V,"staged"),F=j?c$(V.staged):void 0;if(W||!C(Y)||H===void 0||B.has(H)){if(H!==void 0&&!B.has(H))B.add(H);if(H!==void 0)Q.push({id:H,type:C(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,H),candidate:!1,invalid:"roster",stamp:"none",...F?{staged:F}:{}});continue}B.add(H);let U=Y.type==="api"?"api":"oauth",q=Object.hasOwn(z,H),K=q?C3(z[H],J):void 0,N=T3(Y,G[H]),M=Y.enabled!==!1,O=K?K.credentialEpoch:q?void 0:1,_=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,D={id:H,type:U,enabled:M,needsFirstReading:K?K.needsFirstReading:U==="oauth",hasEntry:q,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},..._!==void 0?{identity:_}:{},...N?{credential:N,fingerprint:YZ(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...F?{staged:F}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},..._3(G[H],N,O,_,X),stamp:D3(N,O,_,G[H])};if(q&&!K)D.invalid="entry";else D.candidate=M&&N!==void 0&&!j;Q.push(D)}return Q}function _3(Z,$,J,X,z){if(!C(Z)||!Object.hasOwn(Z,d))return{};let G=P1(Z,$,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let B=Z[d];if(!z?.validate(B))return{providerStateDropped:"invalid"};if(eZ(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function v(Z){return Z.identity??Z.id}function C1(Z,$){if(Z===void 0||Z>$+F9)return $;return Math.max($,Z+1)}function P9(Z,$){return C1(Z,$)>$+F9}function $1(Z){let{id:$,credential:J,identity:X,label:z,addedAt:G}=Z;return{id:$,...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 e$(Z,$){if(Z.type==="api")return{apiKey:Z.apiKey};return{...Z.access!==void 0?{access:Z.access}:{},refresh:Z.refresh,...Z.expires!==void 0?{expires:Z.expires}:{},...$!==void 0?{lastRefreshedAt:$}:{}}}function Z4(Z,$){if(Z.type==="api")return{...Z,baseURL:Z.baseURL.trim(),authHeader:Z.authHeader??"authorization-bearer"};return{...Z,...$!==void 0?{lastRefreshedAt:$}:{}}}function $4(Z,$={}){if(!C(Z))return"credential must be an object";if(Z.type==="oauth"){if(typeof Z.refresh!=="string"||!Z.refresh.trim())return"oauth credential needs a refresh token";return}if(Z.type==="api"){if(typeof Z.apiKey!=="string"||!Z.apiKey.trim())return"api credential needs an api key";if(Z.apiKey.trim()!==Z.apiKey)return"api key must not carry surrounding whitespace";if(!($.baseURLOptional&&Z.baseURL===void 0)&&!K9(Z.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var X5="transition",J4="transitionMark";function L3(Z){if(!C(Z))return;let $=Z[X5];if(!C($))return;if(typeof $.mark!=="string"||$.mark.length===0)return;if($.enabled===!0)return{mark:$.mark,enabled:!0};if($.enabled===!1&&typeof $.reason==="string")return{mark:$.mark,enabled:!1,reason:$.reason};return}function T1(Z,$,J){if(J.enabled)N1(Z,$);else kZ(Z,$,J.reason??"");if(!Z.rosterRow($))return;let X=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0};if(Z.setEntry($,{...X,[J4]:J.mark}),!J.enabled)return;let z=Z.rows().find((G)=>G.id===$);if(z?.type==="oauth"&&z.identity!==void 0)oZ(Z,z.identity)}function O3(Z,$){if(Z.type!=="api")return Z;return{...Z,...$.baseURL!==void 0?{baseURL:$.baseURL}:{},...$.authHeader!==void 0?{authHeader:$.authHeader}:{}}}function A3(Z){if(!Z.binding)return!1;return Z.replace===!0||Z.dispatch===void 0}function S3(Z,$,J,X={}){let z=C($.accounts)?$.accounts:{},G=new Map;for(let B of gZ(Z,$,J)){if(B.invalid||B.staged||!B.credential)continue;let Q=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!C(Q))continue;let Y=a(Q[E]);if(!Y?.binding)continue;if(Y.digest!==DZ(B.credential))continue;let W=B.credentialEpoch??1;if(Y.credentialEpoch>W){if(!A3(Y))continue;if(X.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==OZ(O3(B.credential,Y.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===W&&Y.dispatch!==void 0&&Y.dispatch===OZ(B.credential)&&Y.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===W&&Y.binding.identity===B.identity){if(X.requireCredentialStamps&&Y.dispatch!==OZ(B.credential))continue;let H=L3(Q[E]);if(H&&MZ(Z,B.id)?.[J4]!==H.mark)G.set(B.id,{kind:"transition",transition:H})}}return G}function C9(Z,$,J,X){let G={...Z.entry($)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(rZ))delete G.disabledReason;Z.setEntry($,G);let B=Z.rosterRow($);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 T9(Z,$,J,X={}){let z=S3(Z,$,J,X);if(z.size===0)return{config:Z,torn:[]};let G=structuredClone(Z),B={rows:()=>gZ(G,$,J),rosterRow:(Q)=>Z5(G,Q),entry:(Q)=>MZ(G,Q),setEntry:(Q,Y)=>$5(G,Q,Y)};for(let[Q,Y]of z)if(Y.kind==="replace")C9(B,Q,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[Q,Y]of z)if(Y.kind==="identity")mZ(B,Q,Y.identity);else if(Y.kind==="transition")T1(B,Q,Y.transition);else if(Y.stamp.binding.identity!==void 0)oZ(B,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function _9(Z,$,J,X={}){let{config:z,torn:G}=T9(Z,$,J,X),B=gZ(z,$,J,X.providerState);for(let Q of B){if(G.includes(Q.id))Q.torn=!0,Q.candidate=!1;if(X.requireCredentialStamps&&Q.stamp!=="bound")Q.unbound=!0,Q.candidate=!1}return B}async function z5(Z){try{return await X4(Z,G5)}catch($){if($.code==="ENOENT")return;throw $}}function O9(Z){if(Z===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse(Z)}}catch($){return{exists:!0,parseError:$}}}async function Q4(Z){return D9(O9(await z5(Z)))}async function n(Z){for(let $=0;$<3;$++){let J=await z5(Z.configPath),X=await z5(Z.statePath),z=await z5(Z.configPath);if(J!==z){if($<2)await I3(2+Math.floor(Math.random()*4));continue}let G=D9(O9(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=a$(O9(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:_9(G.config,B.state,Z.codec,{requireCredentialStamps:Z.requireCredentialStamps===!0,...Z.providerState?{providerState:Z.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function HZ(Z,$,J,X="before-first-write"){if(Z.status==="error"&&Z.kind==="snapshot-contended")return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:Z.reason});return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:X,retryable:!1,kind:Z.status==="pending-migration"?"pending-migration":"load-error",message:Z.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${Z.file} file cannot be loaded: ${Z.reason}`})}class W4{ctx;snapshot;locks;progress;info;config;state;constructor(Z,$,J,X,z){this.ctx=Z,this.snapshot=$,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone($.config),this.state=structuredClone($.state)}rows(){return _9(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row(Z){return this.rows().find(($)=>$.id===Z)}reservation(Z){if(this.rosterRow(Z)){let J=this.entry(Z);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let $=this.stateAccount(Z)?.[E];return C($)&&Object.hasOwn($,"staged")?$.staged:void 0}assertNotStaged(Z){wZ(this.info.operation,Z,this.reservation(Z))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow(Z){return this.roster(),Z5(this.config,Z)}dropRosterRows(Z){let $=this.roster(),J=$.filter((X)=>!(C(X)&&X.id===Z));return this.config.accounts=J,$.length-J.length}entries(){return M9(this.config)}entry(Z){return this.entries(),MZ(this.config,Z)}setEntry(Z,$){$5(this.config,Z,$)}async completeTorn(){let{config:Z,torn:$}=T9(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if($.length===0)return;this.config=Z,await this.commitConfig({counted:!1})}stateAccount(Z){let $=C(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn($,Z)?$[Z]:void 0;return C(J)?J:void 0}dropStateAccount(Z){if(C(this.state.accounts)&&Object.hasOwn(this.state.accounts,Z))delete this.state.accounts[Z]}setStateAccount(Z,$){if(!C(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,Z,{value:$,enumerable:!0,writable:!0,configurable:!0})}async commitConfig(Z={}){let $=this.roster(),J=new Set;for(let Y of $)if(C(Y)&&typeof Y.id==="string")J.add(Y.id);let X=new Set;for(let Y of Z1(this.snapshot.config))if(C(Y)&&typeof Y.id==="string"&&!J.has(Y.id))X.add(Y.id);for(let Y of Object.keys(this.entries()))if(!J.has(Y))X.add(Y);t$(this.config,X);let z=this.entries(),G={};for(let[Y,W]of Object.entries(z))if(J.has(Y))Object.defineProperty(G,Y,{value:W,enumerable:!0,writable:!0,configurable:!0});let B=this.config[y],Q={...this.config,version:M1,accounts:$,[y]:{...B,schemaVersion:vZ,[WZ]:G}};await this.write(this.ctx.configPath,Q,"config",Z.counted??!0,Z.durable??!1,()=>{if(Z.publicationDecision)this.markPublicationDecision();for(let Y of X)this.ctx.removedIds.add(Y);this.config=Q}),this.config=Q}async commitState(Z,$={}){let J={...this.state,version:M1,accounts:C(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,$.durable??!1),this.state=J,Z)this.progress.committed=Z}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await L9(this.ctx.statePath)}catch(Z){throw new R({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:Z})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await L9(this.ctx.configPath)}async write(Z,$,J,X=!0,z=!1,G){await G4(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 Y4(Z,$){let J=new NZ(Z.lockDefaults,Z.lockEnv),X={writes:0};try{for(let Q of Z.storeLocks)await J.acquire(Q);let z=await n(Z);if(z.status==="error")throw HZ(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[Q,Y]of Object.entries(z.config))if(!$.includes(Q))G[Q]=Y;G.version=M1,G[y]={schemaVersion:vZ,[WZ]:{}};let B={operation:"initialize",rowId:void 0};return await AZ(Z.configPath,G,{beforeRename:async()=>{await Z.onStep?.("before-config-write",B),await J.assertAll()}}),X.writes++,await Z.onStep?.("after-config-write",B),"initialized"}catch(z){throw hZ(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function f(Z,$,J,X,z,G={}){let B=$.held.length;try{for(let W of Z.storeLocks)await $.acquire(W);let Q=await n(Z);if(Q.status!=="ready")throw HZ(Q,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let Y=new W4(Z,Q,$,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))Y.assertNotStaged(X.rowId);if(G.completeTorn??!0)await Y.completeTorn();return await z(Y)}finally{await $.releaseTo(B)}}function hZ(Z,$,J,X){let z=$==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if($==="publishRoster"&&X.publicationDecided)return new R({operation:$,...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:Z});if($==="publishRoster"&&Z instanceof z4)return new R({operation:$,...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:Z});if(Z instanceof R){if(Z.phase===z&&Z.rowId===J&&Z.operation===$&&Z.committed===G)return Z;return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:Z.kind==="after-persist-hook"?Z.phase:z,retryable:Z.retryable,kind:Z.kind,...Z.committed??G?{committed:Z.committed??G}:{},message:Z.message,...Z.cause!==void 0?{cause:Z.cause}:{}})}let B={operation:$,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:Z};if(Z instanceof B4)return new R({...B,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${$} lost a lease after its first write; the intermediate stays on disk`:`${$} lost a lease before writing; nothing was written`});if(Z instanceof t1)return new R({...B,retryable:!0,kind:"lock-contention",message:Z.message});return new R({...B,retryable:!1,kind:"unexpected",message:Z instanceof Error?Z.message:String(Z)})}async function l(Z,$,J,X,z){let G=new NZ(Z.lockDefaults,Z.lockEnv),B={writes:0};try{return await z(G,B)}catch(Q){let Y=hZ(Q,$,J,B);if(Y.kind!=="after-persist-hook")await d$($,X,J,Y,Z.logger);throw Y}finally{await G.releaseAll()}}function r(Z,$){return{...Z.rowLockOptions,name:`row-${encodeURIComponent(v($))}`,path:Z.ctx.statePath}}async function VZ(Z,$,J){let X=await n(Z.ctx);if(X.status!=="ready")throw HZ(X,$,J);let z=X.rows.find((W)=>W.id===J),G=MZ(X.config,J),B=X.state.accounts,Q=C(B)&&Object.hasOwn(B,J)?B[J]:void 0,Y=C(Q)?Q[E]:void 0;if(z&&!["enable","disable"].includes($)&&G&&Object.hasOwn(G,"staged"))wZ($,J,G.staged);if(!z&&C(Y)&&Object.hasOwn(Y,"staged"))wZ($,J,Y.staged);if(!z)throw e($,J);return{result:X,row:z}}function e(Z,$){return new R({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${$} in the pool`})}function c(Z,$){if($.unbound)throw P(Z,$.id,"unbound-credential",`row ${$.id}'s credential is not the one this store stamped for it (stamp ${$.stamp}); replace it with fresh material`)}function P(Z,$,J,X,z=!1){return new R({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function A9(Z,$){if(!w($?.credentialEpoch))throw P("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function _1(Z,$,J){if(!J)throw e("pull",Z);if(J.invalid)throw P("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!J.credential)throw P("pull",Z,"no-credential",`row ${Z} holds no credential`);if(c("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==$.credentialEpoch||J.identity!==$.identity)throw new R({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${Z} was issued for a credential the row no longer holds`})}function L1(Z,$,J,X){let z=Z.codec.merge(J,X);if(!Z.codec.validate(z))throw P("pull",$,"invalid-quota","the quota codec rejected the merged map");return z}async function B5(Z,$,J,X){let{ctx:z}=Z,G=new NZ(z.lockDefaults,z.lockEnv),B={writes:0};try{A9($,J),await f(z,G,B,{operation:"pull",rowId:$},async(Q)=>{Q.assertNotStaged($);let Y=Q.row($);_1($,J,Y);let W=Q.entry($);if(!W)throw e("pull",$);let H=L1(z,$,W.quota,X);Q.setEntry($,{...W,quota:H,needsFirstReading:!1}),await Q.commitConfig()},{completeTorn:!1})}catch(Q){throw hZ(Q,"pull",$,B)}finally{await G.releaseAll()}}function SZ(Z,$,J,X,z="the provider state"){if(!Z)throw P($,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 P($,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!Z.validate(G))throw P($,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function O1(Z,$,J,X,z){if(X===void 0||!Z?.merge)return{kind:"set",value:z};return{kind:"set",value:SZ(Z,$,J,Z.merge(structuredClone(X),structuredClone(z)),"the merged provider state")}}function H4(Z,$,J,X,z){let G=Z?.onReplace,B=G?G($.providerState===void 0?void 0:structuredClone($.providerState),{id:$.id,credentialEpoch:J,...$.identity!==void 0?{previousIdentity:$.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:SZ(Z,"replace",$.id,B,"the provider state onReplace returned")}}function V4(Z,$,J,X,z){if($.kind==="set")return eZ(Z,$.value);if($.kind==="clear")return;return P1(J,X?.credential,z,X?.identity)}async function U4(Z,$,J,X,z={}){p("updateProviderState");let{ctx:G}=Z,B="updateProviderState";return l(G,B,$,z.onFailure,async(Q,Y)=>{let W=G.providerState;if(!W)throw P(B,$,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw P(B,$,"invalid-input","a mutator is required");let H=C(J)?J.credentialEpoch:void 0;if(!w(H))throw P(B,$,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await VZ(Z,B,$);await Q.acquire(r(Z,V));for(let j of z.extraLocks??[])await Q.acquire(j);return f(G,Q,Y,{operation:B,rowId:$},async(j)=>{let F=j.row($);if(!F)throw e(B,$);if(v(F)!==v(V))throw P(B,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0);if(F.invalid)throw P(B,$,"invalid-row",`row ${$} failed validation`);if(!F.credential)throw P(B,$,"no-credential",`row ${$} holds no credential`);if(c(B,F),(F.credentialEpoch??1)!==H||F.identity!==J.identity)throw P(B,$,"attribution",`the provider state for ${$} was read for a credential or account the row no longer holds`,!0);let q=await S9(j,W,B,F,X);if(q.kind!=="changed")return{id:$,outcome:"unchanged",...q.kind==="unchanged"&&q.value!==void 0?{providerState:q.value}:{}};return j.setStateAccount($,q.account),await j.commitState(),q.value===void 0?{id:$,outcome:"cleared"}:{id:$,outcome:"updated",providerState:q.value}})})}var j4=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function S9(Z,$,J,X,z,G=!1){let{id:B,credential:Q}=X;if(!Q)throw P(J,B,"no-credential",`row ${B} holds no credential`);let Y=X.credentialEpoch??1,W=Z.stateAccount(B),H=W?.[E],V=a(H);if(!C(H)||!V?.binding||V.digest!==DZ(Q)||V.credentialEpoch!==Y||V.binding.identity!==X.identity)throw P(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 j=X.providerState===void 0?void 0:structuredClone(X.providerState),F=await KZ(J,()=>z(j,X));if(G&&F===j4)return{kind:"declined"};let U=F===void 0?void 0:SZ($,J,B,F,"the provider state the mutator returned"),q=W!==void 0&&Object.hasOwn(W,d);if(U===void 0?!q:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let K={...W};if(U===void 0){delete K[d];let N={...H};delete N.providerState,K[E]=N}else{K[d]=U;let N=eZ($,U);if(V.providerState!==N)K[E]={...H,providerState:N}}return{kind:"changed",...U!==void 0?{value:U}:{},account:K}}import{randomUUID as q4}from"node:crypto";async function H5(Z,$,J){if(!J)return;let X=Z.rows().map((G)=>{let{id:B,type:Q,label:Y,enabled:W,disabledReason:H,identity:V,credentialEpoch:j,stamp:F,staged:U,torn:q,invalid:K}=G;return{id:B,type:Q,label:Y,enabled:W,disabledReason:H,identity:V,credentialEpoch:j,stamp:F,staged:U,torn:q,invalid:K}}),z=await KZ(Z.info.operation,()=>J({id:$,row:X.find((G)=>G.id===$),rows:X,config:structuredClone(Z.snapshot.config)}));if(z!==void 0)throw P(Z.info.operation,$,"row-protected",z)}var R3=["access","refresh","expires","lastRefreshedAt","apiKey"];function E3(Z){return{baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function b3(Z,$,J){if(J.type!=="api")return J;let X=Z.rosterRow($);if(!C(X)){if(J.baseURL===void 0)throw P(Z.info.operation,$,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=Z.row($)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:E3(X),B=J.baseURL?.trim()??G.baseURL,Q=J.authHeader??G.authHeader;if(B!==G.baseURL||Q!==G.authHeader)throw P(Z.info.operation,$,"endpoint-mismatch",`row ${$} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:B,authHeader:Q}}function F4(Z,$,J,X){let z=Z.rosterRow($),G=Z.row($),B=X??(G?G.identity:C(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 Q5(Z,$,J,X,z={}){let G=b3($,J,X),B=$.stateAccount(J),Q=z.providerState??{kind:"keep"},Y=$.row(J)?.credentialEpoch??$.entry(J)?.credentialEpoch,W=typeof Y==="number"?Y:1,H=V4(Z.ctx.providerState,Q,B,B&&Object.hasOwn(B,d)?$.row(J):void 0,W),V=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??C1(V,Z.ctx.now()):void 0,F={...B??{}};for(let K of R3)delete F[K];if(z.clearErrors)delete F.lastRefreshError,delete F.lastQuotaRefreshError,delete F.quota;if(Q.kind==="clear")delete F[d];else if(Q.kind==="set")F[d]=Q.value;let U=Z4(G,j),q={...F,...e$(G,j),[E]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[X5]:z.transition}:{},...N9(U,W,z.binding??F4($,J,U,z.identity),{replace:z.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:U,account:q}}async function W5(Z,$,J){return Z.setStateAccount($,J.account),await Z.commitState(J.stored),J.stored}async function V5(Z,$,J,X,z={}){return W5($,J,Q5(Z,$,J,X,z))}async function y3(Z,$,J){if(!$.credential||$.stamp!=="bound")return;let X=Z.stateAccount($.id),z=P1(X,$.credential,$.credentialEpoch??1,$.identity);Z.setStateAccount($.id,{...X??{},[E]:N9($.credential,$.credentialEpoch??1,F4(Z,$.id,$.credential,J),z!==void 0?{providerState:z}:{})}),await Z.commitState()}function R9(Z,$,J){let X=Z==="add"?tZ($):void 0;if(X)throw P(Z,$,"invalid-input",X);let z=$4(J,{baseURLOptional:Z==="rotate"});if(z)throw P(Z,$,"invalid-input",z)}function U5(Z,$,J,X){if(!J)throw e(Z,$);if(J.invalid)throw P(Z,$,"invalid-row",`row ${$} failed validation`);if(X&&X.type!==J.type)throw P(Z,$,"type-mismatch",`row ${$} holds a ${J.type} credential`);return J}function X1(Z,$,J){if(J!==void 0&&!w(C(J)?J.credentialEpoch:void 0))throw P(Z,$,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function j5(Z,$,J,X){if(!J)throw e(Z,$);if(J.invalid)throw P(Z,$,"invalid-row",`row ${$} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw P(Z,$,"attribution",`the ${Z} of ${$} was issued for a credential or account the row no longer holds`,!0)}function Y5(Z,$){return P(Z,$,"identity-mismatch",`row ${$} is recorded for another account; a credential of a different account is a replacement`)}function A1(Z,$){return P(Z,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0)}function k3(Z,$,J,X){let{id:z,credential:G,identity:B}=J;if(!Z.ctx.requireCredentialStamps||$.rosterRow(z)||!J1($.state,z))return;let Q=()=>{throw P("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=$.stateAccount(z),W=a(Y?.[E]);if(!W?.binding||W.dispatch===void 0||W.replace)return Q();if(G.type==="api"&&(W.binding.baseURL===void 0||W.binding.authHeader===void 0))return Q();let H=G.type==="api"?{...G,baseURL:W.binding.baseURL,authHeader:W.binding.authHeader}:G,[V]=gZ({accounts:[$1({id:z,credential:H,identity:W.binding.identity,addedAt:0})],[y]:{rows:{[z]:{credentialEpoch:J5($.config,z)}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return Q();if(B!==void 0&&B!==V.identity)return Q();if(DZ(G)!==W.digest)return Q();if(G.type==="api"){if(G.baseURL.trim()!==W.binding.baseURL)return Q();if((G.authHeader??"authorization-bearer")!==W.binding.authHeader)return Q()}else if(OZ(G)!==W.dispatch)return Q();if(W.providerState!==void 0&&V.providerState===void 0)return Q();if(X!==void 0&&eZ(Z.ctx.providerState,X)!==W.providerState)return Q();return V}function v3(Z,$,J,X){let{id:z,credential:G,identity:B,label:Q}=J,Y=$.rosterRow(z),W=()=>{throw P("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},H=$.stateAccount(z),V=a(H?.[E]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return W();if(Y&&(Y.type!==G.type||Y.label!==Q||Y.accountId!==B))return W();if(j.reservation!==J.stage?.reservation||j.label!==Q||j.disabledReason!==J.disabled?.reason||V.binding.identity!==B)return W();let F=X===void 0?void 0:uZ(X),U=H?.[d],q=U===void 0?void 0:uZ(U);if(j.providerState!==F||j.providerState!==q)return W();if(DZ(G)!==V.digest||OZ(G)!==V.dispatch)return W();let K=Y?$.config:{accounts:[{...$1({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[y]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},N=gZ(K,$.state,Z.ctx.codec,Z.ctx.providerState).find((M)=>M.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==j.label||N.identity!==V.binding.identity||N.disabledReason!==j.disabledReason||N.staged?.reservation!==j.reservation)return W();if(Y)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if(J5($.config,z)!==V.credentialEpoch)return W();return $.roster().push({...$1({id:z,credential:G,identity:B,label:Q,addedAt:Z.ctx.now()}),enabled:!1}),$.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),$.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function K4(Z,$,J={}){p("add");let{ctx:X}=Z,{id:z,credential:G,identity:B,label:Q}=$,Y=$.stage!==void 0||$.disabled!==void 0,W=await l(X,"add",z,J.onFailure,async(H,V)=>{R9("add",z,G);let j=J.onExisting??"rotate";if($.stage!==void 0&&j==="rotate")throw P("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||$.stage!==void 0&&(Q!==void 0&&typeof Q!=="string"||B!==void 0&&(typeof B!=="string"||!B))||$.disabled!==void 0&&(!C($.disabled)||typeof $.disabled.reason!=="string")||$.stage!==void 0&&(!C($.stage)||typeof $.stage.reservation!=="string"||!$.stage.reservation||!$.disabled)||j==="stage-duplicate"&&(!$.disabled||!$.stage))throw P("add",z,"invalid-input","staging requires a reservation and a disabled reason");let F=$.providerState===void 0?void 0:SZ(X.providerState,"add",z,$.providerState);if(await H.acquire(r(Z,{id:z,identity:B})),G.type==="oauth")await H.acquire(J.providerLock??Z.providerLock);for(let U of J.extraLocks??[])await H.acquire(U);return f(X,H,V,{operation:"add",rowId:z},async(U)=>{await H5(U,z,J.protect);let q=C(U.state.accounts)?U.state.accounts:{},K=Object.entries(q).find(([b,g])=>{if(b===z||U.rosterRow(b)||!C(g))return!1;let K1=g[E];if(!C(K1)||!Object.hasOwn(K1,"staged"))return!1;return G.type==="oauth"?g.refresh===G.refresh:typeof g.apiKey==="string"&&g.apiKey.trim()===G.apiKey.trim()});if(K)throw P("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 P("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if($.stage&&j!=="rotate"&&(U.rosterRow(z)||J1(U.state,z)))return v3(Z,U,$,F);if(j==="rotate"){U.assertNotStaged(z);let b=U.rows().find((g)=>g.fingerprint===YZ(G));if(b)U.assertNotStaged(b.id)}if(j==="refuse"){let b=U.rows().find((yZ)=>yZ.fingerprint===YZ(G)||yZ.id===z&&yZ.credential),g=C(U.state.accounts)?U.state.accounts:{},K1=Object.entries(g).find(([,yZ])=>{if(!C(yZ))return!1;if(G.type==="oauth")return yZ.refresh===G.refresh;return typeof yZ.apiKey==="string"&&yZ.apiKey.trim()===G.apiKey.trim()})?.[0],p$=b?.id??K1??z;if(b||K1!==void 0||J1(U.state,z))throw P("add",p$,"credential-exists",`row ${p$} already holds this secret or id`)}if(j==="stage-duplicate"&&(U.rosterRow(z)||J1(U.state,z)))throw P("add",z,"id-exists",`row ${z} already exists`);let N=k3(Z,U,$,F),M=U.rows(),O=YZ(G),_=j==="rotate"&&!N&&M.find((b)=>b.invalid===void 0&&b.fingerprint===O);if(_){if(U.assertNotStaged(_.id),c("add",_),B!==void 0&&_.identity!==void 0&&B!==_.identity)throw Y5("add",_.id);let b=Q5(Z,U,_.id,G,{...F!==void 0?{providerState:O1(X.providerState,"add",_.id,_.providerState,F)}:{}});await U.completeTorn(),U.assertNotStaged(_.id);let g=await W5(U,_.id,b);return{id:_.id,outcome:"rotated",credential:g,credentialEpoch:_.credentialEpoch??1}}let D=M.find((b)=>b.id===z);if(D){if(D.invalid)throw P("add",z,"invalid-row",`row ${z} is invalid`);if(D.credential)throw P("add",z,"id-exists",`row ${z} already holds a credential`);if(c("add",D),D.type!==G.type)throw P("add",z,"type-mismatch",`row ${z} is a ${D.type} row`);if(B!==void 0&&D.identity!==void 0&&B!==D.identity)throw Y5("add",z);if(!D.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let b=Q5(Z,U,z,G,{clearErrors:!0,...F!==void 0?{providerState:{kind:"set",value:F}}:{}});await U.completeTorn();let g=await W5(U,z,b);if(!D.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:g,credentialEpoch:D.credentialEpoch??1}}let T=J5(U.config,z);if(!w(T))throw P("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let A=N?.identity??B;U.roster().push($1({id:z,credential:G,...A!==void 0?{identity:A}:{},...Q!==void 0?{label:Q}:{},addedAt:X.now()})),U.setEntry(z,{credentialEpoch:T,needsFirstReading:G.type==="oauth",...$.stage?{staged:{reservation:$.stage.reservation}}:{}});let L="added";if($.disabled)kZ(U,z,$.disabled.reason),L="added-disabled";if(!$.disabled&&A!==void 0&&G.type==="oauth"){if(M.find((g)=>g.invalid===void 0&&g.type==="oauth"&&g.enabled&&g.identity===A))kZ(U,z,j9),L="added-disabled"}if(N?.credential)return await U.commitConfig(),{id:z,outcome:L,credential:N.credential,credentialEpoch:N.credentialEpoch??T};U.dropStateAccount(z);let I=Q5(Z,U,z,G,{...$.stage&&$.disabled?{staged:{reservation:$.stage.reservation,disabledReason:$.disabled.reason,...Q!==void 0?{label:Q}:{},...F!==void 0?{providerState:uZ(F)}:{}}}:{},...F!==void 0?{providerState:{kind:"set",value:F}}:{}});if(j==="rotate")await U.completeTorn();let x=await W5(U,z,I);return await U.commitConfig(),{id:z,outcome:L,credential:x,credentialEpoch:T}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(W.outcome==="added"||W.outcome==="completed"))Z.firePull(W.id,"add");return W}async function N4(Z,$,J,X={},z={}){p("replace");let{ctx:G}=Z,B=await l(G,"replace",$,z.onFailure,async(Q,Y)=>{R9("replace",$,J),X1("replace",$,z.attribution);let W=X.providerState===void 0?void 0:SZ(G.providerState,"replace",$,X.providerState),{row:H}=await VZ(Z,"replace",$);if(await Q.acquire(r(Z,H)),J.type==="oauth")await Q.acquire(z.providerLock??Z.providerLock);for(let V of z.extraLocks??[])await Q.acquire(V);return f(G,Q,Y,{operation:"replace",rowId:$},async(V)=>{if(z.attribution!==void 0)j5("replace",$,V.row($),z.attribution),await V.completeTorn();let j=U5("replace",$,V.row($),J);if(v(j)!==v(H))throw A1("replace",$);let F=V.entry($)?.credentialEpoch,U=(typeof F==="number"?F:1)+1;if(!w(U))throw P("replace",$,"invalid-row",`row ${$}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let q=H4(G.providerState,j,U,X.identity,W),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(C9(V,$,U,K),X.identity!==void 0)oZ(V,X.identity);let N=await V5(Z,V,$,J,{clearErrors:!0,binding:K,providerState:q});return await V.commitConfig(),{id:$,credential:N,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")Z.firePull($,"replace");return B}async function D4(Z,$,J,X={},z={}){p("rotate");let{ctx:G}=Z;return l(G,"rotate",$,z.onFailure,async(B,Q)=>{R9("rotate",$,J),X1("rotate",$,z.attribution);let Y=X.providerState===void 0?void 0:SZ(G.providerState,"rotate",$,X.providerState),{row:W}=await VZ(Z,"rotate",$);if(await B.acquire(r(Z,W)),X.identity!==void 0&&J.type==="oauth")await B.acquire(z.providerLock??Z.providerLock);for(let H of z.extraLocks??[])await B.acquire(H);return f(G,B,Q,{operation:"rotate",rowId:$},async(H)=>{if(z.attribution!==void 0)j5("rotate",$,H.row($),z.attribution),await H.completeTorn();let V=U5("rotate",$,H.row($),J);if(v(V)!==v(W))throw A1("rotate",$);if(c("rotate",V),X.identity!==void 0&&V.identity!==void 0&&X.identity!==V.identity)throw Y5("rotate",$);let j=X.identity!==void 0&&V.identity===void 0?X.identity:void 0,F=await V5(Z,H,$,J,{identity:j,...Y!==void 0?{providerState:O1(G.providerState,"rotate",$,V.providerState,Y)}:{}}),U=!1;if(!V.hasEntry)H.setEntry($,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),U=!0;if(X.identity!==void 0&&V.identity!==X.identity)mZ(H,$,X.identity),U=!0;if(U)await H.commitConfig();return{id:$,credential:F}},{completeTorn:z.attribution===void 0})})}async function M4(Z,$,J,X,z){p($);let{ctx:G}=Z,B=G.providerState,Q=z.attribution,Y=z.providerState;return l(G,$,J,z.onFailure,async(W,H)=>{if(X1($,J,Q),Y!==void 0){if(typeof Y!=="function")throw P($,J,"invalid-input","the provider-state mutator must be a function");if(Q===void 0)throw P($,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw P($,J,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await VZ(Z,$,J);await W.acquire(r(Z,V));for(let j of z.extraLocks??[])await W.acquire(j);return f(G,W,H,{operation:$,rowId:J},async(j)=>{await H5(j,J,z.protect),j.assertNotStaged(J);let F=j.row(J),U=X.enabled?U5("enable",J,F):F;if(!U||!j.rosterRow(J))throw e($,J);if(v(U)!==v(V))throw A1($,J);if(Q!==void 0)j5($,J,U,Q);if(X.enabled&&U.disabledReason?.startsWith(rZ))throw P("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let q=!X.enabled||!U.enabled||U.disabledReason!==void 0;if(X.enabled&&q&&U.type==="oauth"){let _=U.identity===void 0?void 0:j.rows().find((D)=>D.id!==J&&D.invalid===void 0&&D.type==="oauth"&&D.enabled&&D.identity===U.identity);if(_)throw P("enable",J,"duplicate-identity",`row ${_.id} is enabled with the same identity as row ${J}`)}if(Y===void 0||B===void 0){if(await j.completeTorn(),!q)return{id:J};if(X.enabled)N1(j,J);else kZ(j,J,X.reason);return await j.commitConfig(),{id:J}}if(!U.credential)throw P($,J,"no-credential",`row ${J} holds no credential`);c($,U);let K=await S9(j,B,$,U,Y,!0);if(K.kind==="declined")return{id:J,declined:!0};await j.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(q){if(X.enabled)N1(j,J);else kZ(j,J,X.reason);await j.commitConfig()}return N}if(!q)return j.setStateAccount(J,K.account),await j.commitState(),N;let M=X.enabled?{mark:q4(),enabled:!0}:{mark:q4(),enabled:!1,reason:X.reason},O=K.account[E];return j.setStateAccount(J,{...K.account,[E]:{...O,[X5]:M}}),await j.commitState(),T1(j,J,M),await j.commitConfig(),N},{completeTorn:!1})})}function P4(Z,$,J,X={}){return M4(Z,"disable",$,{enabled:!1,reason:J},X)}function C4(Z,$,J={}){return M4(Z,"enable",$,{enabled:!0},J)}async function T4(Z,$,J={}){p("remove");let{ctx:X}=Z;return l(X,"remove",$,J.onFailure,async(z,G)=>{if(typeof $!=="string"||$.length===0)throw P("remove",$,"invalid-input","id must be non-empty");let B=J.attribution;if(X1("remove",$,B),J.staged!==void 0&&(!C(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw P("remove",$,"invalid-input","a staged removal needs a reservation");let Q=await n(X);if(Q.status!=="ready")throw HZ(Q,"remove",$);let Y=Q.rows.find((H)=>H.id===$);if(!Y&&!J1(Q.state,$))throw e("remove",$);let W=v(Y??{id:$});await z.acquire(r(Z,Y??{id:$}));for(let H of J.extraLocks??[])await z.acquire(H);return f(X,z,G,{operation:"remove",rowId:$},async(H)=>{let V=H.reservation($);if(V!==void 0){if(!C(V)||!J.staged||V.reservation!==J.staged.reservation)throw P("remove",$,"row-staged",`row ${$} is reserved for roster publication`)}else if(J.staged)throw P("remove",$,"attribution",`row ${$} is no longer reserved`);let j=H.row($),F=J1(H.state,$);if(!j&&!F)throw e("remove",$);if(v(j??{id:$})!==W)throw A1("remove",$);if(B!==void 0)if(j)q5($,j,B);else g3(Z,H,$,B);let U=J.protect;if(U){let q={row:j,config:H.snapshot.config,state:H.snapshot.state},K=await KZ("remove",()=>U($,q));if(K!==void 0)throw P("remove",$,"row-protected",K)}if(j){if(B===void 0)await H.completeTorn();H.dropRosterRows($),await H.commitConfig()}if(F)H.dropStateAccount($),await H.commitState();return{id:$,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function q5(Z,$,J,X="remove"){if(j5(X,Z,$,J),$.torn)throw P(X,Z,"attribution",`row ${Z} is between the writes of another operation; retry once it completes`,!0);if($.stamp!=="bound")throw P(X,Z,"unbound-credential",`row ${Z}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function g3(Z,$,J,X){let z=()=>P("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=$.stateAccount(J),B=a(G?.[E]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let Q;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();Q={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")Q={type:"oauth",refresh:G.refresh};else throw z();let[Y]=gZ({accounts:[$1({id:J,credential:Q,identity:B.binding.identity,addedAt:0})],[y]:{rows:{[J]:{credentialEpoch:B.credentialEpoch}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(B.credentialEpoch!==X.credentialEpoch||B.binding.identity!==X.identity)throw P("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function J1(Z,$){let J=Z.accounts;return C(J)&&Object.hasOwn(J,$)}function I9(Z){return C(Z)&&typeof Z.id==="string"?Z.id:void 0}function h3(Z,$){if(!Array.isArray($))return"ids must be an array of roster ids";let J=new Set;for(let G of Z){let B=I9(G);if(B!==void 0)J.add(B)}let X=new Set;for(let G of $){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 f3(Z,$){let J=new Map;for(let G of Z){let B=I9(G);if(B===void 0)continue;let Q=J.get(B);if(Q)Q.push(G);else J.set(B,[G])}let X=$.flatMap((G)=>J.get(G)??[]),z=0;return Z.map((G)=>I9(G)===void 0?G:X[z++])}async function _4(Z,$,J={}){p("reorder");let{ctx:X}=Z,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Q of J.extraLocks??[])await G.acquire(Q);return f(X,G,B,{operation:"reorder",rowId:void 0},async(Q)=>{let Y=Q.roster(),W=h3(Y,$);if(W)throw new R({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:W});let H=[...$],V=f3(Y,H);if(V.every((j,F)=>j===Y[F]))return{ids:H,outcome:"unchanged"};return Q.config.accounts=V,await Q.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function L4(Z,$,J,X,z={}){return p("recordIdentity"),l(Z.ctx,"recordIdentity",$,z.onFailure,async(G,B)=>{if(typeof J!=="string"||J.length===0)throw P("recordIdentity",$,"invalid-input","identity must be non-empty");let Q=C(X)?X.credentialEpoch:void 0;if(!w(Q))throw P("recordIdentity",$,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await VZ(Z,"recordIdentity",$);await G.acquire(r(Z,Y)),await G.acquire(z.providerLock??Z.providerLock);for(let W of z.extraLocks??[])await G.acquire(W);return f(Z.ctx,G,B,{operation:"recordIdentity",rowId:$},async(W)=>{let H=U5("recordIdentity",$,W.row($));if(v(H)!==v(Y))throw A1("recordIdentity",$);if(c("recordIdentity",H),(H.credentialEpoch??1)!==Q)throw P("recordIdentity",$,"attribution",`the identity for ${$} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==J)throw Y5("recordIdentity",$);if(H.identity===void 0)await y3(W,H,J);let V=mZ(W,$,J);return await W.commitConfig(),{id:$,disabled:V}})})}function A4(Z){let $=Z[y];return C($)&&C($.publications)?$.publications:{}}function S4(Z,$){let J=A4(Z);if(!Object.hasOwn(J,$))return;let X=J[$];if(!C(X)||X.operationId!==$||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)=>!C(z)||typeof z.id!=="string"||!w(z.credentialEpoch))||X.finalized.some((z)=>!C(z)||typeof z.id!=="string"||!w(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw P("publishRoster",$,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function I4(Z,$){let J=await n(Z.ctx);if(J.status!=="ready")throw HZ(J,"publishRoster",$);return S4(J.config,$)}function x3(Z,$){let J=()=>{throw P("publishRoster",$?.operationId??"","invalid-input","the publication plan is invalid")};if(!C($)||typeof $.operationId!=="string"||!$.operationId||!Array.isArray($.remove)||!Array.isArray($.finalize)||!Array.isArray($.order))J();let X=new Set;for(let z of[...$.remove,...$.finalize]){if(!C(z)||typeof z.id!=="string"||tZ(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),X1("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of $.remove)if(Z.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();for(let z of $.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))J();if($.order.some((z)=>typeof z!=="string"||tZ(z))||new Set($.order).size!==$.order.length)J()}function R4(Z,$){Z.entries();let J=Z.config[y],X={...A4(Z.config)};Object.defineProperty(X,$.operationId,{value:$,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function m3(Z,$,J){let X=new Set;for(let B of Z1(Z.config)){if(!C(B)||typeof B.id!=="string")continue;if(X.has(B.id))throw P("publishRoster",$.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(B.id)}let z=new Set($.remove.map((B)=>B.id)),G=J.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==$.order.length||$.order.some((B)=>!G.some((Q)=>Q.id===B))||G.some((B)=>!$.order.includes(B.id)))throw P("publishRoster",$.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function O4(Z,$){await Z.assertAll();for(let X of $.removed)if(a(Z.stateAccount(X.id)?.[E])?.credentialEpoch===X.credentialEpoch&&!Z.rosterRow(X.id))Z.dropStateAccount(X.id);for(let X of $.finalized){let z=Z.stateAccount(X.id),G=a(z?.[E]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let B={...z[E]};delete B.staged,Z.setStateAccount(X.id,{...z,[E]:B})}}await Z.commitState(void 0,{durable:!0});let J={...$,phase:"cleaned"};return R4(Z,J),await Z.commitConfig({durable:!0}),J}async function E4(Z,$,J={}){return p("publishRoster"),l(Z.ctx,"publishRoster",$?.operationId??"",J.onFailure,async(X,z)=>{if(!C($)||typeof $.operationId!=="string"||!$.operationId)throw P("publishRoster",$?.operationId??"","invalid-input","the publication needs an operation id");$=structuredClone($);let G=uZ($),B=[...Array.isArray($.remove)?$.remove:[],...Array.isArray($.finalize)?$.finalize:[]].filter((Q)=>C(Q)&&typeof Q.id==="string");for(let Q=0;;Q++){let Y=await n(Z.ctx);if(Y.status!=="ready")throw HZ(Y,"publishRoster",$.operationId);let W=new Map(B.map(({id:V})=>[V,v(Y.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(W.values())].sort())await X.acquire(r(Z,{id:V}));await X.acquire(J.providerLock??Z.providerLock);for(let V of J.extraLocks??[])await X.acquire(V);let H=await f(Z.ctx,X,z,{operation:"publishRoster",rowId:$.operationId},async(V)=>{let j=V.rows();if(B.some(({id:D})=>v(j.find((T)=>T.id===D)??{id:D})!==W.get(D)))return;let F=S4(V.config,$.operationId);if(F){if(F.planDigest!==G)throw P("publishRoster",$.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(F.phase==="cleaned")return{outcome:"already-cleaned",receipt:F};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await O4(V,F)}}x3(Z,$);let U=m3(V,$,j),q=[];for(let D of $.remove){V.assertNotStaged(D.id);let T=j.find((A)=>A.id===D.id);if(!T)throw P("publishRoster",D.id,"attribution","the removed row no longer exists");if(q5(D.id,T,D.attribution,"publishRoster"),!T.credential||D.fingerprint!==void 0&&YZ(T.credential)!==D.fingerprint)throw P("publishRoster",D.id,"attribution","the removed secret no longer matches");q.push(T)}let K=[];for(let D of $.finalize){let T=j.find((g)=>g.id===D.id),A=a(V.stateAccount(D.id)?.[E]);if(!T||T.staged?.reservation!==D.reservation||A?.staged?.reservation!==D.reservation||T.enabled)throw P("publishRoster",D.id,"row-staged","the finalized row is not disabled under this reservation");let L=V.stateAccount(D.id),I=V.rosterRow(D.id),x=L?.[d],b=x===void 0?void 0:uZ(x);if(!A?.staged||A.staged.label!==I?.label||A.staged.disabledReason!==T.disabledReason||A.staged.providerState!==b)throw P("publishRoster",D.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");q5(D.id,T,D.attribution,"publishRoster"),K.push(T)}let N=U.find((D)=>D.torn);if(N)throw P("publishRoster",$.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let M=new Set;for(let D of U){if(!($.finalize.find((A)=>A.id===D.id)?.enabled??D.enabled)||D.type!=="oauth"||D.identity===void 0)continue;if(M.has(D.identity))throw P("publishRoster",D.id,"invalid-input","the final enabled roster repeats a known identity");M.add(D.identity)}for(let D of U)if(D.identity!==void 0&&D.fingerprint!==void 0&&U.some((T)=>T.id!==D.id&&T.identity!==void 0&&T.identity!==D.identity&&T.fingerprint===D.fingerprint))throw P("publishRoster",D.id,"attribution","the resulting pool gives the same secret different known identities");for(let D of K)if(D.identity!==void 0&&q.some((T)=>T.identity!==void 0&&T.identity!==D.identity&&T.fingerprint===D.fingerprint))throw P("publishRoster",D.id,"attribution","the staged secret belonged to a different known identity");await H5(V,$.operationId,J.protect);let O={operationId:$.operationId,planDigest:G,phase:"committed",removed:q.map((D)=>({id:D.id,credentialEpoch:D.credentialEpoch??1})),finalized:$.finalize.map((D,T)=>({id:D.id,credentialEpoch:K[T]?.credentialEpoch??1,reservation:D.reservation,enabled:D.enabled}))};for(let D of $.remove)V.dropRosterRows(D.id);for(let D of $.finalize){let T=V.rosterRow(D.id);T.enabled=D.enabled;let A={...V.entry(D.id)};if(delete A.staged,D.enabled)delete A.disabledReason;else A.disabledReason=D.disabledReason;V.setEntry(D.id,A)}let _=V.roster().filter((D)=>!C(D)||typeof D.id!=="string"||j.find((T)=>T.id===D.id)?.invalid==="roster");return V.config.accounts=[...$.order.map((D)=>V.rosterRow(D)),..._],R4(V,O),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await O4(V,O)}},{completeTorn:!1});if(H)return H;if(await X.releaseAll(),Q>=1)throw P("publishRoster",$.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class E9{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor(Z,$,J,X,z){this.rt=Z,this.hook=$,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire(Z,$){if(!this.hook)return;if($==="load"){if(this.firedAtLoad.has(Z))return;this.firedAtLoad.add(Z)}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 NZ(X.lockDefaults,X.lockEnv),G={writes:0};try{let B=await f(X,z,G,{operation:"pull",rowId:Z},async(W)=>{if(W.reservation(Z)!==void 0)return;await W.completeTorn();let H=W.row(Z);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)c("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let V=W.row(Z);if(!V?.credential||V.credentialEpoch===void 0)return;return{id:Z,credential:V.credential,credentialEpoch:V.credentialEpoch,...V.identity!==void 0?{identity:V.identity}:{},reason:$}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete(Z);return}await X.hold?.("pull-before-request",Z);let Q;try{Q=await this.hook?.(B)}catch(W){throw new R({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await(J.publishQuota??((W,H,V)=>B5(J,W,H,V)))(Z,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(B){this.firedAtLoad.delete(Z);let Q=hZ(B,"pull",Z,G);if(this.onFailure)try{await this.onFailure(Z,Q)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:Z,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:Z,kind:Q.kind})}finally{await z.releaseAll()}}}var b4=100,F5=128;class b9{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=k4){this.rt=Z,this.timeoutMs=$,this.clock=J,this.logger=Z.ctx.logger??s("store")}async record(Z,$,J){try{this.assertOpen(Z),A9(Z,$);let X=structuredClone({id:Z,attribution:$,observation:J}),{row:z,result:G}=await VZ(this.rt,"pull",Z);_1(Z,X.attribution,z),L1(this.rt.ctx,Z,this.overlayRow({...z,quota:MZ(G.config,Z)?.quota}).quota,X.observation),await this.room(Z),this.assertOpen(Z);let B=this.pending.get(Z)??[];if(B.push(X),this.pending.set(Z,B),B.length>=F5)this.flushNow();else this.schedule(b4)}catch(X){throw hZ(X,"pull",Z,{writes:0})}}queued(Z){return this.pending.get(Z)?.length??0}async room(Z){if(this.queued(Z)<F5)return;let{ctx:$}=this.rt,J=Math.max(0,...$.storeLocks.map((z)=>z.timeoutMs??$.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued(Z)>=F5){this.assertOpen(Z),this.flushNow();let z=X-performance.now();if(z<=0)throw P("pull",Z,"lock-contention",`pool quota queue for ${Z} is full (${F5} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let B=()=>{clearTimeout(Q),this.wake.delete(B),G()},Q=setTimeout(B,z);this.wake.add(B)})}}assertOpen(Z){if(this.closed)throw P("pull",Z,"invalid-input","pool quota writer is closed")}overlayRow(Z){let $=Z;for(let J of this.pending.get(Z.id)??[])try{_1(Z.id,J.attribution,Z),$={...$,quota:L1(this.rt.ctx,Z.id,$.quota,J.observation),needsFirstReading:!1}}catch{}return $}overlay(Z){return Z.map(($)=>this.overlayRow($))}schedule(Z){if(this.running||this.timer||!this.pending.size||this.stopped)return;let $=this.closed?0:(this.committedAt??-1/0)+y4-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 Z=[...this.pending.values()].flat(),$={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new NZ($.lockDefaults,$.lockEnv);return this.running=(async()=>{try{await f($,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let B of Z){let{id:Q,attribution:Y,observation:W}=B,H=JSON.stringify([Q,Y.credentialEpoch,Y.identity]);try{z.assertNotStaged(Q),_1(Q,Y,z.row(Q))}catch(F){if(!(F instanceof R))throw F;if(!this.warned.has(H))this.warned.add(H),this.warn("pool quota publication dropped; account binding changed",{id:Q,kind:F.kind});continue}let V=z.entry(Q);if(!V)continue;let j;try{j=L1($,Q,V.quota,W)}catch(F){let U=`codec:${H}`;if(!this.warned.has(U))this.warned.add(U),this.warn("pool quota publication dropped; the quota codec refused it",{id:Q,error:F instanceof Error?F.message:String(F)});continue}z.setEntry(Q,{...V,quota:j,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set(Z);for(let[z,G]of this.pending){let B=G.filter((Q)=>!X.has(Q));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()):b4;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)=>{$=()=>{if(!this.pending.size)X()},this.wake.add($),$()});try{this.flush(),await Promise.race([J,new Promise((X)=>{Z=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout(Z),this.cancelTimer(),this.wake.delete($),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 w3}from"node:crypto";function y9(Z,$){if(wZ("refresh",Z,$?.staged),!$)throw P("refresh",Z,"unknown-row",`no row ${Z} in the pool`);if($.invalid)throw P("refresh",Z,"invalid-row",`row ${Z} is invalid`);if($.type!=="oauth"||$.credential?.type!=="oauth")throw P("refresh",Z,"no-credential",`row ${Z} holds no OAuth credential`);if(!$.enabled)throw P("refresh",Z,"row-disabled",`row ${Z} is disabled`);return $}function v4(Z){return P("refresh",Z,"refresh-stamp-ahead",`row ${Z}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function g4(Z,$,J,X={}){p("refresh");let{ctx:z}=Z;return l(z,"refresh",$,X.onFailure,async(G,B)=>{let{row:Q}=await VZ(Z,"refresh",$);y9($,Q);let Y=await X.refuse?.(Q);if(Y!==void 0)return{status:"refused",rowId:$,reason:Y};let W=v(Q),H;for(let U=0;;U++){await G.acquire(r(Z,{id:$,identity:W===$?void 0:W})),await G.acquire(X.providerLock??Z.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await f(z,G,{writes:0},{operation:"refresh",rowId:$},async(N)=>{let M=y9($,N.row($));if(c("refresh",M),!M.hasEntry)N.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),M=y9($,N.row($));if(v(M)!==W)return{keyNow:v(M)};let O=await X.refuse?.(M);if(O!==void 0)return{refused:O};return{row:M,credential:M.credential,credentialEpoch:M.credentialEpoch,identity:M.identity}});if("refused"in K)return{status:"refused",rowId:$,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),U>=1)throw P("refresh",$,"row-key-changed",`row ${$}'s wire identity changed twice while its lock was held`,!0);W=K.keyNow;continue}H=K;break}if(P9(H.credential.lastRefreshedAt,z.now()))throw v4($);await z.hold?.("refresh-before-provider",$),await G.assertAll();let V;try{V=await J(H.credential,H.row)}catch(U){throw new R({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw P("refresh",$,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:SZ(z.providerState,"refresh",$,V.providerState,"the provider state the provider returned"),F=await f(z,G,B,{operation:"refresh",rowId:$},async(U)=>{let q=U.row($),K=U.entry($);if(!q||q.invalid||!K||K.credentialEpoch!==H.credentialEpoch||q.identity!==H.identity)throw new R({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${$} changed credential while its refresh was in flight; the rotation is discarded`});c("refresh",q);let N=await X.refuse?.(q);if(N!==void 0)return{refused:N};let M=z.now(),O=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(P9(O,M))throw v4($);let _={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},D=q.identity!==void 0&&V.identity!==void 0&&q.identity!==V.identity?{expectedIdentity:q.identity,returnedIdentity:V.identity}:void 0,T=D?{mark:w3(),enabled:!1,reason:`${rZ}${JSON.stringify(D)}`}:void 0,A=q.identity===void 0&&V.identity?V.identity:void 0,L=await V5(Z,U,$,_,{stamp:C1(O,M),transition:T,identity:A,...j!==void 0?{providerState:O1(z.providerState,"refresh",$,q.providerState,j)}:{}});if(T!==void 0)T1(U,$,T),await U.commitConfig();let I=q.identity;if(A!==void 0)mZ(U,$,A),I=A,await U.commitConfig();return{stored:L,identity:I,contradiction:D,refused:void 0}});if(F.refused!==void 0)return{status:"refused",rowId:$,reason:F.refused};if(F.contradiction!==void 0)return{status:"identity-contradicted",rowId:$,...F.contradiction,credential:F.stored};if(X.onPersisted)try{let U=X.onPersisted;await KZ("refresh",()=>U($,F.stored))}catch(U){throw new R({operation:"refresh",rowId:$,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:$,credential:F.stored,...F.identity!==void 0?{identity:F.identity}:{}}})}import{isDeepStrictEqual as u3}from"node:util";var N5=Object.freeze(["version","accounts",y]);function k9(Z){let $={};for(let[J,X]of Object.entries(Z))if(!N5.includes(J))K5($,J,X);return $}function K5(Z,$,J){Object.defineProperty(Z,$,{value:J,enumerable:!0,writable:!0,configurable:!0})}function p3(Z,$){let J={};for(let[X,z]of Object.entries(Z))if(N5.includes(X))K5(J,X,z);else if(Object.hasOwn($,X))K5(J,X,$[X]);for(let[X,z]of Object.entries($))if(!Object.hasOwn(Z,X))K5(J,X,z);return J}function h4(Z){return new R({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:Z})}var l3=new f4;async function x4(Z){let $=async([X=Z.ctx.configPath]=[])=>{let z=await Q4(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:k9(z.config)}},J=G5?await $():await l3.read([Z.ctx.configPath],$);return structuredClone(J)}async function m4(Z,$,J={}){p("updateSettings");let{ctx:X}=Z,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Y of J.extraLocks??[])await G.acquire(Y);let Q=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let Y=await n(X);if(Y.status!=="ready")throw HZ(Y,"updateSettings",void 0);let W=k9(Y.config),H=structuredClone(W),V=await KZ("updateSettings",()=>$(H)),j=V===void 0?H:V;if(!C(j))throw h4("the settings mutator must produce an object");let F=N5.filter((K)=>Object.hasOwn(j,K));if(F.length>0)throw h4(`settings cannot set the pool-owned key(s) ${F.join(", ")}`);if(u3(j,W))return{settings:W,outcome:"unchanged"};let U=p3(Y.config,j),q={operation:"updateSettings",rowId:void 0};return await AZ(X.configPath,U,{beforeRename:async()=>{await X.onStep?.("before-config-write",q),await G.assertAll()}}),B.writes++,await X.onStep?.("after-config-write",q),{settings:k9(U),outcome:"updated"}}finally{await G.releaseTo(Q)}})}var w4=new Map;function d3(Z){let $=w4.get(Z);if(!$)$={removedIds:new Set,firedAtLoad:new Set},w4.set(Z,$);return $}function u4(Z){if(Z.status==="ready")return{status:"ready",schemaVersion:vZ,rows:Z.rows};if(Z.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(Z.config.accounts)?Z.config.accounts:[]};return Z}function S1(Z){let $=d3(Z.configPath),J={...q9,...Z.lockOptions},X={provider:Z.provider,configPath:Z.configPath,statePath:Z.statePath,codec:Z.quota,...Z.providerState?{providerState:Z.providerState}:{},now:Z.now??Date.now,storeLocks:Z.storeLocks??[{name:"save",path:Z.configPath},{name:"save",path:Z.statePath}],lockDefaults:J,lockEnv:{...Z.onLockEvent?{onLockEvent:Z.onLockEvent}:{},...Z.onLockStep?{onLockStep:Z.onLockStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}},removedIds:$.removedIds,requireCredentialStamps:Z.requireCredentialStamps===!0,requireRemovedFingerprint:Z.requireRemovedFingerprint===!0,...Z.logger?{logger:Z.logger}:{},...Z.onStep?{onStep:Z.onStep}:{},...Z.hold?{hold:Z.hold}:{}},z=new E9(()=>G,Z.pull,Z.onPullFailure,$.firedAtLoad,Z.logger),G={ctx:X,providerLock:Z.providerLock??{name:`provider-${encodeURIComponent(Z.provider)}`,path:Z.statePath},rowLockOptions:Z.rowLockOptions??{},firePull:(W,H)=>z.fire(W,H)},B=Z.coalesceQuota?new b9(G,Z.quotaDrainTimeoutMs,Z.quotaCommitTimer):void 0,Q=(W,H,V)=>B?B.record(W,H,V):B5(G,W,H,V);G.publishQuota=Q;let Y=(W)=>{if(W.status==="ready"&&B)return{...W,rows:B.overlay(W.rows)};return W};return{async load(){let W=Y(await n(X));if(W.status==="ready"){for(let H of W.rows)if((H.candidate||H.torn&&H.enabled)&&H.type==="oauth"&&H.needsFirstReading)z.fire(H.id,"load")}return u4(W)},async read(){return u4(Y(await n(X)))},async initialize(W={}){return{status:await Y4(X,W.dropKeys??[])}},add:(W,H)=>K4(G,W,H),publishRoster:(W,H)=>E4(G,W,H),publication:(W)=>I4(G,W),replace:(W,H,V,j)=>N4(G,W,H,V,j),rotate:(W,H,V,j)=>D4(G,W,H,V,j),updateProviderState:(W,H,V,j)=>U4(G,W,H,V,j),disable:(W,H,V)=>P4(G,W,H,V),enable:(W,H)=>C4(G,W,H),remove:(W,H)=>T4(G,W,H),reorder:(W,H)=>_4(G,W,H),readSettings:()=>x4(G),updateSettings:(W,H)=>m4(G,W,H),recordIdentity:(W,H,V,j)=>L4(G,W,H,V,j),refresh:(W,H,V)=>g4(G,W,H,V),recordQuota:Q,close:()=>B?.close()??Promise.resolve(),dispose:()=>B?.close()??Promise.resolve(),requestReading:(W)=>z.fire(W,"admission"),pullsSettled:()=>z.settled()}}var c3=[/\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 h9(Z={}){let{redactStrings:$}=p4({...Z,extraValuePatterns:[...c3,...Z.extraValuePatterns??[]]});return(J)=>$(J)}class u extends Error{code;constructor(Z,$,J){super($,J);this.name="CommandError",this.code=Z}}var l4=/^[a-z][a-z0-9-]{0,63}$/,v9={code:"action-failed",text:"That action failed."},s3=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 I1(Z){if(Z instanceof u)return{code:l4.test(Z.code)?Z.code:v9.code,text:Z.message};if(Z instanceof R)return{code:`pool-${Z.kind}`,text:s3.has(Z.kind)?Z.message:`The account pool could not do that (${Z.kind}).`};return v9}var d4="This cannot be undone. Continue?",a3=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function n3(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");return a3.has($)||$.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function i3(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function g9(Z,$,J){if(typeof Z==="string"){let z=J.redact(Z);if(z!==Z)J.redacted.push($);return z}if(Array.isArray(Z))return Z.map((z,G)=>g9(z,`${$}[${G}]`,J));if(!i3(Z))return Z;let X={};for(let[z,G]of Object.entries(Z)){if(n3(z)){J.dropped.push(`${$}.${z}`);continue}Object.defineProperty(X,z,{value:g9(G,`${$}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function c4(Z,$,J){let X={redact:J.redact,dropped:[],redacted:[]},z=g9(Z,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:$,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:$,fields:X.redacted});return z}function r3(Z){return{value:String(Z.value),label:String(Z.label)}}function o3(Z){switch(Z.kind){case"choice":return{kind:"choice",id:Z.id,label:Z.label,choices:(Z.choices??[]).map(r3),...Z.value!==void 0?{value:Z.value}:{}};case"toggle":return{kind:"toggle",id:Z.id,label:Z.label,value:Z.value===!0};case"number":return{kind:"number",id:Z.id,label:Z.label,...Z.value!==void 0?{value:Z.value}:{},...Z.min!==void 0?{min:Z.min}:{},...Z.max!==void 0?{max:Z.max}:{},...Z.required?{required:!0}:{}};case"text":return{kind:"text",id:Z.id,label:Z.label,...Z.value!==void 0&&!Z.masked?{value:Z.value}:{},...Z.placeholder!==void 0?{placeholder:Z.placeholder}:{},...Z.masked?{masked:!0}:{},...Z.required?{required:!0}:{}}}}function f9(Z){if(Z.irreversible===!0)return{message:Z.confirm||d4,irreversible:!0};if(Z.confirm)return{message:Z.confirm,irreversible:!1};return}function s4(Z){let $=f9(Z);return{id:Z.id,label:Z.label,...Z.description!==void 0?{description:Z.description}:{},...Z.group!==void 0?{group:String(Z.group)}:{},knobs:(Z.knobs??[]).map(o3),...$?{confirm:$}:{}}}function t3(Z){return{id:Z.id,...Z.label!==void 0?{label:Z.label}:{},enabled:Z.enabled,type:Z.type,...Z.identity!==void 0?{identity:Z.identity}:{}}}function e3(Z){return{id:Z.id,label:Z.label,...Z.detail!==void 0?{detail:Z.detail}:{},...Z.group!==void 0?{group:String(Z.group)}:{},...Z.status!==void 0?{status:String(Z.status)}:{},...Z.account?{account:t3(Z.account)}:{},...Z.facts!==void 0?{facts:Z.facts}:{},actions:(Z.actions??[]).map(s4)}}function Z8(Z){let{content:$}=Z;return{id:Z.id,slot:Z.slot,title:Z.title,lines:($.lines??[]).map(String),items:($.items??[]).map(e3),actions:($.actions??[]).map(s4),...$.facts!==void 0?{facts:$.facts}:{}}}function a4(Z,$,J){return{command:Z,title:$,sections:J.map(Z8)}}function n4(Z,$,J,X){return c4({command:Z,menu:a4(Z,$,J)},Z,X)}function i4(Z,$,J,X,z){return c4({command:Z,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:l4.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:a4(Z,$,J)},Z,z)}var J6="disabled from the command menu";function $8(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function IZ(Z){return $8(Z)?{...Z}:{}}function J8(Z){if(Z.status!=="ready")return[];let $=new Set;return Z.rows.filter((J)=>{if($.has(J.id))return!1;return $.add(J.id),!0})}function X8(Z,$){return Z.label??$??Z.id}function D5(Z,$){return fZ(Z.quota)?CZ(Z.quota,$):void 0}function X6(Z,$){return`${Z} ${$}${Z===1?"":"s"}`}var R1="Actions";function z8(Z){if(Z.status==="pending-migration")return"The account pool has not been migrated yet.";if(Z.status==="error")return`The ${Z.file} file cannot be read: ${Z.reason}`;return}function r4(Z,$){switch($.outcome){case"added":return`Added ${Z}.`;case"added-disabled":return`Added ${Z}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${Z}.`;case"rotated":return`${Z} was already in the pool; its credential was updated.`;case"exists":return`${Z} was already in the pool; its credential is unchanged.`}}function o4(Z){return I1(Z).text}async function G8(Z){let{store:$}=Z,J=await $.read(),X=await $.readSettings(),z=await Z.routing?.vaultOrder?.();return{load:J,rows:J8(J),settings:X.status==="error"?{}:X.settings,...z?{vault:z}:{}}}function M5(Z,$){let J=$.accounts?.describeIdentity?$.accounts.describeIdentity(Z):Z.identity;return{account:{id:Z.id,...Z.label!==void 0?{label:Z.label}:{},enabled:Z.enabled,type:Z.type,...J!==void 0?{identity:J}:{}},name:X8(Z,J)}}function B8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=$.rows.map((V)=>V.id),B=z8($.load),Q=$.rows.filter((V)=>V.enabled).length,Y=$.rows.map((V,j)=>{let{account:F,name:U}=M5(V,Z),q=[V.type==="api"?"API key":"OAuth",...F.identity!==void 0?[F.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),K=V.invalid?"invalid":V.enabled?"enabled":"disabled",N=[];if(!V.invalid&&V.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(V.id,J6,z),`Disabled ${U}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(V.id,z),`Enabled ${U}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((M,O)=>({value:String(O+1),label:String(O+1)})),value:String(j+1)}],run:async({values:M})=>{let O=Number(M.position),_=G.filter((T)=>T!==V.id);return _.splice(O-1,0,V.id),(await J.reorder(_,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(V.id,{...z,...Z.accounts?.protect?{protect:Z.accounts.protect}:{}}),`Removed ${U}.`}}),{id:V.id,label:U,detail:q,group:"Accounts",status:K,account:F,actions:N}}),W=Z.accounts?.login,H=[];if(W&&!B)H.push({id:"add",label:W.label??"Add account",group:R1,knobs:W.knobs??[],run:async({values:V,invocation:j})=>{let F=await W.run(V,j);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 r4(F.account.label??U.id,U)}return F.completion.then(async(U)=>{if(!U){j.notify("Login cancelled.","warning");return}let q=await J.add(U,z);j.notify(r4(U.label??q.id,q))},(U)=>{j.notify(`Adding the account failed: ${o4(U)}`,"error")}).catch((U)=>{j.notify(`Adding the account failed: ${o4(U)}`,"error")}),F.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[$.rows.length===0?"No accounts yet":`${X6($.rows.length,"account")}, ${Q} enabled`],items:B?[]:Y,actions:H}}}function Q8(Z,$){let J=Z.quota?.scope??"all",X=Z.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(H,V)=>{if(Z.quota?.check)await Z.quota.check(H,V);else{for(let j of H)Z.store.requestReading(j);await Z.store.pullsSettled()}},B=$.rows.filter((H)=>H.candidate),Q=B.map((H)=>{let{account:V,name:j}=M5(H,Z),F=D5(H,J);return{id:H.id,label:j,group:z,status:PZ(F,{now:X,form:"compact"}),detail:PZ(F,{now:X,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([H.id],U),`Checked quota for ${j}.`}}]}}),Y=$.rows.filter((H)=>!H.candidate).map((H)=>{let{name:V}=M5(H,Z),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",F=PZ(D5(H,J),{now:X,form:"compact"});return`${V} (${j}): ${F}`}),W=[];if(B.length>0)W.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:R1,run:async({invocation:H})=>{let V=B.map((j)=>j.id);return await G(V,H),`Checked quota for ${X6(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:$.rows.length===0?["No accounts yet"]:Y,items:Q,actions:W}}}async function W8(Z,$){try{return await Z.reorder($)}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 x9(Z){return new u("vault-invalid-order",Z)}function Y8(Z){let $=Z.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>$.filter((z)=>z.id===X||z.label===X);return{ids:$.map((X)=>X.id),nameOf:(X)=>$.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let 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 x9(`"${G}" is not a vault account.`);if(B.length>1)throw x9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let Q=B[0].id;if(z.includes(Q))throw x9(`"${G}" names an account already in the order.`);z.push(Q)}return z}}}function H8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...Z.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=IZ($.settings.routing).mode,Q=typeof B==="string"&&G.some((K)=>K.value===B)?B:"ordered",Y=Z6(Q),W=$.vault?Y8($.vault):void 0,H=W?W.ids:$.rows.map((K)=>K.id),V=(K)=>W?W.nameOf(K):K,j=$6(H,Y.placement,Z.routing?.formerMainId??e4),U=[`Mode: ${G.find((K)=>K.value===Q)?.label??Q}`];if(H.length>0)U.push(`${W?"Vault account order":"Roster order"}: ${H.map(V).join(", ")}`);if(Y.mode==="ordered"&&j.join()!==H.join())U.push(`Tried in order: ${j.map(V).join(", ")}`);let q=[{id:"mode",label:"Change mode",group:R1,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:Q}],run:async({values:K})=>{let N=String(K.mode);return await J.updateSettings((M)=>{M.routing={...IZ(M.routing),mode:N};return},z),`Routing mode set to ${G.find((M)=>M.value===N)?.label??N}.`}}];if(H.length>1)q.push({id:"order",label:"Set order",group:R1,knobs:[{kind:"text",id:"order",label:W?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:W?H.map(W.entryOf).join(", "):H.join(", "),required:!0}],run:async({values:K})=>{let M=String(K.order).split(W?/[,\n]+/:/[\s,]+/).map((_)=>_.trim()).filter((_)=>_.length>0),O=$.vault&&W?await W8($.vault,W.resolve(M)):await J.reorder(M,z);return O.outcome==="unchanged"?"The order is unchanged.":`Order set to ${O.ids.map(V).join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:U,actions:q}}}function V8(Z,$){if(Z.limits?.labels)return[...Z.limits.labels];let J=Z.quota?.scope??"all",X=[];for(let z of $.rows)for(let G of D5(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function U8(Z,$){let J=Z.quota?.scope??"all",X=new Map;for(let z of $.rows)for(let G of D5(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,t4(G));return(z)=>X.get(z)??z}function j8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=IZ($.settings.killswitch),B=G.enabled===!0,Q=IZ(G.accounts),Y=V8(Z,$),W=U8(Z,$),H=B?"on":"off",V=$.rows.map((j)=>{let{account:F,name:U}=M5(j,Z),q=IZ(Q[j.id]),K=Y.filter((N)=>typeof q[N]==="number");return{id:j.id,label:U,group:`Floors · killswitch ${H}`,status:K.length===0?"no floors":K.map((N)=>`${W(N)} ≥${q[N]}%`).join(" · "),account:F,actions:[{id:"floors",label:"Set floors",knobs:Y.map((N)=>({kind:"number",id:N,label:`Minimum % left for ${W(N)}`,min:0,max:100,...typeof q[N]==="number"?{value:q[N]}:{}})),run:async({values:N})=>{return await J.updateSettings((M)=>{let O=IZ(M.killswitch),_=IZ(O.accounts),D=IZ(_[j.id]);for(let T of Y){let A=N[T];if(typeof A==="number")D[T]=A;else if(A===null)delete D[T]}if(Object.keys(D).length>0)_[j.id]=D;else delete _[j.id];if(Object.keys(_).length>0)O.accounts=_;else delete O.accounts;M.killswitch=O;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${H}`],items:V,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:R1,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:j})=>{let F=j.enabled===!0;return await J.updateSettings((U)=>{U.killswitch={...IZ(U.killswitch),enabled:F};return},z),`Killswitch ${F?"on":"off"}.`}}]}}}async function z6(Z){let $=await G8(Z);return[B8(Z,$),Q8(Z,$),H8(Z,$),j8(Z,$)]}var q8=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),m9=["accounts","quota","routing","limits"];function G6(Z,$){let{sessionId:J}=Z,X=Z.notify.bind(Z);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X($(String(z))):X($(String(z)),G)})}function F8(Z,$){switch(Z.kind){case"choice":{let J=$??Z.value;if(typeof J==="string"&&Z.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${Z.label}.`}}case"toggle":{let J=$??Z.value;return typeof J==="boolean"?{value:J}:{problem:`${Z.label} must be on or off.`}}case"number":{let J=$===void 0?Z.value??null:$;if(J===null||J==="")return Z.required?{problem:`${Z.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${Z.label} needs a number.`};if(Z.min!==void 0&&X<Z.min)return{problem:`${Z.label} must be at least ${Z.min}.`};if(Z.max!==void 0&&X>Z.max)return{problem:`${Z.label} must be at most ${Z.max}.`};return{value:X}}case"text":{let J=$===void 0?Z.value??null:$;if(J===null||J==="")return Z.required?{problem:`${Z.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${Z.label} must be text.`}}}}function K8(Z,$){let J={};for(let X of Z){let z=$&&Object.hasOwn($,X.id)?$[X.id]:void 0,G=F8(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function N8(Z,$){let J=Z.find((z)=>z.id===$.sectionId);if(!J)return;return($.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===$.itemId)?.actions)?.find((z)=>z.id===$.actionId)}function pZ(Z){let $=Z.logger??s("commands"),J=h9(Z.redaction),X={logger:$,redact:J},z=Z.now??Date.now,G=Z.extras??[],B=Z.replace??{},Q=m9.filter((j)=>!B[j]);for(let j of m9)if(B[j]&&Z[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let Y=Z.store;if(Q.length>0&&!Y)throw Error(`a store is required for the built-in ${Q.join(", ")} section${Q.length>1?"s":""}`);let W=new Set;for(let j of G){if(q8.has(j.id)||W.has(j.id))throw Error(`extra section id ${j.id} is taken`);W.add(j.id)}async function H(j,F,U,q){try{return{id:j,slot:F,title:U.title,content:await U.build(q)}}catch(K){return $.warn("command menu section failed to build",{command:Z.command,section:j,error:J(K instanceof Error?K.message:String(K))}),{id:j,slot:F,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let F=Y&&Q.length>0?await z6({store:Y,now:z,...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.accounts?{accounts:Z.accounts}:{},...Z.quota?{quota:Z.quota}:{},...Z.routing?{routing:Z.routing}:{},...Z.limits?{limits:Z.limits}:{}}):[],U=[];for(let q of m9){let K=B[q];if(K)U.push(await H(q,q,K,j));else{let N=F.find((M)=>M.slot===q);if(N)U.push(N)}}if(Z.cache)U.push(await H("cache","cache",Z.cache,j));if(Z.diagnostics)U.push(await H("diagnostics","diagnostics",Z.diagnostics,j));for(let q of G)U.push(await H(q.id,"extra",q,j));return U}return{command:Z.command,async open(j){let F=G6(j,J);return n4(Z.command,Z.title,await V(F),X)},async apply(j,F){let U=G6(F,J),q=async(_)=>i4(Z.command,Z.title,await V(U),_,X),K=j.command===Z.command?N8(await V(U),j):void 0;if(!K)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=f9(K);if(N&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let M=K8(K.knobs??[],j.values);if("problem"in M)return q({ok:!1,code:"invalid-input",text:M.problem});let O;try{let _=await K.run({values:M.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:U});O=typeof _==="string"?{ok:!0,text:_}:{ok:_.ok,text:_.text,..._.ok?{}:{code:_.code??"refused"}}}catch(_){let D=I1(_);$.warn("command menu action failed",{command:Z.command,section:j.sectionId,action:j.actionId,code:D.code,error:J(_ instanceof Error?_.message:String(_))}),O={ok:!1,...D}}return q(O)}}}function D8(Z){return Z===null||typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"&&Number.isFinite(Z)}function M8(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $=Z;if(typeof $.command!=="string"||typeof $.sectionId!=="string"||typeof $.actionId!=="string")return;if($.itemId!==void 0&&typeof $.itemId!=="string")return;if($.sessionId!==void 0&&typeof $.sessionId!=="string")return;if($.confirmed!==void 0&&typeof $.confirmed!=="boolean")return;let J={};if($.values!==void 0){if($.values===null||typeof $.values!=="object"||Array.isArray($.values))return;for(let[X,z]of Object.entries($.values)){if(!D8(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:$.command,sectionId:$.sectionId,actionId:$.actionId,...typeof $.itemId==="string"?{itemId:$.itemId}:{},...$.values!==void 0?{values:J}:{},...$.confirmed===!0?{confirmed:!0}:{},...typeof $.sessionId==="string"?{sessionId:$.sessionId}:{}}}function k(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}import{statSync as T8}from"node:fs";import{rm as W6}from"node:fs/promises";import{dirname as _8,join as M6}from"node:path";import{resolveClaustrumConnectionPath as L8}from"@cortexkit/claustrum-client";function B6(Z,$){if(!Z)return;let J=Z.rawUsedPercent??Z.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:$,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...typeof Z.windowMinutes==="number"&&Number.isFinite(Z.windowMinutes)&&Z.windowMinutes>0&&{windowMinutes:Z.windowMinutes}}}function w9(Z){if(!k(Z)||typeof Z.minor!=="number"||!Number.isSafeInteger(Z.minor)||typeof Z.exponent!=="number"||!Number.isInteger(Z.exponent))return;let $=Z.minor/10**Z.exponent;return Number.isFinite($)?$:void 0}function P8(Z){let $=w9(Z.total),J=w9(Z.remaining);if($===void 0||J===void 0||$<0||J<0)return;let X=$-J,z=Z.spendable===!1,G=$>0?X/$*100:z?100:0;return{limit:$,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...k(Z.total)&&typeof Z.total.unit==="string"&&{unit:Z.total.unit}}}function C8(Z,$){if(!k(Z))return;let J=w9(Z.remaining);return{hasCredits:!0,unlimited:typeof Z.unlimited==="boolean"?Z.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...Z.spendable===!1&&{overageLimitReached:!0},checkedAt:$}}function u9(Z,$){if(Z.insulaCreditsUnlimitedUnstated&&Z.credits&&Z.credits.balance===void 0&&k($)&&k($.credits)&&$.credits.unlimited===!0)return{...Z,credits:{...Z.credits,unlimited:!0}};return Z}function Q6(Z,$){let J=B6(Z.usage?.primary,$.fetchedAt);if(!J||!Number.isFinite($.fetchedAt))return;let X=B6(Z.usage?.secondary,$.fetchedAt),z=Array.isArray(Z.spend)?Z.spend.find((W)=>k(W)&&W.id==="individual_limit"):void 0,G=k(z)?P8(z):void 0,B=Array.isArray(Z.spend)?Z.spend.find((W)=>k(W)&&W.id==="credits"):void 0,Q=C8(B,$.fetchedAt),Y=k(Z.savedResets)?Z.savedResets.availableCount:void 0;return{primary:J,...Q&&{credits:Q},...Q&&k(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function p9(Z){return`ck auth grant --principal enrolled:${Z} --selector-kind category --selector openai-native --operation read`}var l9="ck auth reclassify --from-registry";function P5(Z,$){if($===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($.grants===0)return`The vault has no grant letting ${Z} read OpenAI accounts. Grant it with \`${p9(Z)}\`.`;return`The vault's grant for ${Z} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${l9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var UZ=s("vault"),O8="openai-auth",P6={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},A8={opencode:"OpenCode",pi:"Pi"};function d9(Z){return H6(O8,Z)}function O5(Z){return M6(_8(Z),"openai-auth-vault")}function lZ(Z,$){return{...U6({stateDir:Z,host:$}),rosterPath:M6(Z,`${$}-roster.json`)}}var C6=2000,EB=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],S8={"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 ${l9} 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 bB(Z,$){if(Z!=="vault-no-grant")return S8[Z];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: ${p9($)}`}function yB(Z){let $=Z.snapshot();if($===void 0)return"vault-unreachable";if($.rows.length===0){let J=Z.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function I8(Z){let $=T5(Z);return $?_5($):void 0}class T6 extends N6{#$;constructor(Z,$){super(Z);this.#$=$}refresh(){let Z=super.refresh();return this.#$(Z),Z}}class R8{host;name;paths;#$;#Z;#Q=new Map;#W=new Map;#U=new Map;#j;#J;#Y;#z;#q=!1;#F=!1;#H=Promise.withResolvers();#K="unknown";#V;constructor(Z){this.#$=Z,this.host=Z.host,this.name=d9(Z.host),this.paths=lZ(Z.stateDir,Z.host),this.#Z=new T6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:P6,connect:()=>this.#C(),isCustodyActive:()=>this.#_(),...Z.reservedRouteIds?{reservedRouteIds:Z.reservedRouteIds}:{},parseIdentity:I8,insula:{provider:"codex",normalize:Q6},...Z.now?{now:Z.now}:{},...Z.pollIntervalMs!==void 0?{pollIntervalMs:Z.pollIntervalMs}:{},...Z.setTimeoutImpl?{setTimeoutImpl:Z.setTimeoutImpl}:{},...Z.clearTimeoutImpl?{clearTimeoutImpl:Z.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onError:($)=>this.#X("vault roster refresh failed",$),logger:{...UZ,warn:($,J)=>{if($!=="skipped insula provider poll")UZ.warn($,J)}}},($)=>this.#L($))}#N(){return(this.#$.connectionFile??L8)()}#D(){return{connectionFile:this.#N(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(Z)=>UZ.debug("vault transport error",{errorClass:Z})}}#C(){return(this.#$.connectScoped?.()??D6(this.#D())).then((Z)=>{return this.#j=Z.insula!==void 0,Z})}#G(Z,$,J){let X=this.#U.get(Z);if(X?.source===$&&X.reason===J)return;this.#U.set(Z,{source:$,reason:J}),UZ.info("vault background quota source changed",{routeId:Z,source:$,reason:J})}#T(){return this.#$.connectEnrollment?.()??V6(this.#D())}#X(Z,$){this.#J=TZ($),UZ.warn(Z,{host:this.host,error:this.#J})}#B(){return[this.paths.tokenPath,this.paths.statePath].map((Z)=>{try{let $=T8(Z);return`${$.ino}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let Z=this.#B(),$=await j6(this.paths,this.name);if(Z===this.#B())return this.#K=$,this.#V=Z,$;return"unreadable"}enrolled(){return this.#V!==this.#B()||this.#K!=="local"}async#_(){if(this.#V!==this.#B())await this.authority();return this.enrolled()}start(){if(this.#q||this.#F)return;this.#q=!0,this.#Z.start()}#L(Z){if(this.#z===Z)return;this.#z=Z,Z.finally(()=>{if(this.#z===Z)this.#z=void 0;this.#H.resolve()}).catch(()=>{})}#M(){return this.#Z.refresh()}firstRoster(){return this.#H.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let Z=this.#z;if(Z)await Z.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#z??this.#M()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let Z=this.#z;if(Z)await Z.catch(()=>{return});let $=await this.#M();return this.#J=void 0,$}catch(Z){return this.#X("vault roster refresh failed",Z),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}watchState(){return this.#Z.watchState()}keptReceiptState(){return this.#Z.keptReceiptState()}grantReach(){return this.#Z.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((Z)=>Z.accountIdentity!==void 0?[Z.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let Z=new Map((this.snapshot()?.rows??[]).map(($)=>[$.routeId,$]));return this.#Z.routingRows().map(($)=>{let J=Z.get($.id)?.accountIdentity;return{id:$.id,credentialId:Z.get($.id)?.credentialId,kind:$.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...$.quota!==void 0?{quota:$.quota}:{}}})}owns(Z){return(this.snapshot()?.rows??[]).some(($)=>$.routeId===Z)}async send(Z,$,J){let X=!1;try{return await this.#Z.send(Z,(z)=>{return X=!0,$(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.#Z.authorize(Z,$.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure(Z,$){if($!==401)return;try{await this.#Z.reportFailure(Z,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot(Z,$,J,X){let z=C5($,(this.#$.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#Z.recordQuota(Z,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}pollQuota(Z,$=!0){let J=this.#W.get(Z);if(J)return J;let X=this.#O(Z,$).finally(()=>{this.#W.delete(Z)});return this.#W.set(Z,X),X}async#O(Z,$){if($){await this.authority(),await this.#Z.refreshInsulaQuota();let J=(await K6(this.paths.rosterPath))?.rows.find((Q)=>Q.routeId===Z),X,z=await this.#Z.pollInsulaQuotaForRoute(Z,async()=>{this.#G(Z,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#P(Z,$);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let Q=C5(u9(z,this.routes().find((W)=>W.id===Z)?.quota),z.primary.checkedAt,!0);if(!Q)return this.#G(Z,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota(Z,J.accountIdentity,Q))return this.#G(Z,"insula",null),{ok:!0};return this.#G(Z,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#Z.lookupInsulaQuotaForRoute(Z),B=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G(Z,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#P(Z,$)}async#P(Z,$){let J,X=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send(Z,async(G,B)=>{try{let Q=$?void 0:await this.#Z.cachedInsulaQuota(B);if(Q!==void 0){let W=C5(u9(Q,this.routes().find((H)=>H.id===Z)?.quota),Q.primary.checkedAt,!0);if(!W)throw Error("unusable insula reading");return await this.#Z.recordQuota(Z,W,B),new Response(null,{status:200})}let Y=await E1({accessToken:G,fetchImpl:X,now:this.#$.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:Z,logger:UZ});return await this.recordSnapshot(Z,Y,!0,B),J=void 0,new Response(null,{status:200})}catch(Q){J=TZ(Q);let Y=Q?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw Q}},{site:"quota"}).catch((G)=>{J=TZ(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading(Z){let $=this.#Q.get(Z);if($)return $;let J=this.pollQuota(Z,!1).catch((X)=>{UZ.warn("vault quota poll failed",{routeId:Z,error:TZ(X)})}).finally(()=>{this.#Q.delete(Z)});return this.#Q.set(Z,J),J}async pollStale(Z){let $=(this.#$.now??Date.now)(),J=[];for(let X of this.routes()){let z=E8(X.quota);if(z!==void 0&&$-z<Z)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder(Z){if(await this.authority()!=="vault")throw Error("Vault order can only be changed in vault mode.");return this.#Z.reorder(Z)}async decline(Z){await this.#Z.decline(Z),UZ.info("vault account declined",{routeId:Z})}async accept(Z){await this.#Z.accept(Z),UZ.info("vault account accepted",{routeId:Z})}async status(){await this.authority();let Z;try{Z=await L5(this.paths,this.name)}catch(J){this.#X("vault enrollment state unreadable",J),Z={state:"blocked",proposedName:this.name,code:J instanceof Y6?J.kind:"unreadable-state"}}let $=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:$!==void 0,accounts:$?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){let Z=await this.#T().catch(($)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${TZ($)}. Is the vault running?`)});try{let $=new q6({client:Z,paths:this.paths,proposedName:this.name,...this.#$.now?{now:this.#$.now}:{}}),J=await $.status();if(J.state==="denied"||J.state==="blocked")await $.resetTerminal();let X=await $.reconcile();if(UZ.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{Z.close()}}waitForApproval(Z={}){return this.#Y??=(async()=>{let $=Z.sleep??((G)=>new Promise((B)=>setTimeout(B,G))),J=Z.pollIntervalMs??2000,X=Date.now()+(Z.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if(Z.onPending?.(z),Date.now()>=X)return z;await $(J),z=await this.connectStep()}return z})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){await W6(this.paths.tokenPath,{force:!0}),await W6(this.paths.statePath,{force:!0}),await this.#$.afterDisconnect?.(),await this.authority(),this.#J=void 0,UZ.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(Z){if(this.serves())F6({mode:"custody",auth:Z,provider:"openai"})}close(){this.#F=!0,this.#H.resolve(),this.#Z.close()}}function E8(Z){if(!Z)return;let $=CZ(Z).limits.map((J)=>J.checkedAt);return $.length>0?Math.max(...$):void 0}function A5(Z,$){if($.state!=="pending")return[];if(!$.requestId)return[`The vault did not take the enrollment request yet${$.retryCode?` (${$.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${$.requestId} for ${Z} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${$.requestId}`,"and let it read your OpenAI accounts with:",` ck auth grant --principal enrolled:${Z} --selector-kind category --selector ${P6.category} --operation read`]}function _6(Z,$,J){let X=`${A8[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(($.state==="blocked"||$.state==="unavailable")&&$.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($.state){case"approved":{let J=Z.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${Z.name}. It serves ${J} OpenAI account${J===1?"":"s"} to this host${J===0?`. ${P5(Z.name,Z.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 (${$.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...A5(Z.name,$),"Still waiting. The request stays open: run Connect again after approving it."].join(`
2
+ `)};default:return{ok:!1,text:`Enrollment is ${$.state}.`}}}var s9="/backend-api/wham/rate-limit-reset-credits",b8=`https://chatgpt.com${s9}`,R6=`${s9}/consume`,y8=`https://chatgpt.com${R6}`,k8=300000,v8=60000,g8=15000,h8=60000;function z1(Z){return{configPath:Z.configPath,statePath:Z.statePath}}class ZZ extends Error{kind;cooldownUntil;constructor(Z,$,J){super($);this.name="ResetRedemptionError",this.kind=Z,this.cooldownUntil=J}}class dZ extends Error{kind;status;constructor(Z,$,J){super($);this.name="ResetCreditError",this.kind=Z,this.status=J}}function E6(Z,$,J){return{authorization:`Bearer ${Z}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":$}}function I5(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function b6(Z){if(!Z)return;return{...Z.inFlight?{inFlight:{...Z.inFlight}}:{},...Z.lastOutcome?{lastOutcome:{...Z.lastOutcome}}:{},...Z.cooldownUntil!==void 0?{cooldownUntil:Z.cooldownUntil}:{}}}function R5(Z){if(!I5(Z)||typeof Z.redeemRequestId!=="string"||Z.redeemRequestId.length===0||typeof Z.creditId!=="string"||Z.creditId.length===0||typeof Z.startedAt!=="number"||!Number.isFinite(Z.startedAt)||Z.chatgptAccountId!==void 0&&(typeof Z.chatgptAccountId!=="string"||Z.chatgptAccountId.length===0))return;return{redeemRequestId:Z.redeemRequestId,creditId:Z.creditId,startedAt:Z.startedAt,...typeof Z.chatgptAccountId==="string"?{chatgptAccountId:Z.chatgptAccountId}:{},...y6(Z.rejectedStatus)?{rejectedStatus:Z.rejectedStatus}:{},...typeof Z.unknownAnswers==="number"&&Number.isSafeInteger(Z.unknownAnswers)&&Z.unknownAnswers>0?{unknownAnswers:Z.unknownAnswers}:{}}}function y6(Z){return typeof Z==="number"&&Z>=400&&Z<500&&Z!==408&&Z!==409&&Z!==425&&Z!==429}function S5(Z){return Z.kind==="http_error"&&y6(Z.status)}function k6(Z,$){return Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$||Z.rejectedStatus!==void 0}function f8(Z,$){if(Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$)throw new ZZ("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function v6(Z){return Boolean(Z&&Object.hasOwn(Z,"inFlight"))}function g6(Z,$){return $-Z.startedAt<k8}function G1(Z,$){if(!RZ($))return;return Z.reset?.[$]}function h6(Z){if(!Z.reset)Z.reset=Object.create(null);return Z.reset}function f6(Z,$,J){if(!RZ($))return;let X=h6(Z),z=X[$]??{},G=z.lastOutcome;delete z.inFlight,z.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[$]=z}function x6(Z,$){let J=b6(Z),X=R5(Z?.inFlight);if(v6(Z)&&!X)return{kind:"corrupt",beforeState:J};if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>$)return{kind:"cooldown",beforeState:J,cooldownUntil:Z.cooldownUntil};if(X&&g6(X,$))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 x8(Z,$){if(!RZ($))return{kind:"fresh",beforeState:void 0};let J=await Z.loadAccountsFn(z1(Z));return x6(J?G1(J,$):void 0,Z.now())}async function m8(Z,$){let J;if(await Z.mutateAccountsFn((X)=>{let z=Z.now(),G=G1(X,$);if(J=x6(G,z),J.kind==="corrupt")f6(X,$,z);return X},z1(Z)),!J)throw Error("corrupt reset state mutation did not run");return J}async function w8(Z,$,J,X){if(!RZ($))return{kind:"fresh",beforeState:void 0};let z;if(await Z.mutateAccountsFn((G)=>{let B=Z.now(),Q=G1(G,$),Y=b6(Q),W=R5(Q?.inFlight);if(v6(Q)&&!W)return f6(G,$,B),z={kind:"corrupt",beforeState:Y},G;if(Q?.cooldownUntil!==void 0&&Q.cooldownUntil>B)return z={kind:"cooldown",beforeState:Y,cooldownUntil:Q.cooldownUntil},G;if(W&&g6(W,B))return z={kind:"claim",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;if(W&&!k6(W,X))return z={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;let H=E5(J);if(!H)return z={kind:"fresh",beforeState:Y},G;let V={redeemRequestId:Z.randomUUID(),creditId:H.id,startedAt:B,...X===void 0?{}:{chatgptAccountId:X}},j=h6(G);return j[$]={...Q,inFlight:V},z={kind:"claim",beforeState:Y,claim:{inFlight:V,selectedCredit:H}},G},z1(Z)),!z)throw Error("reset claim mutation did not run");return z}async function u8(Z,$,J,X,z){if(!RZ($))return;if(!i9(X.kind))return p8(Z,$,J,X,z);await Z.mutateAccountsFn((G)=>{let B=G1(G,$),Q=R5(B?.inFlight);if(!B||!Q||Q.redeemRequestId!==J.redeemRequestId||Q.creditId!==J.creditId)return G;let Y=Z.now();if(delete B.inFlight,B.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")B.cooldownUntil=Y+h8;else delete B.cooldownUntil;return G},z1(Z));return}function L6(Z,$){let J=R5(Z?.inFlight);return J&&J.redeemRequestId===$.redeemRequestId&&J.creditId===$.creditId?J:void 0}async function p8(Z,$,J,X,z){let G=S5(X)?X.status:void 0;if(!(J.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===J.rejectedStatus){let Y=await Z.loadAccountsFn(z1(Z));return L6(Y?G1(Y,$):void 0,J)}let Q;return await Z.mutateAccountsFn((Y)=>{Q=void 0;let W=G1(Y,$),H=L6(W,J);if(!W||!H)return Y;let V={...H};if(V.chatgptAccountId===void 0&&z!==void 0)V.chatgptAccountId=z;if(G===void 0)delete V.rejectedStatus,V.unknownAnswers=(H.unknownAnswers??0)+1;else if((H.unknownAnswers??0)===(J.unknownAnswers??0))V.rejectedStatus=G;return W.inFlight=V,Q=V,Y},z1(Z)),Q}function b1(Z,$){if(!Z||Z.usedPercent<100)return!1;if(!Z.resetsAt)return!0;let J=Date.parse(Z.resetsAt);return!Number.isFinite(J)||J>$}function a9(Z,$,J){if(!($||b1(Z.primary,J)||b1(Z.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function O6(Z,$){let J=Z[$];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function l8(Z){if(!I5(Z))return;let $=O6(Z,"granted_at"),J=O6(Z,"reset_type");if(typeof Z.id!=="string"||typeof Z.status!=="string"||typeof Z.expires_at!=="string"||Number.isNaN(Date.parse(Z.expires_at))||typeof Z.is_supported_by_plan!=="boolean"||$===null||J===null)return;return{id:Z.id,status:Z.status,...$===void 0?{}:{grantedAt:$},expiresAt:Z.expires_at,...J===void 0?{}:{resetType:J},isSupportedByPlan:Z.is_supported_by_plan}}async function n9(Z,$,J){let X;try{X=await Z(b8,{method:"GET",headers:E6($,s9,J),signal:AbortSignal.timeout(g8)})}catch{throw new dZ("http_error","reset credit list request failed")}if(!X.ok)throw new dZ("http_error",`reset credit list request failed: ${X.status}`,X.status);let z;try{z=await X.json()}catch{throw new dZ("invalid_response","reset credit list response was not valid JSON",X.status)}if(!I5(z))throw new dZ("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((B)=>{let Q=l8(B);return Q===void 0?[]:[Q]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function E5(Z){return[...Z].filter(m6).sort(($,J)=>Date.parse($.expiresAt)-Date.parse(J.expiresAt))[0]}function m6(Z){return Z.status==="available"&&Z.isSupportedByPlan&&Z.resetType==="codex_rate_limits"}function w6(Z){return Z.filter(m6).length}function i9(Z){return Z==="reset"||Z==="already_redeemed"||Z==="nothing_to_reset"||Z==="no_credit"}async function d8(Z,$,J,X,z){let G;try{G=await Z(y8,{method:"POST",headers:{...E6($,R6,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:X}),signal:AbortSignal.timeout(v8)})}catch(W){return{kind:"ambiguous",raw:W}}let B;try{B=await G.text()}catch(W){return G.ok?{kind:"ambiguous",raw:W}:{kind:"http_error",raw:W,status:G.status}}let Q=B,Y=!1;try{Q=JSON.parse(B),Y=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Q,status:G.status};if(!Y||!I5(Q)||!i9(Q.code))return{kind:"ambiguous",raw:Q};return{kind:Q.code,raw:Q}}function A6(Z){if(Z.kind==="cooldown")throw new ZZ("cooldown_active","reset credit redemption is cooling down",Z.cooldownUntil);throw Error(`unexpected reset state decision: ${Z.kind}`)}function S6(){throw new ZZ("expired_unreconciled","the previous reset attempt outcome is unknown")}function I6(Z,$){return{target:Z,selectedCredit:void 0,beforeState:$,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function c8(Z){if(Z.kind==="reset"||Z.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if(Z.kind==="nothing_to_reset"||Z.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(S5(Z))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 s8(Z,$){if(Z)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($)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 u6(Z,$){if(!RZ($.accountKey))throw new ZZ("invalid_account_key","the reset account key is reserved");let J=await Z.resolveTarget($.accountKey);if(J.chatgptAccountId!==$.expectedChatgptAccountId)throw new ZZ("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=J.chatgptAccountId,z=J.accountKey==="main"?void 0:X,G=await x8(Z,$.accountKey);if(G.kind==="corrupt"){if(G=await m8(Z,$.accountKey),G.kind==="corrupt")return I6(J,G.beforeState)}if(G.kind==="cooldown")A6(G);let B;if(G.kind==="claim")B=G.claim;else if(G.kind==="expired_unreconciled"&&($.retry||!k6(G.claim.inFlight,X))){if(!$.retry)S6();B=G.claim}else{if($.retry)throw new ZZ("retry_without_inflight","there is no active reset credit redemption to retry");let[j,F]=await Promise.all([Z.fetchUsage(J),n9(Z.fetchImpl,J.accessToken,z)]),U=a9(j,Z.hasActiveRateLimitMark($.accountKey),Z.now());if(!U.ok)throw new ZZ("not_exhausted",U.reason);if(!E5(F.credits))throw new ZZ("no_eligible_credit","no eligible reset credit was returned");let q=await w8(Z,$.accountKey,F.credits,X);if(q.kind==="corrupt")return I6(J,q.beforeState);if(q.kind==="cooldown")A6(q);if(q.kind==="expired_unreconciled")S6();if(q.kind!=="claim")throw new ZZ("no_eligible_credit","no eligible reset credit was available while claiming");B=q.claim}f8(B.inFlight,X);let Q=await d8(Z.fetchImpl,J.accessToken,z,B.inFlight.creditId,B.inFlight.redeemRequestId),Y,W=!1;try{Y=await u8(Z,$.accountKey,B.inFlight,Q,X)}catch{W=!0}let H=W&&i9(Q.kind),V=S5(Q)&&!W&&Y?.rejectedStatus!==void 0;return{target:J,selectedCredit:B.selectedCredit,beforeState:G.beforeState,outcome:Q,retrySafety:H?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":S5(Q)&&!V?s8(W,Y):c8(Q),...V?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}async function p6(Z){let $=[];for(let J of Z)try{$.push(...await J.run())}catch(X){$.push({code:"doctor-check-failed",message:`Check ${J.id} failed: ${X instanceof Error?X.message:String(X)}`})}return{findings:$}}function l6(Z,$){let J=[Z];if($.findings.length===0)return J.push("No problems found."),J;for(let X of $.findings){let z=X.repair?" (repair available)":"";J.push(`- ${X.message}${z}`)}return J}async function d6(Z,$){let J={applied:[],declined:[],failed:[]};for(let X of $.findings){let z=X.repair;if(!z)continue;if(!await Z.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}),Z.print(`Repair failed: ${z.label}: ${G instanceof Error?G.message:String(G)}`)}}return J}function r9(Z){let $=Z.title??"Auth doctor";return{id:"doctor",label:Z.label??"Auth doctor",hint:"check accounts and offer repairs",async run(J){let X=await p6(Z.checks);for(let B of l6($,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 d6(J,X);J.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as a8}from"node:child_process";function s6(Z,$=process.platform,J=a8){try{if($==="win32"){let z=`Start-Process '${Z.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($==="darwin"?"open":"xdg-open",[Z],{stdio:"ignore"});return X.on("error",()=>{}),X.unref(),X.pid!==void 0}catch{return!1}}function c6(Z,$){if(Z.print(""),Z.print("Open this URL in your browser and complete sign-in:"),Z.print(""),Z.print($.url),Z.print(""),$.instructions)Z.print($.instructions),Z.print("")}async function b5(Z,$){let J=new AbortController,X=await Z.begin({headless:!1,signal:J.signal});X.completion.catch(()=>{}),c6($,X);let z=!1;try{z=await(Z.openBrowser??s6)(X.url)!==!1}catch{z=!1}if(!z)J.abort(),$.print("Could not open a browser. Switching to device authorization."),$.print(""),X=await Z.begin({headless:!0}),c6($,X);return X.completion}var S={hide:"\x1B[?25l",show:"\x1B[?25h",up:(Z=1)=>`\x1B[${Z}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 o9(Z){let $=Z.toString(),J=[];for(let X=0;X<$.length;){let z=$[X];if(z==="\x1B"){let G=$.slice(X,X+3),B=G[1]==="["||G[1]==="O"?G[2]:void 0;if(B&&"ABCD".includes(B)){let Y={A:"up",B:"down",C:"right",D:"left"}[B];if(Y)J.push(Y);X+=3}else if(X+1===$.length){if(X===0)J.push("escape-start");X+=1}else if(($[X+1]==="["||$[X+1]==="O")&&X+2>=$.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 a6=`${String.fromCharCode(27)}\\[[0-9;]*m`,n8=new RegExp(a6,"g"),i8=new RegExp(`^${a6}`);function n6(Z){return Z.replace(n8,"")}function cZ(Z,$){if($<=0)return"";if(n6(Z).length<=$)return Z;let J=$>=3?"...":".".repeat($),X=Math.max(0,$-J.length),z="",G=0,B=0;while(G<Z.length&&B<X){if(Z[G]==="\x1B"){let Q=Z.slice(G).match(i8);if(Q){z+=Q[0],G+=Q[0].length;continue}}z+=Z[G],G+=1,B+=1}return z.includes("\x1B[")?`${z}${S.reset}${J}`:z+J}function t9(){return{input:process.stdin,output:process.stdout,signals:process}}function sZ(Z){return Z.input.isTTY===!0}function e9(Z,$=""){Z.output.write(`${$}
4
+ `)}var r8=50;function o8(Z){if(Z==="red")return S.red;if(Z==="cyan")return S.cyan;return""}async function B1(Z,$,J){if(!sZ(Z))throw Error("Interactive select requires a TTY terminal");if($.length===0)throw Error("No menu items provided");let{input:X,output:z,signals:G}=Z,B=0,Q=null,Y=!1,W=0,H=()=>{let V=z.columns??80,j=z.rows??24,F=W;if(J.clearScreen)z.write(S.clearScreen+S.moveTo(1,1));else if(F>0)z.write(S.up(F));let U=0,q=(T)=>{z.write(`${S.clearLine}${T}
5
+ `),U+=1},K=J.lines??[],N=1+(J.subtitle?3:0)+K.length+(K.length?1:0),M=Math.max(1,Math.min($.length,j-N-2-1)),O=Math.max(0,Math.min(B-Math.floor(M/2),Math.max(0,$.length-M))),_=$.slice(O,O+M);if(q(`${S.dim}┌ ${S.reset}${cZ(J.message,Math.max(1,V-4))}`),J.subtitle)q(`${S.dim}│${S.reset}`),q(`${S.cyan}◆${S.reset} ${cZ(J.subtitle,Math.max(1,V-4))}`),q("");for(let T of K)q(`${S.cyan}│${S.reset} ${cZ(T,Math.max(1,V-4))}`);if(K.length)q(`${S.cyan}│${S.reset}`);for(let T=0;T<_.length;T++){let A=_[T];if(!A)continue;let L=O+T===B,I=o8(A.color),x=I?`${L?"":S.dim}${I}${A.label}${S.reset}`:L?A.label:`${S.dim}${A.label}${S.reset}`;if(A.hint)x+=` ${S.dim}${A.hint}${S.reset}`;x=cZ(x,Math.max(1,V-8)),q(L?`${S.cyan}│${S.reset} ${S.green}●${S.reset} ${x}`:`${S.cyan}│${S.reset} ${S.dim}○${S.reset} ${x}`)}let D=_.length<$.length?` (${O+1}-${O+_.length}/${$.length})`:"";q(`${S.cyan}│${S.reset} ${S.dim}${cZ(`Up/Down to select | Enter: confirm | Esc: back${D}`,Math.max(1,V-6))}${S.reset}`),q(`${S.cyan}└${S.reset}`);for(let T=U;T<F;T++)q("");W=U};return new Promise((V)=>{let j=X.isRaw??!1,F=()=>{if(Y)return;if(Y=!0,Q)clearTimeout(Q);X.removeListener("data",K);try{X.setRawMode(j),X.pause(),z.write(S.show)}catch{}G?.removeListener("SIGINT",q),G?.removeListener("SIGTERM",q)},U=(N)=>{F(),V(N)},q=()=>U(null),K=(N)=>{for(let M of o9(N)){if(Y)break;if(Q)clearTimeout(Q),Q=null;switch(M){case"up":B=(B-1+$.length)%$.length,H();break;case"down":B=(B+1)%$.length,H();break;case"enter":U($[B]?.value??null);break;case"escape":U(null);break;case"escape-start":Q=setTimeout(()=>U(null),r8);break;default:break}}};G?.once("SIGINT",q),G?.once("SIGTERM",q);try{X.setRawMode(!0)}catch{F(),V(null);return}X.resume(),z.write(S.hide),H(),X.on("data",K)})}async function Z$(Z,$,J=!1){if(!sZ(Z))return!1;return await B1(Z,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:$})??!1}function i6(Z){let $=sZ(Z);return{terminal:Z,interactive:$,print:(J)=>e9(Z,J),confirm:(J,X)=>Z$(Z,J,X),select:async(J,X)=>$&&J.length>0?B1(Z,J,X):null}}function t8(Z,$){if(Z.print($.title),$.subtitle)Z.print($.subtitle);for(let J of $.status??[])Z.print(` ${J}`);Z.print(""),Z.print("Actions:");for(let J of $.actions)Z.print(J.hint?` - ${J.label} (${J.hint})`:` - ${J.label}`);return Z.print(""),Z.print("This menu needs an interactive terminal to choose an action; nothing was changed."),{status:"not-interactive"}}async function y1(Z){let $=Z.terminal??t9(),J=i6($);if(!J.interactive)return t8(J,Z);if(Z.actions.length===0)return J.print("No actions are available."),{status:"cancelled"};let X=await B1($,Z.actions.map((z)=>({label:z.label,value:z,color:z.destructive?"red":"cyan",...z.hint?{hint:z.hint}:{}})),{message:Z.title,subtitle:Z.subtitle??"Select an account action",...Z.status?{lines:Z.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 o6="disabled from the auth menu",r6=8;async function _Z(Z){let $=await Z.read();if($.status==="ready")return{rows:$.rows};if($.status==="pending-migration")return{rows:[],problem:"The account store has not been migrated yet."};return{rows:[],problem:`The account store could not be read (${$.file}: ${$.reason}).`}}async function e8(Z){let{rows:$}=await _Z(Z);return $.some((J)=>J.credential!==void 0)}function X$(Z){let $=[];if(Z.label)$.push(Z.label);if(Z.invalid)$.push(`invalid ${Z.invalid}`);else if(!Z.enabled)$.push(Z.disabledReason?`disabled: ${Z.disabledReason}`:"disabled");else $.push("enabled");if(!Z.credential&&!Z.invalid)$.push("no credential");return $.join(", ")}function Z2(Z){if(Z.problem)return[Z.problem];if(Z.rows.length===0)return["No accounts yet."];let $=Z.rows.slice(0,r6).map((X)=>`${X.id}: ${X$(X)}`),J=Z.rows.length-r6;if(J>0)$.push(`... and ${J} more`);return $}function $2(Z){return Z instanceof Error?Z.message:String(Z)}async function z$(Z,$,J){if($.length===0)return Z.print("There are no accounts."),null;return Z.select($.map((X)=>({label:X.id,value:X,hint:X$(X)})),{message:J})}function J2(Z,$){let J=new Set($.map((X)=>X.id));if(Z.id&&!J.has(Z.id))return Z.id;for(let X=1;;X++){let z=`account-${X}`;if(!J.has(z))return z}}function t6(Z,$=Date.now()){let J=fZ(Z.quota)?CZ(Z.quota):void 0,X=y5(J,{now:$,form:"full"});return(X.length>0?X:[PZ(J,{now:$})]).map((z)=>` ${z}`)}function e6(Z){return{id:"add-account",label:"Add account",hint:"sign in to another account",async run($){let J=Z.login;if(!J)throw Error("No login is configured");let X=await b5(J,$),{rows:z}=await _Z(Z.store),G=(Z.newAccountId??J2)(X,z),B=await Z.store.add({id:G,credential:X.credential,...X.identity!==void 0?{identity:X.identity}:{},...X.label!==void 0?{label:X.label}:{}},Z.extraLocks?{extraLocks:Z.extraLocks}:{});if(B.outcome==="rotated")$.print(`That sign-in is already account ${B.id}; its credential was updated.`);else if(B.outcome==="added-disabled")$.print(`Added account ${B.id}, disabled: another enabled account is the same provider account.`);else if(B.outcome==="completed")$.print(`Finished adding account ${B.id}.`);else $.print(`Added account ${B.id}.`)}}}function Z7(Z){return{id:"reauthenticate",label:"Re-authenticate account",hint:"sign an account in again",async run($){let J=Z.login;if(!J)throw Error("No login is configured");let{rows:X}=await _Z(Z.store),z=await z$($,X,"Re-authenticate which account?");if(!z)return;let G=await b5(J,$);if(G.identity!==void 0&&z.identity!==void 0&&G.identity!==z.identity){$.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 Z.store.replace(z.id,G.credential,B!==void 0?{identity:B}:{},Z.extraLocks?{extraLocks:Z.extraLocks}:{}),$.print(`Updated the sign-in of account ${z.id}.`)}}}function $7(Z){return{...Z.protect?{protect:Z.protect}:{},...Z.extraLocks?{extraLocks:Z.extraLocks}:{}}}function J7(Z){return Z instanceof R&&Z.kind==="row-protected"?Z.message:void 0}function X7(Z){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run($){let{rows:J}=await _Z(Z.store),X=await z$($,J,"Remove which account?");if(!X)return;if(!await $.confirm(`Remove account ${X.id}?`)){$.print("Cancelled; nothing was changed.");return}try{await Z.store.remove(X.id,$7(Z))}catch(z){let G=J7(z);if(G===void 0)throw z;$.print(`Account ${X.id} was kept: ${G}`);return}$.print(`Removed account ${X.id}.`)}}}function $$(Z){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run($){let{rows:J}=await _Z(Z.store),X=await z$($,J,"Enable or disable which account?");if(!X)return;let z=Z.extraLocks?{extraLocks:Z.extraLocks}:{};if(X.enabled){await Z.store.disable(X.id,Z.disableReason??o6,z),$.print(`Disabled account ${X.id}.`);return}try{await Z.store.enable(X.id,z)}catch(G){if(G instanceof R&&G.kind==="duplicate-identity"){$.print(`Account ${X.id} stays disabled: another enabled account is the same provider account.`);return}throw G}$.print(`Enabled account ${X.id}.`)}}}function z7(Z){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run($){let J=await _Z(Z.store);if(J.problem){$.print(J.problem);return}if(J.rows.length===0)$.print("No accounts yet.");for(let X of J.rows)$.print(`${X.id}: ${X$(X)}`)}}}function J$(Z){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run($){let J=await _Z(Z.store);if(J.problem){$.print(J.problem);return}let X=new Map,z=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 Q=await z(B);await Z.store.recordQuota(B.id,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(Q){X.set(B.id,$2(Q))}}let G=await _Z(Z.store);if(G.rows.length===0)$.print("No accounts yet.");for(let B of G.rows){$.print(`${B.id}:`);let Q=X.get(B.id);if(Q)$.print(` quota check failed: ${Q}`);for(let Y of t6(B,(Z.now??Date.now)()))$.print(Y)}}}}function G7(Z){return{id:"delete-all",label:"Delete all accounts",destructive:!0,confirm:"Delete every account? Accounts the plugin keeps are not deleted.",async run($){let J=await _Z(Z.store);if(J.problem){$.print(J.problem);return}let X=[],z=[];for(let G of J.rows)try{await Z.store.remove(G.id,$7(Z)),X.push(G.id)}catch(B){let Q=J7(B);if(Q===void 0)throw B;z.push(`${G.id} (${Q})`)}if($.print(`Deleted ${X.length} account(s).`),z.length>0)$.print(`Kept: ${z.join(", ")}.`)}}}async function G$(Z){return B7(Z,await Z.custody?.()===!0)}function B7(Z,$){let J=Z.doctor?.length?[r9({checks:Z.doctor})]:[],X=[...Z.extraActions??[]];if($)return[z7(Z),$$(Z),J$(Z),...J,...X];return[...Z.login?[e6(Z),Z7(Z)]:[],X7(Z),$$(Z),J$(Z),...J,...X,G7(Z)]}async function X2(Z){let $=await Z.custody?.()===!0,J=B7(Z,$),[X,z]=await Promise.all([_Z(Z.store),Z.status?.()??[]]);return y1({title:Z.title,subtitle:$?"Accounts come from the vault; select an action":"Select an account action",status:[...z,...Z2(X)],actions:J,...Z.terminal?{terminal:Z.terminal}:{}})}function Q7(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function W7(Z){return Z!==void 0}function z2(Z){return async($)=>{if(!W7($))return Z.login();if(!await Z.hasCredential())return Z.login($);return await Z.openMenu($),Q7()}}function $Z(Z){return Z.authority!=="local"}async function i(Z){return{authority:await Z.authority(),status:await Z.status(),identities:Z.identities(),routes:new Set(Z.routes().map(($)=>$.id))}}async function k5(Z){let $;try{return await Promise.race([Promise.resolve().then(()=>Z.refresh()).then(()=>{return},(J)=>J instanceof Error?J.message:String(J)),new Promise((J)=>{$=setTimeout(()=>J("Vault roster refresh did not finish within the roster wait budget."),C6)})])}finally{clearTimeout($)}}function jZ(Z){return Z.email||Z.label||Z.routeId}function Y7(Z,$){let J=CZ(fZ(Z.quota)?Z.quota:void 0),X=y5(J,{now:$});return(X.length>0?X:[PZ(J,{now:$})]).map((z)=>` ${z}`)}var k1="Accounts are managed in the vault with ck. Disconnect to use local accounts.",aZ="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function H7(Z){let $=[...Z.label?[Z.label]:[],Z.invalid?`invalid ${Z.invalid}`:Z.enabled?"enabled":`disabled${Z.disabledReason?`: ${Z.disabledReason}`:""}`];return`${Z.id}: ${$.join(", ")}`}async function G2(Z,$){let J=await k5($),X=await i($),{status:z}=X,G=$Z(X)?void 0:await Z.store.read(),B=await G$(Z),Q=new Set(["check-quotas",...(Z.extraActions??[]).map((H)=>H.id)]),Y=B.filter((H)=>!$Z(X)||Q.has(H.id)).map((H)=>({...H,run:async(V)=>{if(!Q.has(H.id)&&$Z(await i($))){V.print(aZ);return}await $.authority(),await H.run(V)}})),W=Y.find((H)=>H.id==="check-quotas");if(W)W.run=async(H)=>{await k5($);let V=await i($),j=$Z(V)?void 0:await Z.store.read();if(!j)H.print(k1);else if(j.status!=="ready")H.print("The local account store could not be read.");else for(let q of j.rows){H.print(H7(q));try{if(Z.pollQuota&&q.credentialEpoch!==void 0){let M=await Z.pollQuota(q);await Z.store.recordQuota(q.id,{credentialEpoch:q.credentialEpoch,...q.identity!==void 0?{identity:q.identity}:{}},M)}}catch(M){H.print(` quota check failed: ${M instanceof Error?M.message:String(M)}`)}let K=await Z.store.read(),N=K.status==="ready"?K.rows.find((M)=>M.id===q.id):void 0;for(let M of Y7(N??q,(Z.now??Date.now)()))H.print(M)}let F=V.routes;for(let q of $.snapshot()?.rows??[]){if(H.print(`Vault ${jZ(q)}: ${q.enabled?q.state:"declined"}`),!F.has(q.routeId)){H.print(" quota check skipped: account is not enabled and active");continue}let K=await $.pollQuota(q.routeId);if(!K.ok)H.print(` quota check failed: ${K.error??"vault unavailable"}`);let N=$.snapshot()?.rows.find((M)=>M.routeId===q.routeId);for(let M of Y7({quota:N?.quota},(Z.now??Date.now)()))H.print(M)}let U=await $.status();if(U.lastError)H.print(`Claustrum vault unreachable: ${U.lastError}`)};return y1({title:Z.title,subtitle:"Select an account action",status:[...await Z.status?.()??[],...J?[`Last error: ${J}`]:[],...z.lastError?[`Claustrum vault unreachable: ${z.lastError}`]:[],...z.accounts.map((H)=>`Vault ${jZ(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!G?[k1]:G.status==="ready"?G.rows.map((H)=>H7(H)):["The local account store could not be read."]],actions:Y,...Z.terminal?{terminal:Z.terminal}:{}})}function V7(Z){return k(Z)?{...Z}:{}}function B$(Z,$){let J=fZ($)?U7($.credits):void 0;return J?`${Z} · prepaid ${J}`:Z}function q7(Z,$){return{...Z,sections:Z.sections.map((J)=>J.id!=="quota"?J:{...J,items:J.items.map((X)=>X.detail===void 0?X:{...X,detail:B$(X.detail,$.get(X.id))})})}}function v5(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 Q=await Z.apply({command:Z.command,sectionId:$,...X?{itemId:X}:{},actionId:J.id,values:G,confirmed:!0},B);return{ok:Q.ok,text:Q.text,...Q.code?{code:Q.code}:{}}}}}function Q$(Z,$){return new Proxy(Z,{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((W)=>({...W,label:W.label??W.id}))};if(!$)return B;let Q=await i($);if(!$Z(Q))return B;let Y=[...Q.status.accounts.map((W)=>({id:W.routeId,label:jZ(W),type:"oauth",enabled:W.enabled,identity:W.accountIdentity,quota:W.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:Y}};if(X==="readSettings")return async()=>{let G=await J.readSettings();if(G.status==="error"||!$)return G;let B=await i($),Q=V7(G.settings.killswitch);if(!$Z(B)||!G.settings.killswitch)return G;let Y=V7(Q.accounts);for(let W of B.status.accounts)Y[W.routeId]=v1({version:1,accounts:[],...G.settings},W.routeId);return{...G,settings:{...G.settings,killswitch:{...Q,accounts:Y}}}};let z=Reflect.get(J,X);return typeof z==="function"?z.bind(J):z}})}function W$(Z,$,J={}){let X=pZ(Z),z=(W)=>pZ({command:Z.command,title:Z.title,store:Q$(Z.store,$),accounts:Z.accounts,quota:Z.quota,limits:Z.limits,routing:{...Z.routing,formerMainId:W??"",vaultOrder:async()=>{let H=await i($);if(!$Z(H))return;return{rows:H.status.accounts.map((V)=>({id:V.routeId,label:jZ(V)})),reorder:async(V)=>{if(!$Z(await i($)))throw new u("vault-local-action",aZ);return $.reorder(V)}}}},...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.now?{now:Z.now}:{}}),G=async(W,H)=>{let V=await i($),j=$Z(V),F=j7(V.status.accounts.map((L)=>({id:L.routeId,credentialId:L.credentialId}))),U=j?z(F):X,K=(await U.open(H)).menu.sections.find((L)=>L.id===W);if(!K)throw new u("unavailable","The account menu is unavailable.");if(!j)return{lines:K.lines,items:K.items.map((L)=>({...L,actions:L.actions.map((I)=>v5(U,W,I,L.id))})),actions:K.actions.map((L)=>v5(U,W,L))};let N=new Map(V.status.accounts.map((L)=>[L.routeId,L])),M=(Z.now??Date.now)(),O=(L)=>({id:"check",label:L?"Check this account":"Check now",group:"Actions",run:async()=>{let x=[...(await i($)).routes].filter((b)=>!L||b===L);if(L&&x.length===0)throw new u("unavailable","This vault account cannot be checked right now.");for(let b of x){let g=await $.pollQuota(b);if(!g.ok)throw new u("quota-check-failed",`${b}: ${g.error??"vault unavailable"}`)}return`Checked quota for ${x.length} account${x.length===1?"":"s"}.`}});if(W==="quota"){let L=(I,x)=>PZ(CZ(I.quota,Z.quota?.scope),{now:M,form:x});return{lines:V.status.accounts.filter((I)=>!V.routes.has(I.routeId)).map((I)=>`${jZ(I)} (${I.enabled?I.state:"disabled"}): ${B$(L(I,"compact"),I.quota)}`),items:V.status.accounts.filter((I)=>V.routes.has(I.routeId)).map((I)=>({id:I.routeId,label:jZ(I),group:"Accounts",status:L(I,"compact"),detail:B$(L(I,"full"),I.quota),actions:[O(I.routeId)]})),actions:V.routes.size>0?[O()]:[]}}let _=K.items.map((L)=>{let I=N.get(L.id),x=I&&W==="accounts"?`Vault · ${I.credentialType==="oauth"?"login":"API key"} · ${I.state} · ${I.enabled?"enabled":"declined"}`:L.detail;return{id:L.id,label:L.label,detail:x,group:L.group,status:I&&W==="accounts"?I.enabled?I.state:"disabled":L.status,...L.facts?{facts:L.facts}:{},actions:I&&W!=="limits"?[]:L.actions.map((b)=>v5(U,W,b,L.id))}}),D=K.actions.filter((L)=>V.status.accounts.length>0&&(W==="limits"||W==="routing"&&(L.id==="mode"||L.id==="order"))).map((L)=>v5(U,W,L)),T=K.actions.find((L)=>L.id==="mode")?.knobs.find((L)=>L.id==="mode"),A=W==="routing"&&F===null&&T?.kind==="choice"&&(T.value==="main-first"||T.value==="fallback-first");return{lines:W==="accounts"?[...V.status.discovered?[`${V.status.accounts.length} vault account${V.status.accounts.length===1?"":"s"}`,`${V.routes.size} can route`]:["Connected · waiting for the vault's first answer"],k1]:[...K.lines,...A?["No default vault account, so this mode orders like Ordered"]:[]],items:_,actions:D}},B=pZ({...Z,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(W)=>G("accounts",W)},quota:{title:"Quota",build:(W)=>G("quota",W)},routing:{title:"Routing",build:(W)=>G("routing",W)},limits:{title:"Limits",build:(W)=>G("limits",W)}},extras:Z.extras?.map((W)=>W.id!=="reset"?W:{...W,build:async(H)=>{let V=await i($);if($Z(V))return{lines:[k1]};return W.build(H)}})}),Q=async()=>{if(!$Z(await i($)))return{menu:X,error:void 0};let W=J.refresh===!1?void 0:await k5($);return{menu:B,error:W}},Y=async(W,H)=>{let V=await W.menu.open(H);if(W.error)V.menu.sections.find((F)=>F.id==="vault")?.lines.push(`Last error: ${W.error}`);return V};return{command:Z.command,open:async(W)=>Y(await Q(),W),apply:async(W,H)=>{let V=await Q(),{menu:j}=V;if(j===B&&(W.sectionId==="accounts"||W.sectionId==="reset"||W.sectionId==="quota"&&(await i($)).routes.size===0||W.sectionId==="limits"&&W.itemId!==void 0&&!(await i($)).status.accounts.some((F)=>F.routeId===W.itemId)))return{...await Y(V,H),ok:!1,code:"vault-local-action",text:aZ};if(J.refuseApply)return{...await Y(V,H),ok:!1,...J.refuseApply};return j.apply(W,H)}}}var h1="openai",M7="OpenAI accounts",xZ="main",P7="that account is already your main account, so it was not added again",XZ=s("commands"),C7=new Set(["__proto__","constructor","prototype"]);function B2(Z,$){let J={version:1,accounts:[],killswitch:Z},X=k(Z.accounts)?Object.keys(Z.accounts):[],z={};for(let Q of new Set([xZ,...$,...X])){if(C7.has(Q))continue;let Y=v1(J,Q===xZ?void 0:Q);z[Q]={primary:Y.primary,secondary:Y.secondary}}let G=v1(J,void 0),B={...Z};return delete B.main,B.accounts=z,B.defaults={primary:G.primary,secondary:G.secondary},B.schema=f1,B}function Q2(Z,$){let J=k(Z.accounts)?{...Z.accounts}:{};for(let z of new Set([xZ,...$])){if(C7.has(z)||Object.hasOwn(J,z))continue;J[z]={primary:g1.primary,secondary:g1.secondary}}let X=k(Z.defaults)?Z.defaults:{primary:g1.primary,secondary:g1.secondary};return{...Z,accounts:J,defaults:X,schema:f1}}function F7(Z,$){let J=!1;if(k(Z.cachekeep))Z.cacheKeep={...Z.cachekeep,...k(Z.cacheKeep)?Z.cacheKeep:{}},delete Z.cachekeep,J=!0;let X=Z.killswitch;if(k(X)&&X.schema!==f1)Z.killswitch=B2(X,$),J=!0;return J}async function K7(Z){let $=await Z.read();return $.status==="ready"?$.rows.map((J)=>J.id):[]}function V$(Z){let $=async()=>{let X=await Z.readSettings();if(X.status==="error")return X;let z=structuredClone(X.settings);return F7(z,await K7(Z)),{...X,settings:z}},J=async(X,z)=>{let G=await K7(Z);return Z.updateSettings(async(B)=>{F7(B,G);let Q=await X(B)??B;if(k(Q.killswitch)&&Q.killswitch.schema!==f1)Q.killswitch=Q2(Q.killswitch,G);return Q},z)};return new Proxy(Z,{get(X,z){if(z==="readSettings")return $;if(z==="updateSettings")return J;let G=Reflect.get(X,z,X);return typeof G==="function"?G.bind(X):G}})}function W2(Z,$){let J=(Y,W)=>$.rowLocks?$.rowLocks(Y):W,X=(Y,W)=>{let H=J(Y,W?.extraLocks);return{...W??{},...H?{extraLocks:H}:{}}},z=(Y,W,H,V)=>Z.replace(Y,W,H,X(Y,V)),Q={add:async(Y,W)=>{let H=await Z.read(),j=(H.status==="ready"?H.rows:[]).filter((K)=>K.type==="oauth"&&!K.invalid),F=Y.identity?j.find((K)=>K.identity===Y.identity):void 0;if(F?.id===xZ)throw new u("main-account",P7);let U=F??j.find((K)=>K.id===Y.id&&K.id!==xZ);if(!U||Y.credential.type!=="oauth")return Z.add(Y,W);let q=await z(U.id,Y.credential,Y.identity!==void 0?{identity:Y.identity}:{},W?.extraLocks?{extraLocks:W.extraLocks}:void 0);return XZ.info("account signed in again",{id:U.id}),{id:q.id,outcome:"rotated",credential:q.credential,credentialEpoch:q.credentialEpoch}},replace:z,enable:(Y,W)=>Z.enable(Y,X(Y,W)),disable:(Y,W,H)=>Z.disable(Y,W,X(Y,H)),remove:(Y,W)=>Z.remove(Y,X(Y,W))};return new Proxy(Z,{get(Y,W){if(Object.hasOwn(Q,W))return Q[W];let H=Reflect.get(Y,W,Y);return typeof H==="function"?H.bind(Y):H}})}async function fQ(Z,$,J){await V$(Z).updateSettings((X)=>{J(X);return},$?{extraLocks:$}:{})}var Y2=["version","accounts","commonAuthPool"];function xQ(Z,$){return async(J)=>{let X;if(await V$(Z).updateSettings((z)=>{let G={...z,version:1,accounts:[]},B=J(G)??G;X=B;let Q={...B};for(let Y of Y2)delete Q[Y];return Q},$?{extraLocks:$}:{}),!X)throw Error("the settings write did not run");return X}}var H2="migration";function N7(Z){let $=["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.",Z.length>0?"These processes still hold the move back:":"No running process holds the move back."],J={command:h1,title:M7,sections:[{id:H2,slot:"extra",title:"Accounts are moving",lines:$,items:Z.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 H$(J)}var V2=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function U2(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");if(V2.has($))return!0;return $.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function Y$(Z,$,J){if(Array.isArray(Z))return Z.map((z,G)=>Y$(z,`${$}[${G}]`,J));if(!k(Z))return Z;let X={};for(let[z,G]of Object.entries(Z)){if(U2(z)){J.push(`${$}.${z}`);continue}X[z]=Y$(G,`${$}.${z}`,J)}return X}function H$(Z){let $=[],J=Y$(Z,"menu",$);if($.length>0)XZ.warn("credential-shaped field stripped before RPC",{fields:$});return J}function j2(Z){return{id:Z.id,credential:{type:"oauth",refresh:Z.refresh,...Z.access!==void 0?{access:Z.access}:{},...Z.expires!==void 0?{expires:Z.expires}:{}},...Z.accountId!==void 0?{identity:Z.accountId}:{},...Z.label!==void 0?{label:Z.label}:{}}}function q2(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 Z.begin({...X!==void 0?{label:X}:{},headless:z}),B=z?`Open this verification URL:
6
6
 
7
7
  ${G.url}
8
8
 
@@ -14,11 +14,11 @@ ${G.url}
14
14
 
15
15
  ${G.instructions}
16
16
 
17
- The account is added when you finish.`,Q=G.completion.then(async(Y)=>{if($&&await $.authority()!=="local")throw new u("vault-local-action",sZ);let W=await Z.mainIdentity?.();if(Y.id===xZ||Y.accountId&&W&&Y.accountId===W)throw XZ.warn("account add rejected (main identity)",{id:Y.id}),new u("main-account",M7);return XZ.info("account added",{id:Y.id}),H2(Y)});return{status:"pending",message:B,completion:Q}}}}function fQ(Z){return{id:"session",title:"This session",build:async($)=>{let J=$.sessionId;if(!J)return{lines:["No current session"]};let X=await Z.getPin?.(J);return{lines:[X?`Pinned to ${X}`:"No sticky pin"],actions:Z.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 Z.clearPin?.(z.sessionId),XZ.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 hQ(Z){let{vault:$}=Z;return{id:"vault",title:"Vault",build:async()=>{let J=await $.status(),X=await $.authority()!=="local",z=$.routes().length;return{lines:[X?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}`,C6(J.host,J.name,J.enrollment),...O5(J.name,J.enrollment),...X&&J.discovered?[J.accounts.length===0?D5(J.name,$.grantReach()):`The vault serves ${J.accounts.length} OpenAI account${J.accounts.length===1?"":"s"}; ${z} can route now.`]:[],...X&&$.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((G)=>({id:G.routeId,label:jZ(G),group:"Accounts",status:G.enabled?G.state:"disabled",detail:[G.credentialType==="api_key"?"API key":"login",G.state==="active"?"active":`vault state ${G.state}`,G.enabled?"enabled":"disabled here"].join(", "),actions:[G.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 $.decline(G.routeId),await Z.changed?.(),`${jZ(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await $.accept(G.routeId),await Z.changed?.(),`${jZ(G)} is enabled on this host.`}}]})),actions:X?[{id:"disconnect",label:"Disconnect",description:"Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",confirm:"Disconnect from the vault? Connecting again needs a new approval with `ck`.",run:async()=>{return await $.disconnect(),await Z.changed?.(),`Disconnected: ${$.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${$.name}\` to revoke it in the vault too.`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:G})=>{let B=await $.connectStep();if(B.state!=="pending"&&B.state!=="busy")return await Z.changed?.(),d9($,B);return $.waitForApproval(Z.wait).then(async(Q)=>{await Z.changed?.();let Y=d9($,Q);G.notify(Y.text,Y.ok?"info":"warning")}).catch((Q)=>{G.notify(`Connecting to the vault failed: ${Q instanceof Error?Q.message:String(Q)}`,"error")}),{ok:!0,text:[...O5($.name,B),"Waiting for the approval; you are told here when it lands."].join(`
18
- `)}}}]}}}}async function K7(Z,$,J){if(!RZ($))return JZ($,"invalid_account_key","That account cannot take a reset credit.");let X;try{let z=(await Z.loadAccounts({configPath:Z.configPath,statePath:Z.statePath}))?.reset?.[$];if(J||z&&Object.hasOwn(z,"inFlight"))X=(await Z.resolveResetTarget($)).chatgptAccountId;else{let B=await C7($,Z);if(!B.eligible)return JZ($,"not_eligible",T7(B));X=B.chatgptAccountId}if(!X)return JZ($,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");XZ.info("reset redemption decision",{accountKey:$,retry:J});let G=await m6({configPath:Z.configPath,statePath:Z.statePath,mutateAccountsFn:Z.mutateAccounts,loadAccountsFn:Z.loadAccounts,now:Z.now,randomUUID:Z.randomUUID,fetchImpl:Z.fetchImpl,resolveTarget:Z.resolveResetTarget,fetchUsage:(B)=>E1({accessToken:B.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:$,expectedChatgptAccountId:X,retry:J});return XZ.info("reset redemption outcome",{accountKey:$,code:G.outcome.kind}),L7(G,Z,X)}catch(z){let G=N2($,z,X);return XZ.info("reset redemption outcome",{accountKey:$,code:G.code}),G}}function xQ(Z){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await Z.accountKeys()).map(($)=>({id:$,group:"Accounts",label:$===xZ?"Main account":$,actions:[{id:"preview",label:"Preview",description:"Fetch the account's current quota and reset credits before spending a credit.",run:async()=>{let J=await C7($,Z);return{ok:J.eligible,text:`${K2(J)}
17
+ The account is added when you finish.`,Q=G.completion.then(async(Y)=>{if($&&await $.authority()!=="local")throw new u("vault-local-action",aZ);let W=await Z.mainIdentity?.();if(Y.id===xZ||Y.accountId&&W&&Y.accountId===W)throw XZ.warn("account add rejected (main identity)",{id:Y.id}),new u("main-account",P7);return XZ.info("account added",{id:Y.id}),j2(Y)});return{status:"pending",message:B,completion:Q}}}}function mQ(Z){return{id:"session",title:"This session",build:async($)=>{let J=$.sessionId;if(!J)return{lines:["No current session"]};let X=await Z.getPin?.(J);return{lines:[X?`Pinned to ${X}`:"No sticky pin"],actions:Z.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 Z.clearPin?.(z.sessionId),XZ.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 wQ(Z){let{vault:$}=Z;return{id:"vault",title:"Vault",build:async()=>{let J=await $.status(),X=await $.authority()!=="local",z=$.routes().length;return{lines:[X?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}`,_6(J.host,J.name,J.enrollment),...A5(J.name,J.enrollment),...X&&J.discovered?[J.accounts.length===0?P5(J.name,$.grantReach()):`The vault serves ${J.accounts.length} OpenAI account${J.accounts.length===1?"":"s"}; ${z} can route now.`]:[],...X&&$.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((G)=>({id:G.routeId,label:jZ(G),group:"Accounts",status:G.enabled?G.state:"disabled",detail:[G.credentialType==="api_key"?"API key":"login",G.state==="active"?"active":`vault state ${G.state}`,G.enabled?"enabled":"disabled here"].join(", "),actions:[G.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 $.decline(G.routeId),await Z.changed?.(),`${jZ(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await $.accept(G.routeId),await Z.changed?.(),`${jZ(G)} is enabled on this host.`}}]})),actions:X?[{id:"disconnect",label:"Disconnect",description:"Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",confirm:"Disconnect from the vault? Connecting again needs a new approval with `ck`.",run:async()=>{return await $.disconnect(),await Z.changed?.(),`Disconnected: ${$.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${$.name}\` to revoke it in the vault too.`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:G})=>{let B=await $.connectStep();if(B.state!=="pending"&&B.state!=="busy")return await Z.changed?.(),c9($,B);return $.waitForApproval(Z.wait).then(async(Q)=>{await Z.changed?.();let Y=c9($,Q);G.notify(Y.text,Y.ok?"info":"warning")}).catch((Q)=>{G.notify(`Connecting to the vault failed: ${Q instanceof Error?Q.message:String(Q)}`,"error")}),{ok:!0,text:[...A5($.name,B),"Waiting for the approval; you are told here when it lands."].join(`
18
+ `)}}}]}}}}async function D7(Z,$,J){if(!RZ($))return JZ($,"invalid_account_key","That account cannot take a reset credit.");let X;try{let z=(await Z.loadAccounts({configPath:Z.configPath,statePath:Z.statePath}))?.reset?.[$];if(J||z&&Object.hasOwn(z,"inFlight"))X=(await Z.resolveResetTarget($)).chatgptAccountId;else{let B=await _7($,Z);if(!B.eligible)return JZ($,"not_eligible",L7(B));X=B.chatgptAccountId}if(!X)return JZ($,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");XZ.info("reset redemption decision",{accountKey:$,retry:J});let G=await u6({configPath:Z.configPath,statePath:Z.statePath,mutateAccountsFn:Z.mutateAccounts,loadAccountsFn:Z.loadAccounts,now:Z.now,randomUUID:Z.randomUUID,fetchImpl:Z.fetchImpl,resolveTarget:Z.resolveResetTarget,fetchUsage:(B)=>E1({accessToken:B.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:$,expectedChatgptAccountId:X,retry:J});return XZ.info("reset redemption outcome",{accountKey:$,code:G.outcome.kind}),O7(G,Z,X)}catch(z){let G=P2($,z,X);return XZ.info("reset redemption outcome",{accountKey:$,code:G.code}),G}}function uQ(Z){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await Z.accountKeys()).map(($)=>({id:$,group:"Accounts",label:$===xZ?"Main account":$,actions:[{id:"preview",label:"Preview",description:"Fetch the account's current quota and reset credits before spending a credit.",run:async()=>{let J=await _7($,Z);return{ok:J.eligible,text:`${M2(J)}
19
19
 
20
- ${T7(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 K7(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 K7(Z,$,!0);return{ok:J,text:X}}}]}))})}}var U2=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],j2=["primary","secondary"];function mQ(Z){let $=new Set(Z.unavailableSections),J=(W)=>({title:W,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),X=[...Z.extras??[]];if($.has("reset")){let W={id:"reset",...J("Reset credits")},H=X.findIndex((V)=>V.id==="reset");if(H<0)X.unshift(W);else X[H]=W}let z={command:f1,title:N7,store:B$(H$(G2(Z.store,{...Z.rowLocks?{rowLocks:Z.rowLocks}:{}}))),...Z.extraLocks?{extraLocks:Z.extraLocks}:{},accounts:{...Z.login?{login:V2(Z.login,Z.vault)}:{},...Z.protect?{protect:Z.protect}:{},...Z.describeIdentity?{describeIdentity:Z.describeIdentity}:{}},quota:Z.quotaCheck?{check:Z.quotaCheck}:{},routing:{orderedVariants:U2,formerMainId:xZ},limits:{labels:j2},...$.has("cache")?{cache:J("Cache")}:Z.cache?{cache:Z.cache}:{},...$.has("diagnostics")?{diagnostics:J("Diagnostics")}:Z.diagnostics?{diagnostics:Z.diagnostics}:{},extras:X,...Z.logger?{logger:Z.logger}:{},...Z.now?{now:Z.now}:{}},G=Z.vault?Q$(z,Z.vault,{refresh:!Z.readOnly,...Z.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):pZ(z),B=Z.vault?Q$(z,Z.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,Q=(W)=>{let{sessionId:H}=W,V=W.notify.bind(W);return{...H!==void 0?{sessionId:H}:{},notify:V}},Y=async(W)=>{if(Z.vault&&await Z.vault.authority()!=="local")return W;let H=await Z.store.read().catch(()=>{return});if(H?.status!=="ready")return W;return{...W,menu:U7(W.menu,new Map(H.rows.map((V)=>[V.id,V.quota])))}};return{command:f1,async open(W){let H=Q(W),V=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(V&&!V.migrated)return{command:f1,menu:F7(V.blockers)};let j=await G.open(H);return Y({...j,menu:Y$(j.menu)})},async apply(W,H){let V=Q(H),j=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(j&&!j.migrated)return{command:f1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:F7(j.blockers)};if(Z.readOnly&&Z.vault)return G.apply(W,V);if(Z.readOnly||Z.allowAction&&!Z.allowAction(W)||$.has(W.sectionId)){if(B)return B.apply(W,V);return{...await G.open(V),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let F=await G.apply(W,V);if(F.ok)await Z.afterApply?.();return Y({...F,menu:Y$(F.menu)})}}}function P7(Z){let $=[Z.primary?.usedPercent,Z.secondary?.usedPercent].filter((J)=>J!==void 0);return $.length>0?Math.max(...$):void 0}function q2(Z,$){let J=[Z.primary,Z.secondary].filter((z)=>z!==void 0),X=J.filter((z)=>b1(z,$));return(X.length>0?X:J).sort((z,G)=>G.usedPercent-z.usedPercent)[0]?.resetsAt}function F2(Z,$){if(!Z)return!1;let J=[Z.primary,Z.secondary].filter((X)=>X!==void 0);if(J.length===0)return!1;return J.every((X)=>!b1(X,$))}async function C7(Z,$){let J;try{J=await $.resolveResetTarget(Z);let X=J.accountKey==="main"?void 0:J.chatgptAccountId,[z,G]=await Promise.all([E1({accessToken:J.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:J.chatgptAccountId}),a9($.fetchImpl,J.accessToken,X)]),B=R5(G.credits),Q=x6(G.credits),Y=G.availableCount??z.resetCreditsAvailable??(Q>0?Q:void 0),W=z.resetCreditsApplicable,H=s9(z,$.quotaManager.isRateLimited(Z),$.now()),V;if(!J.chatgptAccountId)V="stable ChatGPT account identity unavailable";else if(!H.ok)V=H.reason;else if(!B)V="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:P7(z),resetTime:q2(z,$.now()),availableCount:Y,applicableAvailableCount:W,eligible:V===void 0,reason:V,selectedCreditId:B?.id,selectedCreditExpiresAt:B?.expiresAt}}catch(X){if(X?.status===401)await J?.onAuthFailure?.(401);return XZ.warn("reset preview row failed",{accountKey:Z,error:X?.message??String(X)}),{accountKey:Z,label:Z==="main"?"Main account":Z,eligible:!1,reason:X?.message??String(X)}}}function K2(Z){let $=Z.usedPercent===void 0?"quota unavailable":`${Z.usedPercent}% used`,J=Z.availableCount===void 0?"credits unavailable":`${Z.applicableAvailableCount===void 0?"?":Z.applicableAvailableCount}/${Z.availableCount} applicable/available`,X=Z.eligible?`eligible · credit ${Z.selectedCreditId} expires ${Z.selectedCreditExpiresAt}`:Z.reason;return`${$}; ${J}; ${X}`}function T7(Z){let $=["## Confirm reset credit","",`Account: **${Z.label}** (\`${Z.accountKey}\`)`,`Current quota: **${Z.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Z.availableCount??"unknown"}**`,`Credit expires: **${Z.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Z.resetTime??"unavailable"}**`,""];if((Z.availableCount??0)>0&&Z.applicableAvailableCount===0)$.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."),$.push("");if(Z.eligible&&Z.chatgptAccountId)$.push('Eligible: choose "Spend a reset credit" to redeem one.');else $.push(`Cannot reset: **${Z.reason??"not eligible"}**`);return $.join(`
21
- `)}function JZ(Z,$,J,X={}){if(Object.keys(X).length>0)XZ.debug("reset step details",{accountKey:Z,code:$,...X});return{ok:$==="reset"||$==="already_redeemed",code:$,text:J}}function N2(Z,$,J){if($ instanceof ZZ){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 JZ(Z,$.kind,`## Reset credit
20
+ ${L7(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 D7(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 D7(Z,$,!0);return{ok:J,text:X}}}]}))})}}var F2=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],K2=["primary","secondary"];function pQ(Z){let $=new Set(Z.unavailableSections),J=(W)=>({title:W,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),X=[...Z.extras??[]];if($.has("reset")){let W={id:"reset",...J("Reset credits")},H=X.findIndex((V)=>V.id==="reset");if(H<0)X.unshift(W);else X[H]=W}let z={command:h1,title:M7,store:Q$(V$(W2(Z.store,{...Z.rowLocks?{rowLocks:Z.rowLocks}:{}}))),...Z.extraLocks?{extraLocks:Z.extraLocks}:{},accounts:{...Z.login?{login:q2(Z.login,Z.vault)}:{},...Z.protect?{protect:Z.protect}:{},...Z.describeIdentity?{describeIdentity:Z.describeIdentity}:{}},quota:Z.quotaCheck?{check:Z.quotaCheck}:{},routing:{orderedVariants:F2,formerMainId:xZ},limits:{labels:K2},...$.has("cache")?{cache:J("Cache")}:Z.cache?{cache:Z.cache}:{},...$.has("diagnostics")?{diagnostics:J("Diagnostics")}:Z.diagnostics?{diagnostics:Z.diagnostics}:{},extras:X,...Z.logger?{logger:Z.logger}:{},...Z.now?{now:Z.now}:{}},G=Z.vault?W$(z,Z.vault,{refresh:!Z.readOnly,...Z.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):pZ(z),B=Z.vault?W$(z,Z.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,Q=(W)=>{let{sessionId:H}=W,V=W.notify.bind(W);return{...H!==void 0?{sessionId:H}:{},notify:V}},Y=async(W)=>{if(Z.vault&&await Z.vault.authority()!=="local")return W;let H=await Z.store.read().catch(()=>{return});if(H?.status!=="ready")return W;return{...W,menu:q7(W.menu,new Map(H.rows.map((V)=>[V.id,V.quota])))}};return{command:h1,async open(W){let H=Q(W),V=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(V&&!V.migrated)return{command:h1,menu:N7(V.blockers)};let j=await G.open(H);return Y({...j,menu:H$(j.menu)})},async apply(W,H){let V=Q(H),j=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(j&&!j.migrated)return{command:h1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:N7(j.blockers)};if(Z.readOnly&&Z.vault)return G.apply(W,V);if(Z.readOnly||Z.allowAction&&!Z.allowAction(W)||$.has(W.sectionId)){if(B)return B.apply(W,V);return{...await G.open(V),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let F=await G.apply(W,V);if(F.ok)await Z.afterApply?.();return Y({...F,menu:H$(F.menu)})}}}function T7(Z){let $=[Z.primary?.usedPercent,Z.secondary?.usedPercent].filter((J)=>J!==void 0);return $.length>0?Math.max(...$):void 0}function N2(Z,$){let J=[Z.primary,Z.secondary].filter((z)=>z!==void 0),X=J.filter((z)=>b1(z,$));return(X.length>0?X:J).sort((z,G)=>G.usedPercent-z.usedPercent)[0]?.resetsAt}function D2(Z,$){if(!Z)return!1;let J=[Z.primary,Z.secondary].filter((X)=>X!==void 0);if(J.length===0)return!1;return J.every((X)=>!b1(X,$))}async function _7(Z,$){let J;try{J=await $.resolveResetTarget(Z);let X=J.accountKey==="main"?void 0:J.chatgptAccountId,[z,G]=await Promise.all([E1({accessToken:J.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:J.chatgptAccountId}),n9($.fetchImpl,J.accessToken,X)]),B=E5(G.credits),Q=w6(G.credits),Y=G.availableCount??z.resetCreditsAvailable??(Q>0?Q:void 0),W=z.resetCreditsApplicable,H=a9(z,$.quotaManager.isRateLimited(Z),$.now()),V;if(!J.chatgptAccountId)V="stable ChatGPT account identity unavailable";else if(!H.ok)V=H.reason;else if(!B)V="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:T7(z),resetTime:N2(z,$.now()),availableCount:Y,applicableAvailableCount:W,eligible:V===void 0,reason:V,selectedCreditId:B?.id,selectedCreditExpiresAt:B?.expiresAt}}catch(X){if(X?.status===401)await J?.onAuthFailure?.(401);return XZ.warn("reset preview row failed",{accountKey:Z,error:X?.message??String(X)}),{accountKey:Z,label:Z==="main"?"Main account":Z,eligible:!1,reason:X?.message??String(X)}}}function M2(Z){let $=Z.usedPercent===void 0?"quota unavailable":`${Z.usedPercent}% used`,J=Z.availableCount===void 0?"credits unavailable":`${Z.applicableAvailableCount===void 0?"?":Z.applicableAvailableCount}/${Z.availableCount} applicable/available`,X=Z.eligible?`eligible · credit ${Z.selectedCreditId} expires ${Z.selectedCreditExpiresAt}`:Z.reason;return`${$}; ${J}; ${X}`}function L7(Z){let $=["## Confirm reset credit","",`Account: **${Z.label}** (\`${Z.accountKey}\`)`,`Current quota: **${Z.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Z.availableCount??"unknown"}**`,`Credit expires: **${Z.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Z.resetTime??"unavailable"}**`,""];if((Z.availableCount??0)>0&&Z.applicableAvailableCount===0)$.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."),$.push("");if(Z.eligible&&Z.chatgptAccountId)$.push('Eligible: choose "Spend a reset credit" to redeem one.');else $.push(`Cannot reset: **${Z.reason??"not eligible"}**`);return $.join(`
21
+ `)}function JZ(Z,$,J,X={}){if(Object.keys(X).length>0)XZ.debug("reset step details",{accountKey:Z,code:$,...X});return{ok:$==="reset"||$==="already_redeemed",code:$,text:J}}function P2(Z,$,J){if($ instanceof ZZ){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 JZ(Z,$.kind,`## Reset credit
22
22
 
23
23
  ${z[$.kind]}
24
24
 
@@ -26,17 +26,17 @@ Code: \`${$.kind}\``,{cooldownUntil:$.cooldownUntil,...$.kind==="expired_unrecon
26
26
 
27
27
  ${{unknown_account:"Account unavailable: the selected account no longer exists. Reopen the reset account list.",disabled_account:"Account unavailable: the selected account is disabled. Reopen the reset account list.",non_oauth_account:"Account unavailable: the selected account is not authenticated with OAuth. Reopen the reset account list.",token_unavailable:"Authentication problem: the selected account token is unavailable. Reauthenticate the account before retrying."}[X]}
28
28
 
29
- Code: \`${X}\``);if($ instanceof lZ)return JZ(Z,$.kind,`## Reset credit
29
+ Code: \`${X}\``);if($ instanceof dZ)return JZ(Z,$.kind,`## Reset credit
30
30
 
31
31
  No redemption was attempted: reset credit availability could not be loaded.
32
32
 
33
33
  Code: \`${$.kind}\``);return XZ.warn("reset command failed before a known result",{accountKey:Z,error:$?.message??String($)}),JZ(Z,"error",`## Reset credit
34
34
 
35
- The reset request failed before a known result: internal command failure — see plugin log.`)}async function L7(Z,$,J){let{accountKey:X}=Z.target,z=Z.outcome.kind;if(Z.finalizeStateWriteFailed)return JZ(X,z,`## Reset credit result
35
+ The reset request failed before a known result: internal command failure — see plugin log.`)}async function O7(Z,$,J){let{accountKey:X}=Z.target,z=Z.outcome.kind;if(Z.finalizeStateWriteFailed)return JZ(X,z,`## Reset credit result
36
36
 
37
37
  Account: **${Z.target.label}** (\`${X}\`)
38
38
 
39
- The server outcome recorded as \`${z}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:Z.retrySafety,chatgptAccountId:J});if(z==="reset"||z==="already_redeemed"){let B={account:X,ok:!1,error:"targeted quota refresh did not complete"};try{B=await $.refreshResetTargetQuota(X)}catch(F){B.error=F?.message??String(F)}let Q=!B.ok&&B.error!==void 0;if(Q)XZ.warn("reset quota re-check failed",{accountKey:X,error:B.error});let Y=X==="main"?$.quotaManager.getMain():$.quotaManager.getFallback(X),W=B.ok&&F2(Y?.quota,$.now()),H=Y?.quota.resetCreditsApplicable,V=W?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${z}\`).`,j=Q?`
39
+ The server outcome recorded as \`${z}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:Z.retrySafety,chatgptAccountId:J});if(z==="reset"||z==="already_redeemed"){let B={account:X,ok:!1,error:"targeted quota refresh did not complete"};try{B=await $.refreshResetTargetQuota(X)}catch(F){B.error=F?.message??String(F)}let Q=!B.ok&&B.error!==void 0;if(Q)XZ.warn("reset quota re-check failed",{accountKey:X,error:B.error});let Y=X==="main"?$.quotaManager.getMain():$.quotaManager.getFallback(X),W=B.ok&&D2(Y?.quota,$.now()),H=Y?.quota.resetCreditsApplicable,V=W?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${z}\`).`,j=Q?`
40
40
 
41
41
  quota re-check failed — see log.`:"";return JZ(X,z,`## Reset credit result
42
42
 
@@ -46,7 +46,7 @@ Code: \`${z}\`
46
46
 
47
47
  ${V}${j}${H===void 0?"":`
48
48
 
49
- Remaining applicable credits: **${H}**`}`,{verifiedFresh:W,afterUsedPercent:P7(Y?.quota??{}),remainingCredits:H})}if(z==="ambiguous_local")return JZ(X,z,`## Reset credit result
49
+ Remaining applicable credits: **${H}**`}`,{verifiedFresh:W,afterUsedPercent:T7(Y?.quota??{}),remainingCredits:H})}if(z==="ambiguous_local")return JZ(X,z,`## Reset credit result
50
50
 
51
51
  Account: **${Z.target.label}** (\`${X}\`)
52
52
 
@@ -64,11 +64,11 @@ Account: **${Z.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."}`)}var V$=s("quota"),_7="the account holds a tombstone from the removed vault custody, not a credential";function M2(Z){return Z?.status===401}async function sQ(Z,$={}){let J=Z.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let X=[],z=Z.logger??V$,G=(U)=>{X.push(U);let q={pid:process.pid,accountId:U.account,status:U.ok?"ok":"error",...U.error?{error:U.error}:{}};if(U.ok)z.debug("quota refresh succeeded",q);else z.warn("quota refresh failed",q)},B=Z.skipFresherThanMs,Q=!1,Y;if(B!==void 0)try{Y=await Z.readSidebarState()}catch{}let W=new Map(Y?.fallbacks.map((U)=>[U.id,U])??[]),H=(...U)=>B!==void 0&&U.some((q)=>typeof q==="number"&&Number.isFinite(q)&&q<=Z.now()&&Z.now()-q<B),V=await Z.loadAccounts(Z.paths).catch(()=>{return}),j=V?.mainAccountId??Z.storageMainAccountId,F;if(!$.accountKey||$.accountKey==="main")try{let U=await Z.getAuth();if(I7(U)){if(F=R7(V),!F)G({account:"main",ok:!1,error:x1(U)?_7:"main account row is missing from the account pool"})}else if(U.type==="oauth"){let q=Y&&j!==void 0&&Y.main.mainAccountId===j?Y.main.quota:void 0;if(H(Z.quotaManager.peekMainForPolicy(j)?.checkedAt,q?.primary?.checkedAt,q?.secondary?.checkedAt,q?.checkedAt))G({account:"main",ok:!0});else{if(!U.access||(U.expires??0)<Z.now()){let N=await Z.refreshMainWithLease();U={...U,access:N.access,expires:N.expires}}if(U.access)if(Z.respectBackoff&&Z.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let N=await J({accessToken:U.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:j,accountKey:"main"});Z.quotaManager.setMain(U.access,{quota:N,refreshAfter:Z.now()+300000,checkedAt:Z.now()},j,!0),Q=!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:TZ(U)})}if(V)for(let U of V.accounts){let q=F!==void 0&&U===F;if(!q&&$.accountKey&&($.accountKey==="main"||U.id!==$.accountKey))continue;if(!q&&Z.isOAuthAccountFn(U)&&S7(V,U)){if($.accountKey)G({account:U.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let K=q?U.accountId??j:void 0,N=(D,O,L)=>{if(q)Z.quotaManager.setMain(O,D,K,!0);else Z.quotaManager.setFallback(U.id,D,O,!0,L)};if(U.enabled===!1||!Z.isOAuthAccountFn(U)){if($.accountKey)G({account:U.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let D=W.get(U.id),O=U.accountId,L=q?Y&&K!==void 0&&Y.main.mainAccountId===K?Y.main.quota:void 0:D&&O!==void 0&&D.accountId===O?D.quota:void 0;if(H(q?Z.quotaManager.peekMainForPolicy(K)?.checkedAt:Z.quotaManager.peekFallbackForPolicy(U.id,O)?.checkedAt,L?.primary?.checkedAt,L?.secondary?.checkedAt,L?.checkedAt)){G({account:U.id,ok:!0});continue}if(Z.respectBackoff&&(q?Z.quotaManager.isBackedOff():Z.quotaManager.isFallbackBackedOff(U.id,U.access))){G({account:U.id,ok:!0});continue}let M=U.lastRefreshError;if(O7(M,U.refresh,Z.now())){G({account:U.id,ok:!1,error:A7(M,Z.now()),permanent:!0});continue}if(x1(U)){G({account:U.id,ok:!1,error:_7});continue}let T;try{T=q?await Z.fallbackManager.refreshAccount(U,V,{asPoolMain:!0}):await Z.fallbackManager.refreshAccount(U,V)}catch(_){V$.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:U.id,error:TZ(_)}),T=U}if(!T.access||(T.expires??0)<Z.now()){G({account:U.id,ok:!1,error:"no usable access token"});continue}let A;try{A=await J({accessToken:T.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:T.accountId,accountKey:U.id})}catch(_){if(!M2(_))throw _;if(V$.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:U.id}),T=await Z.fallbackManager.refreshAccount(U,V,q?{force:!0,asPoolMain:!0}:{force:!0}),!T.access){G({account:U.id,ok:!1,error:"no usable access token after forced refresh"});continue}A=await J({accessToken:T.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:T.accountId,accountKey:U.id})}N({quota:A,refreshAfter:Z.now()+300000,checkedAt:Z.now()},T.access,T.accountId),Q=!0,G({account:U.id,ok:!0})}catch(D){G({account:U.id,ok:!1,error:TZ(D)})}}if($.accountKey&&$.accountKey!=="main"&&!X.some((U)=>U.account===$.accountKey))X.push({account:$.accountKey,ok:!1,error:"account not found"});if(B===void 0||Q){let U=await Z.loadAccounts(Z.paths);await Z.writeSidebarState(Z.quotaManager,U)}return X}import{types as D2}from"node:util";var P2=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,C2=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function v7(Z){return Z.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,($,J,X)=>{if(J)return String.fromCharCode(Number.parseInt(J,16));return{b:"\b",f:"\f",n:`
68
- `,r:"\r",t:"\t"}[X]??X??$})}function T2(Z,$){if(!$)return Z;let J=Z.split($).join("[credential]"),X=$.replace(/\s/g,"");if(!X)return J;let z=J.replace(/\s/g,"");if(!z.includes(X))return J;let G=[];for(let Y=0;Y<J.length;Y++){let W=J[Y]??"";if(!/\s/.test(W))G.push(Y)}let B=[],Q=0;for(let Y=z.indexOf(X);Y>=0;Y=z.indexOf(X,Y+X.length)){let W=G[Y]??Q,H=(G[Y+X.length-1]??W)+1;B.push(J.slice(Q,W),"[credential]"),Q=H}return B.length?B.join("")+J.slice(Q):J}function E7(Z,$){let J=T2(Z,$);return k7(J).replaceAll("***REDACTED***","[credential]")}function Q1(Z,$){let J=E7(Z,$),X=v7(J),z=E7(X,$);return z===X?J:z}function b7(Z){let $=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(Z);if(!$)return;let J=$[3]??"",X=($[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=$[4]??"0",Q=B.startsWith("-")||B.startsWith("+")?1:0;while(B[Q]==="0")Q++;let Y=B.slice(Q)||"0";if(Y.length>16)return;let W=BigInt((B.startsWith("-")?"-":"")+Y)-BigInt(J.length)+BigInt(X.length-G);return`${$[1]}${X.slice(z,G)}e${W}`}function g7(Z,$){let J=$?b7($):void 0;return Z.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(X)=>{if(!X.startsWith('"'))return $&&(X===$||J!==void 0&&b7(X)===J||($==="Infinity"||$==="-Infinity")&&/^[-\d]/.test(X)&&String(Number(X))===$)?'"[credential]"':X;let z=v7(X.slice(1,-1)),G=Q1(z,$);return G===z?X:JSON.stringify(G)})}function j$(Z,$){let J=g7(Z,$);try{return JSON.parse(Z),J}catch{return Q1(J,$)}}var L2=16384,_2=65536,O2=[/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 A2(Z){try{let $=m(JSON.parse(Z),"request_id");if(typeof $==="string")return $;if(typeof $!=="number")return;let J=0,X,z=!0,G=!1,B;for(let Q of Z.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Y=Q[0];if(Y==="{"||Y==="["){J++;continue}if(Y==="}"||Y==="]"){J--;continue}if(J!==1)continue;if(Y===","){z=!0,G=!1,X=void 0;continue}if(Y===":"){G=!0;continue}if(z&&Y.startsWith('"')){X=JSON.parse(Y),z=!1;continue}if(G&&X==="request_id"&&!Y.startsWith('"'))B=Y;G=!1}return B}catch{return}}function S2(Z,$){let J=j$(Z,$);if(Buffer.byteLength(J,"utf8")<=_2)return J;let X=O2.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(m(G,"type")==="error")z.type="error";let B=m(G,"error"),Q={};for(let W of["code","type"]){let H=m(B,W);if(typeof H==="string")Q[W]=H.slice(0,256)}if(Object.keys(Q).length)z.error=Q;let Y={};for(let W of["workspace","limitName"]){let H=m(m(G,"metadata"),W);if(typeof H==="string")Y[W]=H.slice(0,256)}if(Object.keys(Y).length)z.metadata=Y}catch{}return JSON.stringify(z)}function v5(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;for(let J=0;$&&J<16;J++){if(D2.isProxy($))return!1;$=Object.getPrototypeOf($)}return $===null}function m(Z,$){if(!v5(Z))return;let J=Object.getOwnPropertyDescriptor(Z,$);return J&&"value"in J?J.value:void 0}function m1(Z,$){return Q1(Z,$).slice(0,L2)}function W1(Z,$){let J=Object.getOwnPropertyDescriptor(Z,$)?.get;if(!J)throw Error(`Missing native ${$} accessor`);return J}var I2=W1(DOMException.prototype,"message"),R2=W1(DOMException.prototype,"name");function U$(Z,$){let J=m(Z,"message"),X=m(Z,"name");if(v5(Z)&&Z instanceof DOMException)try{J=I2.call(Z),X=R2.call(Z)}catch{}let z=Error(m1(typeof J==="string"?J:typeof Z==="string"?Z:"Provider request failed",$));for(let V of Object.getOwnPropertyNames(z))if(V!=="message")Reflect.deleteProperty(z,V);Object.defineProperty(z,"name",{value:typeof X==="string"?m1(X,$):"Error",configurable:!0,writable:!0});let G=(V,j,F)=>{let U=m(V,F);if(typeof U==="string"||typeof U==="number"&&Number.isFinite(U)||typeof U==="boolean")Object.defineProperty(j,F,{value:typeof U==="string"?m1(U,$):U,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=m(Z,V);if(typeof j==="number"&&Number.isFinite(j))G(Z,z,V)}for(let V of["code","type","isRetryable"])G(Z,z,V);for(let V of["error","data"]){let j=m(Z,V),F=Object.create(null);for(let q of["type","code","message","resets_at","resets_in_seconds"])G(j,F,q);let U=m(j,"error");if(v5(U)){let q=Object.create(null);for(let K of["type","code","message","resets_at","resets_in_seconds"])G(U,q,K);F.error=q}if(Object.keys(F).length)Object.defineProperty(z,V,{value:F,enumerable:!0})}let B=m(Z,"responseHeaders");if(B&&typeof B==="object"){let V={};for(let j of["retry-after-ms","retry-after"]){let F=m(B,j);if(typeof F==="string")V[j]=m1(F,$)}Object.defineProperty(z,"responseHeaders",{value:V,enumerable:!0})}let Q=m(Z,"responseBody");if(typeof Q==="string")Object.defineProperty(z,"responseBody",{value:S2(Q,$),enumerable:!0});let Y=m(Z,"request_id"),W=m(B,"x-request-id"),H=typeof Y==="string"?Y:typeof W==="string"?W:typeof Q==="string"?A2(j$(Q,$)):void 0;if(typeof H==="string")Object.defineProperty(z,"request_id",{value:m1(H,$),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(V);if(m(Z,j)===!0)Object.defineProperty(z,j,{value:!0})}return z}function E2(Z,$){if(!Z.includes("error")&&(!Z.includes("\\u00")||!P2.test(Z)&&!C2.test(Z)))return Z;let J;try{J=JSON.parse(Z)}catch{return Z}if(J?.type==="error"||J?.error||J?.response?.error)return g7(Z,$);return Z}var b2=W1(Response.prototype,"status"),y2=W1(Response.prototype,"statusText"),k2=W1(Response.prototype,"headers"),v2=W1(Response.prototype,"body"),g2=Response.prototype.text,y7=Headers.prototype.entries;async function rQ(Z,$,J="http"){try{let F=function(U){let q=j&&U.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,q+U.slice(q.length).replace(/^data: ?([^\r\n]*)/gm,(K,N)=>K.slice(0,K.length-N.length)+E2(N,$))};if(!v5(Z))throw Error("Invalid provider response");let X=b2.call(Z),z=k2.call(Z),G=v2.call(Z),B=new Headers;for(let[U,q]of y7.call(z))B.append(U,q);let Q={status:X,statusText:Q1(y2.call(Z),$),headers:B};if(X<200||X>299){for(let[q,K]of y7.call(z)){if(Q1(q,$?.toLowerCase())!==q){Q.headers.delete(q);continue}try{Q.headers.set(q,Q1(K,$))}catch{Q.headers.delete(q)}}Q.headers.delete("content-length");let U=await g2.call(Z);return new Response(j$(U,$),Q)}if(!G||J==="http")return Z;Q.headers.delete("content-length");let Y=ReadableStream.prototype.getReader.call(G),W=new TextDecoder("utf-8",{ignoreBOM:!0}),H=new TextEncoder,V="",j=!0;return new Response(new ReadableStream({async pull(U){try{for(;;){let q=await Y.read();V+=W.decode(q.value,{stream:!q.done});let K=!1;for(;;){let N=/\r?\n\r?\n/.exec(V);if(!N)break;let D=N.index+N[0].length;U.enqueue(H.encode(F(V.slice(0,D)))),V=V.slice(D),K=!0}if(q.done){if(V)U.enqueue(H.encode(F(V)));U.close();return}if(K)return}}catch(q){U.error(U$(q,$))}},async cancel(U){try{await Y.cancel(U)}catch(q){throw U$(q,$)}finally{Y.releaseLock()}}}),Q)}catch(X){throw U$(X,$)}}function eQ(Z,$,J){let X=Z.get($.sessionId),z=new Set($.validPinnedAccountIds);if(X&&!$.excludeAccountIds.includes(X.accountId)&&f7(X,z,$.wireAccountIdByAccount[X.accountId])){if($.persist){let Y=$.quotaCheckedAtByAccount[X.accountId];J($.sessionId,{accountId:X.accountId,inputBytes:$.requestBytes,...X.wireIdentity!==void 0?{wireIdentity:X.wireIdentity}:{},...Y!==void 0?{quotaCheckedAt:Y}:{}})}return{accountId:X.accountId}}let G=new Map(Object.entries($.quotaCheckedAtByAccount)),B=h7(Z,G,$.sessionId),Q=$.select(B);if(!Q)return;if($.persist){let Y=$.wireAccountIdByAccount[Q.accountId];J($.sessionId,{accountId:Q.accountId,inputBytes:$.requestBytes,...Y!==void 0?{wireIdentity:Y}:{},...Q.quotaCheckedAt!==void 0?{quotaCheckedAt:Q.quotaCheckedAt}:{}})}return{accountId:Q.accountId}}import{statSync as f2}from"node:fs";var u7=30000,h2=8,x2=1800000;function p7(Z){return Z.identity?`identity:${Z.identity}`:`row:${Z.id}`}function zW(Z){try{let $=f2(Z);return`${$.ino}:${$.size}:${$.mtimeMs}`}catch{return"-"}}function GW(Z){let $=Z.credential;if($?.type!=="oauth")return;return{access:$.access??"",expires:$.expires,refresh:$.refresh}}function m2(Z,$){try{return x7(Z,$)}catch{return Z}}function BW(Z,$,J){let X=p7($);Z.set(X,[...Z.get(X)??[],{credentialEpoch:$.credentialEpoch,identity:$.identity,observation:J}].slice(-h2))}function QW(Z,$,J){let X=Z;for(let z of $.get(p7(Z))??[]){if(!(J-z.observation.checkedAt<=x2)||z.credentialEpoch!==Z.credentialEpoch||z.identity!==Z.identity)continue;X={...X,quota:m2(X.quota,z.observation)}}return X}function WW(Z,$,J,X){let z=w1(Z);if(typeof $?.status==="number"||m7($)){let B=w7({error:$,now:J,refreshToken:Z,...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+u7,tokenHash:z,retryCount:X?.tokenHash===z?X.retryCount:0}}function YW(Z,$,J,X){let z=new Map;for(let G of Z){if(X(G,J))continue;let B=$.get(G.id);z.set(G.id,B&&B.nextRetryAt>J?B.nextRetryAt:J+u7)}return z}import{readdir as u2,readFile as p2}from"node:fs/promises";import{homedir as l2}from"node:os";import{join as H1}from"node:path";var F$=Symbol.for("@cortexkit/openai-auth/runtime-layout-runs"),K$=globalThis,q$=globalThis,w2=K$[F$];K$[F$]??={};var Y1=K$[F$];Y1.legacyGeneration??=w2===void 0&&q$[Symbol.for("@cortexkit/openai-auth/runtime-layouts")]===void 0&&(q$[Symbol.for("@cortexkit/openai-auth/opencode-vaults")]!==void 0||q$[Symbol.for("__openaiAuthRpcServers")]!==void 0||("__openaiAuthRpcServers"in globalThis));Y1.runs??=new Map;Y1.logged??=new Set;var EZ=Object.assign(Y1,{runs:Y1.runs,logged:Y1.logged});function o(){return EZ.legacyGeneration===!0}function g5(){return process.env.XDG_STATE_HOME||H1(l2(),".local","state")}function d2(Z=g5()){return H1(Z,"cortexkit","openai-auth","processes")}function c2(Z=g5()){return H1(Z,"cortexkit","openai-auth","rpc")}function s2(Z){try{return process.kill(Z,0),!0}catch($){return $.code==="EPERM"}}function l7(Z){let $=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(Z.trim());if(!$)return;return{core:[Number($[1]),Number($[2]),Number($[3])],pre:$[4]?$[4].split("."):[]}}function d7(Z,$){let J=l7(Z),X=l7($);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 Q=/^\d+$/.test(G),Y=/^\d+$/.test(B);if(Q&&Y){let W=Number(G)-Number(B);if(W!==0)return Math.sign(W)}else if(Q!==Y)return Q?-1:1;else if(G!==B)return G<B?-1:1}return 0}async function N$(Z){try{return{ok:!0,names:await u2(Z)}}catch($){let J=$.code;if(J==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:J,error:`${Z}: ${String($)}`}}}async function c7(Z,$){let J;try{J=await p2(Z,"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===$&&typeof X.version==="string"){let z=X.layouts;return{kind:"ok",version:X.version,...z!==null&&typeof z==="object"&&!Array.isArray(z)?{layouts:z}:{}}}}catch{}return{kind:"unreadable"}}async function a7(Z){let $=Z.isAlive??s2,J=Z.selfPid??process.pid,X=new Map,z=(j)=>{let F=j.pid==="unknown"?`dir:${j.detail}`:j.pid;if(!X.has(F))X.set(F,j)};if(Z.layoutMove&&J===process.pid&&o())z({pid:J,version:"unknown",detail:"an older plugin generation ran in this process"});let G=(j)=>{try{return $(j)}catch{return!0}},B=(j,F)=>{let U=F.exec(j),q=U?Number(U[1]):Number.NaN;return Number.isSafeInteger(q)&&q>=1?q:void 0},Q=d2(Z.stateHome),Y=await N$(Q);if(!Y.ok)z({pid:"unknown",version:"unknown",detail:Y.error});for(let j of Y.ok?Y.names:[]){let F=B(j,/^(\d+)\.json$/);if(F===void 0||F===J)continue;let U=H1(Q,j),q=await c7(U,F);if(q.kind==="gone")continue;if(!G(F))continue;if(q.kind==="unreadable"){z({pid:F,version:"unknown",detail:U});continue}let K=d7(q.version,Z.currentVersion);if(K===void 0||K<0){z({pid:F,version:q.version,detail:U});continue}if(Z.layoutMove===!0&&(q.layouts===void 0||Object.values(q.layouts).includes("legacy")))z({pid:F,version:q.version,detail:U})}let W=Z.rpcDir??c2(Z.stateHome),H=await N$(W);if(!H.ok)z({pid:"unknown",version:"unknown",detail:H.error});for(let j of H.ok?H.names:[]){if(!s7(j))continue;let F=H1(W,j),U=await N$(F);if(!U.ok){if(U.code==="ENOTDIR")continue;z({pid:"unknown",version:"unknown",detail:U.error});continue}for(let q of U.names){let K=B(q,/^port-(\d+)\.json$/);if(K===void 0||K===J||!G(K))continue;let N=H1(F,q),D=await c7(N,K);if(D.kind==="gone")continue;let O=D.kind==="ok"?D.version:"unknown",L=d7(O,Z.currentVersion);if(L===void 0||L<0)z({pid:K,version:O,detail:N})}}let V=(j)=>j.pid==="unknown"?Number.POSITIVE_INFINITY:j.pid;return X.size===0?{open:!0}:{open:!1,blockers:[...X.values()].sort((j,F)=>V(j)-V(F))}}import{createHash as a2}from"node:crypto";import{existsSync as n2,realpathSync as M$}from"node:fs";import{homedir as o7}from"node:os";import{basename as i2,dirname as r2,join as zZ,resolve as C$}from"node:path";var T$="openai-auth-sessions.json",L$="openai-auth-sessions-opencode2.json",f5="layout.json",_$="config-dir.json";function h5(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return o2()}function o2(){return zZ(process.env.XDG_CONFIG_HOME||zZ(o7(),".config"),"opencode")}function x5(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||zZ(h5(),D$)}function V1(Z,$){let J=C$(Z);return $==="win32"||$==="darwin"?J.toLowerCase():J}function n7(Z){try{return M$.native(Z)}catch{try{return zZ(M$.native(r2(Z)),i2(Z))}catch{return}}}function m5(Z,$,J=process.platform){if(V1(Z,J)===V1($,J))return!0;let X=n7(Z),z=n7($);return X!==void 0&&z!==void 0&&V1(X,J)===V1(z,J)}function i7(Z){try{return M$.native(Z)}catch{return C$(Z)}}var r7=new Map;function w5(Z=h5()){let $=g5(),J=zZ(o7(),".config","opencode"),X=`${Z}\x00${J}\x00${$}`,z=r7.get(X);if(z&&p5(z))return z;let G=i7(Z);if(z&&z.key===G)return z;let B=G===i7(J),Q=zZ($,"cortexkit","openai-auth"),Y={key:G,configDir:Z,stateHomeDir:B?zZ(Q,"opencode"):zZ(Q,`opencode-${a2("sha256").update(G).digest("hex").slice(0,16)}`),isDefaultConfigDir:B};return r7.set(X,Y),Y}var t7=Symbol.for("@cortexkit/openai-auth/runtime-layouts"),e7=globalThis,O$=e7[t7]??new Map;e7[t7]=O$;function Z0(Z){return`${Z.stateHomeDir}\x00${Z.key}`}function u5(Z,$){O$.set(Z0(Z),o()?"legacy":$)}function p5(Z){return O$.get(Z0(Z))}function $0(Z=h5()){if(o())return Z;let $=w5(Z);return(p5($)??(n2(zZ($.stateHomeDir,f5))?"state-home":"legacy"))==="state-home"?$.stateHomeDir:Z}function iW(Z){return zZ($0(),Z==="opencode1"?T$:L$)}function A$(Z){let $=zZ(h5(),D$);return Z===$||V1(Z,process.platform)===V1($,process.platform)}function J0(Z=x5()){let $=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if($)return $;return A$(Z)?void 0:P$(Z)}function X0(Z=x5()){return A$(Z)?void 0:Z}function t2(Z=x5()){let $=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if($){if(m5(Z,$))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${C$(Z)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return $}if(!A$(Z))return P$(Z);return zZ($0(),u1)}function rW(Z=x5()){return{configPath:Z,statePath:t2(Z)}}import{createHash as BJ}from"node:crypto";import{readFileSync as QJ}from"node:fs";import{readFile as WJ}from"node:fs/promises";import{resolve as YJ}from"node:path";import{createHash as e2}from"node:crypto";import{readFile as ZJ}from"node:fs/promises";import{homedir as $J}from"node:os";import{join as z0,resolve as JJ}from"node:path";var XJ="openai",G0=250,l1="main-refresh";function I$(Z){if(typeof Z.access!=="string"||typeof Z.refresh!=="string")return;let $=Buffer.from(Z.access),J=Buffer.from(Z.refresh),X=(z)=>{let G=Buffer.alloc(4);return G.writeUInt32BE(z.length),G};return e2("sha256").update(X($)).update($).update(X(J)).update(J).digest("hex")}function V0(Z){if(!Z||typeof Z!=="object")return;let $=Z;if($.type!=="oauth")return;return{type:"oauth",...typeof $.access==="string"?{access:$.access}:{},...typeof $.refresh==="string"?{refresh:$.refresh}:{},...typeof $.expires==="number"?{expires:$.expires}:{},...typeof $.accountId==="string"?{accountId:$.accountId}:{}}}function U0(Z){let $=V0(Z);if(typeof $?.access!=="string"||typeof $.refresh!=="string")return;return{access:$.access,refresh:$.refresh,...typeof $.expires==="number"?{expires:$.expires}:{}}}function B0(Z){if(aZ(Z)&&Z.type==="api"&&typeof Z.key==="string")return{kind:"api"};let $=V0(Z);if(!$)return{kind:"indeterminate"};return x1($)?{kind:"tombstone",oauth:$}:{kind:"real",oauth:$}}async function Q0(Z){return Z.auth.get({path:{id:XJ}})}async function W0(Z){return Object.keys(await Z.auth.all()).length>0}async function j0(Z){let $=await Q0(Z.client);if($!==void 0)return B0($);let J=await W0(Z.client),X=Z.now();if(await Z.sleep(G0),Z.now()-X<G0)return{kind:"indeterminate"};let z=await Q0(Z.client);if(z!==void 0)return B0(z);let G=await W0(Z.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function l5(Z=process.env,$=$J()){let J=Z.XDG_DATA_HOME||z0($,".local","share");return z0(J,"opencode","auth.json")}function aZ(Z){return!!Z&&typeof Z==="object"&&!Array.isArray(Z)}var Y0=(Z)=>Z===void 0||typeof Z==="string";function zJ(Z){if(!aZ(Z))return!1;switch(Z.type){case"oauth":return typeof Z.refresh==="string"&&typeof Z.access==="string"&&typeof Z.expires==="number"&&Number.isSafeInteger(Z.expires)&&Z.expires>=0&&Y0(Z.accountId)&&Y0(Z.enterpriseUrl);case"api":return typeof Z.key==="string"&&(Z.metadata===void 0||aZ(Z.metadata)&&Object.values(Z.metadata).every(($)=>typeof $==="string"));case"wellknown":return typeof Z.key==="string"&&typeof Z.token==="string";default:return!1}}async function S$(Z,$=process.env){let J=$.OPENCODE_AUTH_CONTENT;if(J)try{let z=JSON.parse(J);return aZ(z)?z:{}}catch{}let X;try{X=JSON.parse(await ZJ(Z,"utf8"))}catch{return{}}if(!aZ(X))return{};return Object.fromEntries(Object.entries(X).filter(([,z])=>zJ(z)))}function H0(Z){if(!Z.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(Z.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class d5 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function GJ(Z){let $=Z.env??process.env,J=Z.path??l5($),X=new Map;return{path:JJ(J),migrationDisabledReason:()=>H0($)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(z){let G=(await S$(J,$))[z.path.id];return X.set(z.path.id,JSON.stringify(G)),G},async all(){return S$(J,$)},async set(z){if(H0($))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let G=(await S$(J,$))[z.path.id];if(p1(z.body)&&(!X.has(z.path.id)||X.get(z.path.id)!==JSON.stringify(G)))throw new d5;let B=await Z.set(z);if(aZ(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 zY(Z,$={}){let J=aZ(Z)?Z.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:GJ({...$,set:(z)=>X.call(J,z)})}}var U1="openai",HJ="common-auth-placeholder:v1:openai",d1=Object.freeze({type:"oauth",access:"",refresh:HJ,expires:0});function p1(Z){if(!GZ(Z))return!1;return Z.type===d1.type&&Z.access===d1.access&&Z.refresh===d1.refresh&&Z.expires===d1.expires}var c5="openaiAuthPool",VJ=120000,T0="pool-migration",UJ="slot-transfer-origin-unknown",jJ="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.",r5=Object.freeze({mainRefreshTtlMs:VJ,fallbackTtlMs:P0,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function s5(Z,$,J){return Z.kind==="placeholder"&&!$&&!J.pending}class nZ extends Error{constructor(Z){super(`timed out waiting for the legacy ${Z} lock`);this.name="LegacyLockContention"}}function GZ(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function qJ(Z){let $=Z.now??Date.now;return{paths:Z.paths,slot:Z.slot,now:$,sleep:Z.sleep??((J)=>new Promise((X)=>setTimeout(X,J))),newId:Z.newId??(()=>crypto.randomUUID()),log:Z.log??s("pool-migration"),...Z.vaultServes?{vaultServes:Z.vaultServes}:{},locks:{...r5,...Z.legacyLocks},leaseWait:Z.leaseWait??{timeoutMs:4000,pollMs:50},store:S1({provider:U1,configPath:Z.paths.configPath,statePath:Z.paths.statePath,quota:n5,now:$,...Z.store}),onStep:async(J)=>{await Z.onStep?.(J)}}}async function q1(Z){let $;try{$=await WJ(Z,"utf8")}catch(X){if(X.code==="ENOENT")return{};throw X}let J=JSON.parse($);if(!GZ(J))throw Error("config root is not an object");return J}async function c1(Z,$,J,X,z){let G=performance.now();for(;;){if(z?.aborted)throw new nZ($);let B=await QZ({name:$,path:J,ttlMs:X,renew:Z.locks.renew,...Z.locks.renewIntervalMs!==void 0?{renewIntervalMs:Z.locks.renewIntervalMs}:{}});if(B){if(!z?.aborted)return B;throw await B.release(),new nZ($)}if(performance.now()-G>=Z.locks.timeoutMs)throw new nZ($);await Z.sleep(Z.locks.retryMs)}}async function KY(Z,$,J={}){let X={...r5,...J},z=performance.now();for(;;){let G=await QZ({name:l1,path:Z,ttlMs:X.mainRefreshTtlMs,renew:X.renew,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}});if(G)try{return await $()}finally{await G.release().catch(()=>{})}if(performance.now()-z>=X.timeoutMs)throw new nZ(l1);await new Promise((B)=>setTimeout(B,X.retryMs))}}async function s1(Z,$){let J=Z.locks.saveTtlMs,X=await c1(Z,"save",Z.paths.configPath,J);try{let z=await c1(Z,"save",Z.paths.statePath,J);try{let G=await q1(Z.paths.configPath);if(!await $(G))return;await AZ(Z.paths.configPath,G,{beforeRename:async()=>{await X.assertOwned(),await z.assertOwned()}})}finally{await z.release().catch(()=>{})}}finally{await X.release().catch(()=>{})}}function FJ(Z){if(!GZ(Z))return;let{rowId:$,operation:J,rowFingerprint:X,slotFingerprint:z}=Z,{credentialFingerprint:G,carryLegacyMain:B,recordedAt:Q,identity:Y}=Z;if(typeof $!=="string"||!$)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:$,operation:J,rowFingerprint:X,slotFingerprint:z,credentialFingerprint:G,...typeof Y==="string"&&Y?{identity:Y}:{},carryLegacyMain:B===!0,recordedAt:typeof Q==="number"?Q:0}}function L0(Z,$){if(!GZ(Z)||!$)return!1;return qZ(Z).pending?.credentialFingerprint===YZ({type:"oauth",refresh:$})}function NY(Z,$){let J;try{J=JSON.parse(QJ(Z,"utf8"))}catch{return!1}return L0(J,$)}class KJ extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var NJ=600000;async function MY(Z,$,J={}){let X=J.now??Date.now,z=(Y)=>{let W=qZ(Y).pending;return W&&L0(Y,$)&&X()-W.recordedAt>=NJ?W:void 0},G=z(await q1(Z.configPath));if(!G)return!1;let B={...r5,...J.legacyLocks},Q=await QZ({name:T0,path:Z.configPath,ttlMs:B.mainRefreshTtlMs});if(!Q)return!1;try{let Y=await q1(Z.configPath),W=qZ(Y).migratedAt!==void 0,H=await S1({provider:U1,configPath:Z.configPath,statePath:Z.statePath,quota:n5,now:X}).read();if(W&&H.status!=="ready")return!1;let V;if(H.status==="ready"){let F=H.rows.find((q)=>q.id===G.rowId&&!q.invalid),U=F?.fingerprint??null;if(W&&F&&U===G.credentialFingerprint)return!1;if(F&&U!==G.credentialFingerprint&&U!==G.rowFingerprint)V=J.slotAccess!==void 0?I$({type:"oauth",access:J.slotAccess,refresh:$}):G.slotFingerprint}let j=!1;if(await s1({paths:Z,locks:B,sleep:(F)=>new Promise((U)=>setTimeout(U,F))},(F)=>{let U=qZ(F),q=z(F);if(!q||q.recordedAt!==G.recordedAt)return!1;let{pending:K,...N}=U;return o5(F,V!==void 0?{...N,declinedSlotFingerprint:V}:N),j=!0,!0}),j)(J.log??s("pool-migration")).warn(V!==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 j}finally{await Q.release().catch(()=>{})}}function qZ(Z){let $=Z[c5];if(!GZ($))return{};let J=FJ($.pending);return{...typeof $.migratedAt==="number"?{migratedAt:$.migratedAt}:{},...J?{pending:J}:{},...typeof $.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:$.declinedSlotFingerprint}:{}}}function o5(Z,$){let X={...GZ(Z[c5])?Z[c5]:{}};for(let z of["migratedAt","pending","declinedSlotFingerprint"])delete X[z];Object.assign(X,$),Z[c5]=X}function MJ(Z){let $=Z?C5(Z):void 0;return $?T5($):void 0}function DJ(Z){let $=I$({type:"oauth",...Z}),J=MJ(Z.access);return{kind:"real",credential:Z,fingerprint:$,credentialFingerprint:YZ({type:"oauth",refresh:Z.refresh}),...J?{identity:J}:{}}}function _0(Z){if(p1(Z))return{kind:"placeholder",...GZ(Z)&&typeof Z.accountId==="string"?{origin:Z.accountId}:{}};let $=U0(Z);if(!$?.refresh.trim())return{kind:"empty"};return DJ($)}async function a1(Z){let $=await j0({client:{auth:{get:(J)=>Z.slot.get(J),all:()=>Z.slot.all()}},now:Z.now,sleep:Z.sleep});if($.kind==="real")return _0($.oauth);return $.kind==="slot-absent"||$.kind==="indeterminate"?{kind:$.kind}:{kind:$.kind}}async function DY(Z,$){if(!p1($))return!1;let J=await q1(Z.configPath),X=await S1({provider:U1,configPath:Z.configPath,statePath:Z.statePath,quota:n5}).read();if(X.status==="error")return!1;let z=X.status==="ready"?X.rows.some((G)=>G.id==="main"):X.roster.some((G)=>GZ(G)&&G.id==="main");return s5({kind:"placeholder"},z,qZ(J))}async function PJ(Z){let $=Z.now()+Z.leaseWait.timeoutMs;for(;;){let J=await a1(Z);if(J.kind!=="real")return J;if(!await O0(Z,J.credential.refresh))return J;if(Z.now()>=$)return{kind:"retry"};await Z.sleep(Z.leaseWait.pollMs)}}async function O0(Z,$){let J=await i5(Z.paths),X=J?.refresh?.mainRefreshLeaseUntil;return Boolean(X&&X>Z.now()&&J?.refresh?.mainRefreshLeaseTokenHash===w1($))}function CJ(Z){return Z.length>0&&Z.trim()===Z&&!["__proto__","constructor","prototype","main"].includes(Z)}function TJ(Z,$,J,X,z){let G=J.identity?{identity:J.identity}:{},B=$.find((H)=>!H.invalid&&H.fingerprint===J.credentialFingerprint);if(B)return{rowId:B.id,operation:"rotate",rowFingerprint:B.fingerprint??null,...G,carryLegacyMain:Z==="migrate"&&B.id==="main"};let Q=$.find((H)=>H.id==="main");if(!Q||!Q.invalid&&!Q.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...G,carryLegacyMain:Z==="migrate"};if(J.identity){let H=$.find((V)=>!V.invalid&&V.type==="oauth"&&V.enabled&&V.identity===J.identity);if(H)return{rowId:H.id,operation:"replace",rowFingerprint:H.fingerprint??null,...G,carryLegacyMain:Z==="migrate"&&H.id==="main"}}let Y=new Set($.map((H)=>H.id));return{rowId:X??(J.identity&&CJ(J.identity)&&!Y.has(J.identity)?J.identity:z()),operation:"add",rowFingerprint:null,...G,carryLegacyMain:!1}}function LJ(Z,$,J,X,z,G,B){let Q=$.pending;if(Q){let Y=J.find((V)=>V.id===Q.rowId&&!V.invalid),W=Y?.fingerprint??null,H=X.kind==="real"&&X.fingerprint===Q.slotFingerprint;if(Y&&W===Q.credentialFingerprint)return{kind:"finish",record:Q};if((Y||Q.rowFingerprint===null)&&W===Q.rowFingerprint)return H&&X.kind==="real"?{kind:"transfer",record:Q,credential:X.credential,fresh:!1}:{kind:"drop-record"};if(!Y)return{kind:"drop-record"};return H?{kind:"ambiguous",record:Q}:{kind:"drop-record"}}if(X.kind==="indeterminate")return{kind:"drop-record"};if(X.kind!=="real")return{kind:"nothing",slot:X.kind};if($.declinedSlotFingerprint===X.fingerprint)return{kind:"nothing",slot:"declined"};return{kind:"transfer",record:{...TJ(Z,J,X,z,B),slotFingerprint:X.fingerprint,credentialFingerprint:X.credentialFingerprint,recordedAt:G},credential:X.credential,fresh:!0}}async function _J(Z,$,J){let X={type:"oauth",access:J.access,refresh:J.refresh,...J.expires!==void 0?{expires:J.expires}:{}},z=$.identity?{identity:$.identity}:{},G={extraLocks:a5(Z.paths,$.rowId,Z.locks)};if($.operation==="add")await Z.store.add({id:$.rowId,credential:X,...z},G);else if($.operation==="replace")await Z.store.replace($.rowId,X,z,G);else{let B=await Z.store.read(),Q=B.status==="ready"?B.rows.find((Y)=>Y.id===$.rowId):void 0;await Z.store.rotate($.rowId,X,Q?.identity===void 0?z:{},G)}}async function OJ(Z,$){let J=await Z.store.read();if(J.status!=="ready")return;let X=J.rows.find((z)=>z.id===$.rowId&&!z.invalid);return X?.fingerprint===$.credentialFingerprint?X:void 0}function AJ(Z,$){let J=[],X=[["primary",Z.primary],["secondary",Z.secondary]],z=0;for(let[Q,Y]of X){if(!Y||!Number.isFinite(Y.checkedAt)||!Number.isFinite(Y.usedPercent))continue;z=Math.max(z,Y.checkedAt),J.push({checkedAt:Y.checkedAt,readings:[{label:Q,usedPercent:Y.usedPercent,...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{},...Number.isFinite(Y.windowMinutes)?{windowMinutes:Y.windowMinutes}:{}}]})}let G=$??(z||void 0),B=Z.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&&Z.spendControlCleared)J.push({checkedAt:G,budget:{kind:"cleared"}});return J.sort((Q,Y)=>Q.checkedAt-Y.checkedAt)}async function SJ(Z,$){let J=await i5(Z.paths);if(!J)return;let X=J.quota?.mainQuotaToken,z=$.credential?.type==="oauth"?$.credential.access:void 0,B=!X||z!==void 0&&X===N0(z)?J.quota?.mainQuota:void 0;if(B&&$.credentialEpoch!==void 0){let H={credentialEpoch:$.credentialEpoch,...$.identity!==void 0?{identity:$.identity}:{}};for(let V of AJ(B,J.quota?.mainQuotaCheckedAt))try{await Z.store.recordQuota($.id,H,V)}catch(j){Z.log.warn("legacy main quota not carried to the pool row",{rowId:$.id,error:j instanceof Error?j.message:String(j)})}}let Q=J.refresh?.mainLastRefreshError,Y=J.accounts.find((H)=>H.id===$.id);if(!Y||!M0(Y)||Y.corrupt)return;if(!Q&&!B)return;let W={...J,accounts:[{...Y,...Y.lastRefreshError||!Q?{}:{lastRefreshError:Q},...Y.quota||!B?{}:{quota:B}}]};try{await D0(W,Z.paths,{accounts:[$.id]})}catch(H){Z.log.warn("legacy main backoff not carried to the pool row",{rowId:$.id,error:H instanceof Error?H.message:String(H)})}}async function j1(Z,$,J={}){await s1(Z,(X)=>{let z=qZ(X);if(delete X.mainAccountId,$==="migrate"&&z.migratedAt===void 0)IJ(X);return o5(X,{...z.migratedAt!==void 0||$==="migrate"?{migratedAt:z.migratedAt??Z.now()}:{},...J.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:J.declinedSlotFingerprint}:z.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:z.declinedSlotFingerprint}:{}}),!0})}function IJ(Z){let $=Z.routing;if($===void 0)Z.routing={mode:"main-first"};else if(GZ($)&&$.mode===void 0)Z.routing={...$,mode:"main-first"}}async function E$(Z){await s1(Z,($)=>{let J=qZ($);if(!J.pending)return!1;let{pending:X,...z}=J;return o5($,z),!0})}async function RJ(Z,$){await s1(Z,(J)=>{let X=qZ(J);if($.identity)J.mainAccountId=$.identity;return o5(J,{...X,pending:$}),!0})}async function EJ(Z,$,J,X){let z=await c1(Z,l1,Z.paths.configPath,Z.locks.mainRefreshTtlMs);try{return await bJ(Z,$,J,X)}finally{await z.release().catch(()=>{})}}async function bJ(Z,$,J,X){let z=(W)=>({status:"completed",rowId:J.rowId,operation:X,placeholder:W}),G=await a1(Z);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!==R$(Z))return{status:"foreign-placeholder"};return await j1(Z,$),await Z.onStep("after-record-clear"),z("already-present")}if(Object.keys(await Z.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 E$(Z),await Z.onStep("after-record-clear"),{status:"restart"};if(G.kind!=="real"||G.fingerprint!==J.slotFingerprint)return await j1(Z,$),await Z.onStep("after-record-clear"),z("slot-moved-on");await Z.onStep("before-placeholder-write");let B=await Z.slot.get({path:{id:U1}}),Q=B===void 0||B===null?void 0:_0(B);if(Q?.kind!=="real"||Q.fingerprint!==J.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await Z.slot.set({path:{id:U1},body:{...d1,accountId:R$(Z)}})}catch(W){if(W instanceof d5)return{status:"retry",reason:"slot-changed"};throw W}await Z.onStep("after-placeholder-write");let Y=await Z.slot.get({path:{id:U1}});if(!p1(Y))return{status:"retry",reason:"placeholder-overwritten"};if(GZ(Y)&&Y.accountId===void 0)return{status:"untagged-placeholder"};if(GZ(Y)&&Y.accountId!==R$(Z))return{status:"foreign-placeholder"};return await j1(Z,$),await Z.onStep("after-record-clear"),z("written")}async function yJ(Z,$,J){let{record:X}=J;if(J.fresh)await RJ(Z,X),await Z.onStep("after-record-write");if(await O0(Z,J.credential.refresh))return{status:"restart"};let z=await a1(Z);if(z.kind!=="real"||z.fingerprint!==X.slotFingerprint)return{status:"restart"};return await _J(Z,X,J.credential),await Z.onStep("after-row-write"),A0(Z,$,X,J.fresh?X.operation:"resumed")}async function A0(Z,$,J,X){let z=await OJ(Z,J);if(!z)return{status:"retry",reason:"verify-failed"};if(await Z.onStep("after-verify"),J.carryLegacyMain)await SJ(Z,z),await Z.onStep("after-carry-over");let G=await EJ(Z,$,J,X);if(G.status==="untagged-placeholder"){await Z.store.disable(J.rowId,UJ,{extraLocks:a5(Z.paths,J.rowId,Z.locks),attribution:{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}}}),await j1(Z,$);let B=`${Z.paths.configPath}\x00${J.rowId}`;if(!K0.has(B))K0.add(B),Z.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${jJ}`,{rowId:J.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(G.status!=="foreign-placeholder")return G;return await Z.store.remove(J.rowId,{extraLocks:a5(Z.paths,J.rowId,Z.locks),protect:(B,Q)=>Q.row?.fingerprint!==J.credentialFingerprint?"the transfer row changed before rollback":void 0}),await E$(Z),await b$(Z),{status:"refused",reason:"placeholder-without-main"}}var q0=new Set,F0=new Set,K0=new Set;function R$(Z){return`openai-auth-pool:${BJ("sha256").update(YJ(Z.paths.configPath)).digest("hex")}`}async function kJ(Z){try{let $=await Z();return $.open?[]:$.blockers}catch($){return[{pid:"unknown",version:"unknown",detail:$ instanceof Error?$.message:String($)}]}}async function S0(Z,$,J){let X=qJ(Z),z=X.slot.migrationDisabledReason?.();if(z){let W=X.slot.path??l5();if(!F0.has(W))F0.add(W),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 q1(X.paths.configPath)}catch(W){return{status:"error",reason:W instanceof Error?W.message:String(W)}}let B=await I0(X,$,G);if(B){if(B.status==="already-migrated"&&"mainAccountId"in G)await b$(X);return B}if(J){let W=await kJ(J);if(W.length>0){let H=`${X.paths.configPath}\x00${W.map((V)=>`${V.pid}@${V.version}`).join(",")}`;if(!q0.has(H))q0.add(H),X.log.info("account pool migration deferred: an older openai-auth version is running",{blockers:W});return{status:"deferred",reason:"older-version-running",blockers:W}}}let Q,Y;try{Y=await c1(X,"pool-slot-transfer",X.slot.path??l5(),X.locks.mainRefreshTtlMs,Z.signal),Q=await c1(X,T0,X.paths.configPath,X.locks.mainRefreshTtlMs,Z.signal)}catch(W){if(await Y?.release().catch(()=>{}),W instanceof nZ)return{status:"retry",reason:"lock-contention"};throw W}try{return await vJ(X,$)}catch(W){if(W instanceof nZ)return{status:"retry",reason:"lock-contention"};if(W instanceof R)return{status:"retry",reason:W.kind==="lock-contention"?"lock-contention":`store-${W.kind}`};throw W}finally{await Q?.release().catch(()=>{}),await Y?.release().catch(()=>{})}}async function I0(Z,$,J){let X=qZ(J);if(X.pending)return;if($==="migrate"&&X.migratedAt!==void 0){let z=await Z.store.read();if(z.status==="ready"&&!z.rows.some((G)=>G.id==="main")&&!X.pending&&s5(await a1(Z),z.rows.some((G)=>G.id==="main"),X))return{status:"refused",reason:"placeholder-without-main"};return{status:"already-migrated"}}if($==="adopt"&&X.migratedAt===void 0)return{status:"not-migrated"};return}async function vJ(Z,$){let J;for(let X=0;X<4;X++){let z=await q1(Z.paths.configPath),G=await I0(Z,$,z);if(G){if(G.status==="already-migrated")await b$(Z);return G}let B=await Z.store.read(),Q=qZ(z);if(B.status==="pending-migration"){if(s5(await a1(Z),B.roster.some((V)=>GZ(V)&&V.id==="main"),Q))return{status:"refused",reason:"placeholder-without-main"};await Z.store.initialize(),await Z.onStep("after-pool-key-write"),B=await Z.store.read()}if(B.status!=="ready")return{status:"error",reason:B.status==="error"?`${B.file}: ${B.reason}`:"pool still pending migration"};let Y=await PJ(Z);if(Y.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(Y.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(s5(Y,B.rows.some((V)=>V.id==="main"),Q))return{status:"refused",reason:"placeholder-without-main"};let W=LJ($,Q,B.rows,Y,J,Z.now(),Z.newId);if(W.kind==="nothing"){if($==="migrate")await j1(Z,$),await Z.onStep("after-marker-write");return{status:"nothing-to-import",slot:W.slot}}if(W.kind==="drop-record"){await E$(Z),await Z.onStep("after-record-clear");continue}if(W.kind==="ambiguous")return await j1(Z,$,{declinedSlotFingerprint:W.record.slotFingerprint}),await Z.onStep("after-record-clear"),Z.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:W.record.rowId}),{status:"ambiguous",rowId:W.record.rowId};if(W.kind==="transfer"&&W.fresh)J=W.record.rowId;let H=W.kind==="finish"?await A0(Z,$,W.record,"resumed"):await yJ(Z,$,W);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function b$(Z){await s1(Z,($)=>{if(!("mainAccountId"in $))return!1;if(qZ($).pending)return!1;return delete $.mainAccountId,!0})}function PY(Z){return S0(Z,"migrate",Z.fence)}function CY(Z){return S0(Z,"adopt")}class R0 extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function a5(Z,$,J={}){let X={...r5,...J},z={renew:X.renew,timeoutMs:X.timeoutMs,retryMs:X.retryMs,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}};return[{name:l1,path:Z.configPath,ttlMs:X.mainRefreshTtlMs,...z},{name:C0($),path:Z.configPath,ttlMs:X.fallbackTtlMs,...z}]}async function TY(Z,$,J,X={}){let z=Z.now??Date.now,G=Z.sleep??((Y)=>new Promise((W)=>setTimeout(W,Y))),B=Z.leaseWait??{timeoutMs:4000,pollMs:50},Q=async(Y,W)=>{let H=w1(Y.refresh),V=async()=>{let j=await i5(Z.paths),F=j?.refresh?.mainRefreshLeaseUntil;return Boolean(F&&F>z()&&j?.refresh?.mainRefreshLeaseTokenHash===H)};if(await V()){let j=z()+B.timeoutMs;while(z()<j&&await V())await G(B.pollMs);throw new R0}return J(Y,W)};return Z.store.refresh($,Q,{...X,extraLocks:a5(Z.paths,$,Z.legacyLocks)})}function E0(){let Z=crypto.getRandomValues(new Uint8Array(16)),$=Date.now();Z[0]=$/1099511627776&255,Z[1]=$/4294967296&255,Z[2]=$/16777216&255,Z[3]=$/65536&255,Z[4]=$/256&255,Z[5]=$&255,Z[6]=(Z[6]??0)&15|112,Z[8]=(Z[8]??0)&63|128;let J=Array.from(Z,(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 gJ,mkdirSync as b0,readFileSync as fJ,renameSync as hJ,writeFileSync as xJ}from"node:fs";import{dirname as y0}from"node:path";var y$="sessions",mJ=1e4,wJ=5000,uJ=25;async function pJ(Z,$=wJ){let J=performance.now()+$;for(;;){let X=await QZ({name:y$,path:Z,ttlMs:mJ});if(X||performance.now()>=J)return X;await new Promise((z)=>setTimeout(z,uJ))}}function lJ(Z){let $=new Map,J=JSON.parse(fJ(Z,"utf8"));if(!k(J.sessions))return $;for(let[X,z]of Object.entries(J.sessions)){if(!k(z)||typeof z.threadID!=="string")continue;$.set(X,z.threadID)}return $}function EY(Z,$=E0){let J=new Map,X;try{X=lJ(Z)}catch{return J}for(let[z,G]of X)J.set(z,{threadID:G,turnID:$(),windowID:`${G}:0`});return J}function dJ(Z,$){let J=`${Z}.tmp-${process.pid}`;b0(y0(Z),{recursive:!0});let X={version:1,sessions:Object.fromEntries([...$].map(([z,G])=>[z,{threadID:G}]))};xJ(J,`${JSON.stringify(X,null,2)}
69
- `,{encoding:"utf8",mode:384}),gJ(J,384),hJ(J,Z)}var t5=new Map;function bY(Z,$){let X=(t5.get(Z)??Promise.resolve()).then(async()=>{let z=null;try{if(b0(y0(Z),{recursive:!0}),z=await pJ(Z),!z)return;dJ(Z,[...$.entries()].map(([G,B])=>[G,B.threadID]))}catch{}finally{await z?.release().catch(()=>{})}});return t5.set(Z,X),X.then(()=>{if(t5.get(Z)===X)t5.delete(Z)}),X}import{randomUUID as cJ}from"node:crypto";import{chmod as sJ,mkdir as aJ,rename as nJ,rm as k$,writeFile as iJ}from"node:fs/promises";import{homedir as rJ}from"node:os";import{join as Z9}from"node:path";function v$(){let Z=process.env.XDG_STATE_HOME||Z9(rJ(),".local","state");return Z9(Z,"cortexkit","openai-auth","processes")}function k0(Z=process.pid,$=v$()){return Z9($,`${Z}.json`)}var e5=0,$9,v0=Symbol.for("@cortexkit/openai-auth/process-layouts"),g0=globalThis,J9=g0[v0]??new Map;g0[v0]=J9;function f0(){return{...Object.fromEntries(J9),...o()?{"*":"legacy"}:{}}}function oJ(){if(o())return!0;for(let Z of J9.values())if(Z==="legacy")return!0;return!1}async function h0(Z,$){await aJ(Z,{recursive:!0,mode:448}),await sJ(Z,448);let J=k0($.pid,Z),X=Z9(Z,`0${$.pid}.json`),z=o()?[X,J]:[J];if(!o())await k$(X,{force:!0}).catch(()=>{});for(let G of z){let B=`${G}.${cJ()}.tmp`;try{await iJ(B,`${JSON.stringify($)}
70
- `,{mode:384}),await nJ(B,G)}catch(Q){throw await k$(B,{force:!0}).catch(()=>{}),Q}}return J}async function xY(Z){let $=Z.pid??process.pid,J=Z.dir??v$();$9??=(Z.now??Date.now)(),e5++;let X;try{X=await h0(J,{pid:$,version:Z.version,startedAt:$9,layouts:f0()})}catch(G){Z.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,e5=Math.max(0,e5-1),e5>0)return;if(oJ())return;await k$(k0($,J),{force:!0}).catch((G)=>{Z.logger.warn("process heartbeat not removed",{dir:J,error:G instanceof Error?G.message:String(G)})})}}}async function X9(Z){let $=o()?"legacy":Z.layout;if(J9.set(Z.key,$),$!=="legacy")return;$9??=(Z.now??Date.now)(),await h0(Z.dir??v$(),{pid:Z.pid??process.pid,version:Z.version,startedAt:$9,layouts:f0()})}import{createHash as tJ}from"node:crypto";import{realpathSync as eJ}from"node:fs";import{chmod as ZX,mkdir as $X,readdir as JX,readFile as FZ,rmdir as s0,stat as a0,unlink as W9}from"node:fs/promises";import{basename as n0,dirname as i0,isAbsolute as XX,join as f,relative as zX,resolve as B9}from"node:path";var GX="runtime-layout",F1="layout-moving.json",r0=1e4,z9=15000,BX=4*z9+r0,QX=50,WX=5,YX=50,HX=[0,10,20,40,80,100],x0=500,VX="openai-auth keeps its files in OpenCode's config folder until every running OpenCode using it has restarted on this version.",m0="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 t extends Error{stateDir;errorClass;constructor(Z,$,J=UX(Z,$)){super(J);this.stateDir=Z;this.errorClass=$;this.name="RuntimeLayoutRefusal"}}function UX(Z,$){if($==="ERR_PRIVATE_FILES_SECURITY")return`openai-auth cannot start: ${Z} is not a folder only your user can access, or it is a link, so the plugin will not use it (${$}). 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 w0(Z,$){return new t(Z,"foreign-folder",`openai-auth cannot start: ${Z} belongs to another OpenCode config folder, not ${$}. It was left untouched. Move it aside, then restart OpenCode.`)}function Q9(Z,$){return new t(Z,"credential-conflict",`openai-auth cannot start: runtime credentials conflict between ${$.old} and ${$.next}. Keep the newer one, delete the other, then restart OpenCode.`)}function eY(){let Z=EZ.notice;if(!Z||Z.shown)return;return Z.shown=!0,Z.text}function _Z(Z,$){if(EZ.logged.has(Z))return;EZ.logged.add(Z),$()}function bZ(Z){if(Z instanceof t)return Z.errorClass;let $=Z?.code;if(typeof $==="string"&&$)return $;return Z instanceof Error?Z.name:typeof Z}function jX(Z){let{path:$,stage:J}=Z??{};return{...typeof $==="string"&&$?{file:n0($)}:{},...typeof J==="string"&&J?{stage:J}:{}}}class i1 extends Error{code;constructor(Z,$){super($);this.code=Z;this.name="LayoutMoveError"}}class f$ extends i1{path;constructor(Z){super("old-credential-kept",`${Z} could not be removed`);this.path=Z}}function o0(Z,$,J,X){_Z(`${Z.key}\x00cleanup`,()=>$.warn("openai-auth could not finish removing its old files from OpenCode's config folder; it tries again at the next start",{configDir:Z.configDir,step:J,errorClass:bZ(X),...jX(X)}))}function ZH(Z){let $=w5(),J=p5($);if(J)return Promise.resolve(J);let X=`${$.stateHomeDir}\x00${$.key}`,z=EZ.runs.get(X);if(!z)z=qX($,Z).catch((G)=>{if(G instanceof t)throw G;throw new t($.stateHomeDir,bZ(G))}).finally(()=>{EZ.runs.delete(X)}),EZ.runs.set(X,z);return z}async function qX(Z,$){let J=$.log??s("runtime-layout");if(o()){u5(Z,"legacy"),_Z("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 X9({key:Z.key,layout:"legacy",version:$.version})}catch(K){J.warn("process heartbeat not written",{errorClass:bZ(K)})}return"legacy"}let X=Z.stateHomeDir,z=f(X,f5),G=x$(Z),B=KX(),Q=B.length>0,Y=B.some((K)=>t0(K,X)),W=$.fence??FX($.version),H=async()=>{return await X9({key:Z.key,layout:"state-home",version:$.version}),u5(Z,"state-home"),"state-home"},V=await n1(z,X);if(await c0(Z,V),V?.oldFilesRemoved&&!Y){if(await EX(Z,G,B,V,J),!await BZ(f(X,F1)).catch(()=>!0))return H()}let j=await G3(Z.configDir,X),F;try{if(!j)await Q3(X);F=await G9(GX,z,$.layoutLockWaitMs??BX)}catch(K){if(V=await n1(z,X),V&&!Y)return H();throw new t(X,bZ(K))}let U=F,q=async()=>{try{await U.assertOwned(),await X9({key:Z.key,layout:"legacy",version:$.version})}catch(K){throw new t(X,bZ(K))}return u5(Z,"legacy"),"legacy"};try{if(V=await n1(z,X),await c0(Z,V),!j)await bX(Z);if(Y)return _Z(`${Z.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 q();if(V){if(!V.oldFilesRemoved&&!Q&&!j)await MX(Z,G,z,V,U,{fence:W,log:J,steps:$.steps});else if(V.oldFilesRemoved)await DX(Z,U,$.steps,J);return await H()}if(Q)return await q();if(j)return _Z(`${Z.key}\x00aliased`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: its state folder is that same folder",{configDir:Z.configDir,stateDir:X})),await q();let K=await W();if(!K.open)return u0(Z,K.blockers,J),await q();let N=!1;try{let D=await NX(Z,G,z,U,{fence:W,log:J,steps:$.steps,onMarker:()=>{N=!0}});if(D.kind==="deferred")return u0(Z,D.blockers,J),await q();if(D.kind==="refused")return _Z(`${Z.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 q();if(D.moved)J.info("openai-auth moved its runtime files out of OpenCode's config folder",{from:Z.configDir,to:X});return await H()}catch(D){if(D instanceof t)throw D;if(N&&await n1(z,X))return await H();return _Z(`${Z.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:Z.configDir,errorClass:bZ(D)})),await q()}}finally{await U.release().catch(()=>{})}}function FX(Z){return()=>a7({currentVersion:Z,layoutMove:!0})}function u0(Z,$,J){_Z(`${Z.key}\x00deferred`,()=>J.info(VX,{configDir:Z.configDir,blockers:$}))}function KX(){let Z=J0();if(Z===void 0)return[];let $=X0();return[Z,_5(Z),...$?[$]:[]]}function t0(Z,$){let J=zX(p0($),p0(Z));if(J==="")return!0;if(!J.startsWith("..")&&!XX(J))return!0;return m5(Z,$)}function p0(Z){let $=B9(Z),J=[];for(;;){try{return f(eJ.native($),...J)}catch{}let X=i0($);if(X===$)return B9(Z);J.unshift(n0($)),$=X}}async function NX(Z,$,J,X,z){let G=Z.stateHomeDir,B=await Z3(Z,$),Q=!1;try{let Y=await z.fence();if(!Y.open)return{kind:"deferred",blockers:Y.blockers};let W=await z3(Z,$);if(W.length>0)return{kind:"refused",reason:"same-physical-file",paths:W};let H=await yX(G),V=(await OX($)).filter((K)=>!H.has(K));if(V.length>0)return{kind:"refused",reason:"destination-in-use",paths:V};let j=await X3($);await X.assertOwned(),await kX(G,[...new Set([...H,...j.map((K)=>K.next)])]);let F=new Set(j.map((K)=>K.next));for(let K of H){if(F.has(K))continue;await X.assertOwned(),await W9(K).catch((N)=>{if(N.code!=="ENOENT")throw N})}for(let K of j)await X.assertOwned(),await AX(K);await z.steps?.afterCopy?.(),await X.assertOwned();for(let K of B)await K.assertOwned();let U=await TX($,j),q={version:1,oldDir:Z.key,...U?{keptVaultState:U}:{}};z.onMarker(),await g$(J,q),await z.steps?.afterMarker?.(),await X.assertOwned();try{await B3(Z,j,X,{log:z.log,keptVaultState:U,steps:z.steps})}catch(K){if(!(K instanceof f$))throw K;return o0(Z,z.log,"remove-old-copies",K),{kind:"moved",moved:j.length>0}}return Q=!0,await X.assertOwned(),await g$(J,{...q,oldFilesRemoved:!0}),await h$(G,X,z.steps),{kind:"moved",moved:j.length>0}}finally{for(let Y of B.reverse())await Y.release().catch(()=>{});if(Q)await e0($,X,z.steps)}}async function MX(Z,$,J,X,z,G){let B=[],Q=!1,Y="fence";try{if(!(await G.fence()).open)return;if(Y="data-locks",B=await Z3(Z,$),Y="fence",!(await G.fence()).open)return;Y="same-file-check";let W=await z3(Z,$);if(W.length>0){_Z(`${Z.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:W}));return}Y="remove-old-copies",await z.assertOwned(),await B3(Z,await X3($),z,{log:G.log,keptVaultState:X.keptVaultState,steps:G.steps}),Q=!0,Y="marker",await z.assertOwned(),await g$(J,{...X,oldFilesRemoved:!0}),Y="manifest",await h$(Z.stateHomeDir,z,G.steps)}catch(W){if(W instanceof t)throw W;o0(Z,G.log,Y,W)}finally{for(let W of B.reverse())await W.release().catch(()=>{});if(Q)await e0($,z,G.steps)}}async function DX(Z,$,J,X){try{await h$(Z.stateHomeDir,$,J)}catch(z){_Z(`${Z.key}\x00manifest`,()=>X.warn(`openai-auth could not remove ${F1} from its state folder; it tries again at the next start`,{stateDir:Z.stateHomeDir,errorClass:bZ(z)}))}}async function h$(Z,$,J){let X=f(Z,F1);if(!await BZ(X))return;await J?.beforeRemove?.(X),await $.assertOwned(),await vX(Z)}async function e0(Z,$,J){try{await J?.beforeRemove?.(Z.vault.old),await $.assertOwned(),await s0(Z.vault.old)}catch{}}async function Z3(Z,$){let J=[];try{if(await BZ(Z.configDir)){if(J.push(await G9("save",$.state.old,z9)),await BZ($.vault.old))J.push(await G9("claustrum-roster-write",X1($.vault.old,"opencode").rosterPath,z9));for(let X of $.sessions)J.push(await G9(y$,X.old,z9))}return J}catch(X){for(let z of J.reverse())await z.release().catch(()=>{});throw X}}function x$(Z){let $=f(Z.configDir,u1),J=f(Z.stateHomeDir,u1);return{state:{old:$,next:J},vault:{old:_5($),next:_5(J)},sessions:[T$,L$].map((X)=>({old:f(Z.configDir,X),next:f(Z.stateHomeDir,X)}))}}var PX=/^[0-9a-f]{64}$/;function $3(Z){return tJ("sha256").update(Z).digest("hex")}function Y9(Z){return{old:X1(Z.vault.old,"opencode").statePath,next:X1(Z.vault.next,"opencode").statePath}}var l0=l9("opencode"),CX="opencode-enrollment-no-token.json";async function J3(Z){try{let $=await L5(Z,l0);return $.state==="blocked"&&$.code==="missing_token"&&$.proposedName===l0}catch{return!1}}async function TX(Z,$){let J=Y9(Z);if(!$.some((z)=>z.old===J.old))return;return await J3({statePath:J.next,tokenPath:f(Z.vault.next,CX)})?$3(await FZ(J.next)):void 0}async function LX(Z,$){if(!$)return!1;try{return $3(await FZ(Z))===$}catch{return!1}}async function m$(Z,$){if(!$)return!1;let J=X1(Z.vault.old,"opencode");if(await LX(J.statePath,$))return!0;return J3(J)}async function $H(Z){let $=w5(),J=x$($);if(B9(Z)!==B9(J.vault.next))return;let X=$.stateHomeDir,z=await n1(f(X,f5),X);if(!z?.keptVaultState||z.oldDir!==$.key)return;let G=Y9(J).old;if(!await m$(J,z.keptVaultState))return;await W9(G).catch((B)=>{if(B.code!=="ENOENT")throw B}),await s0(J.vault.old).catch(()=>{})}function _X(Z){return Z.includes(".lock")||Z.includes(".tmp")}async function H9(Z){let $;try{$=await JX(Z,{withFileTypes:!0})}catch(J){let X=J.code;if(X==="ENOENT"||X==="ENOTDIR")return[];throw J}return $.filter((J)=>J.isFile()&&!_X(J.name)).map((J)=>J.name).sort()}async function X3(Z){let $=[];if(await BZ(Z.state.old))$.push(Z.state);for(let J of await H9(Z.vault.old))$.push({old:f(Z.vault.old,J),next:f(Z.vault.next,J)});for(let J of Z.sessions)if(await BZ(J.old))$.push(J);return $}async function OX(Z){let $=[];if(await BZ(Z.state.next))$.push(Z.state.next);for(let J of await H9(Z.vault.next))$.push(f(Z.vault.next,J));for(let J of Z.sessions)if(await BZ(J.next))$.push(J.next);return $}async function z3(Z,$){let J=[[Z.configDir,Z.stateHomeDir],[$.vault.old,$.vault.next],[$.state.old,$.state.next],...$.sessions.map((z)=>[z.old,z.next])];for(let z of await H9($.vault.old))J.push([f($.vault.old,z),f($.vault.next,z)]);let X=[];for(let[z,G]of J)if(await G3(z,G))X.push(z);return X}async function G3(Z,$){let J=async(z)=>{try{let G=await a0(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(Z);return X!==void 0&&X===await J($)}async function AX(Z){let $=await FZ(Z.old),J=$.toString("utf8");if(!Buffer.from(J,"utf8").equals($))throw new i1("not-utf8",`${Z.old} is not UTF-8 text`);if(await V9(Z.next,J),!(await FZ(Z.next)).equals($))throw new i1("copy-mismatch",`${Z.next} does not match ${Z.old}`)}async function B3(Z,$,J,X){let z=[],G=[],B=x$(Z),Q=Y9(B).old,Y=[...$.filter((H)=>H.old!==Q),...$.filter((H)=>H.old===Q)];for(let H of Y){if(await J.assertOwned(),H.old===Q){if(await m$(B,X.keptVaultState))continue;if(G.length>0)continue;if(X.keptVaultState&&await SX(H.old,H.next))continue}let V=H.old===B.state.old||t0(H.old,B.vault.old);if(!await RX(H,Z.stateHomeDir,V,()=>IX(H.old,J,X.steps)))(V?G:z).push(H.old)}if(z.length>0)X.log.warn("openai-auth left old files in OpenCode's config folder; it no longer reads them",{configDir:Z.configDir,kept:z});let[W]=G;if(W!==void 0)throw new f$(W)}async function SX(Z,$){try{return(await FZ(Z)).equals(await FZ($))}catch{return!1}}async function IX(Z,$,J){await J?.beforeRemove?.(Z),await $.assertOwned()}function d0(Z){let $=Z?.code;return process.platform==="win32"&&($==="EBUSY"||$==="EPERM"||$==="EACCES")}async function RX(Z,$,J,X){let z=performance.now();for(let G of HX){if(G>0)await new Promise((Q)=>setTimeout(Q,G));let B;try{B=(await FZ(Z.old)).equals(await FZ(Z.next))}catch(Q){if(Q.code==="ENOENT"&&!await BZ(Z.old))return!0;if(d0(Q)){if(performance.now()-z>=x0)return!1;continue}if(J)throw Q9($,Z);return!1}if(!B){if(J)throw Q9($,Z);return!1}await X();try{return await W9(Z.old),!0}catch(Q){if(Q.code==="ENOENT")return!0;if(!d0(Q)||performance.now()-z>=x0)return!1}}return!1}async function EX(Z,$,J,X,z){let G=(Q)=>J.some((Y)=>m5(Y,Q));if(!G($.state.old)&&await BZ($.state.old))throw Q9(Z.stateHomeDir,$.state);if(!G($.vault.old)){let Q=Y9($).old;for(let Y of await H9($.vault.old)){let W=f($.vault.old,Y);if(W===Q&&await m$($,X.keptVaultState))continue;if(!G(W))throw Q9(Z.stateHomeDir,{old:W,next:f($.vault.next,Y)})}}let B=[];try{for(let Q of $.sessions)if(await BZ(Q.old))B.push(Q.old)}catch{}if(B.length===0)return;_Z(`${Z.key}\x00reappeared`,()=>{EZ.notice={text:`${m0} Old folder: ${Z.configDir}`,shown:!1},z.warn(m0,{configDir:Z.configDir,stateDir:Z.stateHomeDir,found:B})})}async function n1(Z,$){let J,X;for(let z=0;z<WX;z++){if(z>0)await new Promise((G)=>setTimeout(G,YX));try{J=await FZ(Z,"utf8");break}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;X=G}}if(J===void 0)throw new t($,bZ(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"&&PX.test(z.keptVaultState)?{keptVaultState:z.keptVaultState}:{}}}catch{}throw new t($,"malformed-marker",`openai-auth cannot start: ${Z} is malformed. The old files are still in OpenCode's config folder. Delete layout.json, then restart OpenCode.`)}async function c0(Z,$){let J=Z.stateHomeDir;if($?.oldDir!==void 0&&$.oldDir!==Z.key)throw w0(J,Z.key);let X;try{X=await FZ(f(J,_$),"utf8")}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;throw new t(J,bZ(G))}let z;try{z=JSON.parse(X)?.configDir}catch{}if(z!==Z.key)throw w0(J,Z.key)}async function bX(Z){let $=f(Z.stateHomeDir,_$);if(await BZ($))return;await V9($,`${JSON.stringify({version:1,configDir:Z.key},null,2)}
71
- `)}async function yX(Z){let $;try{$=await FZ(f(Z,F1),"utf8")}catch(J){if(J.code==="ENOENT")return new Set;throw J}try{let J=JSON.parse($);if(Array.isArray(J?.files))return new Set(J.files.filter((X)=>typeof X==="string"))}catch{}return new Set}async function kX(Z,$){await V9(f(Z,F1),`${JSON.stringify({version:1,files:$},null,2)}
72
- `)}async function vX(Z){await W9(f(Z,F1)).catch(($)=>{if($.code!=="ENOENT")throw $})}async function g$(Z,$){await V9(Z,`${JSON.stringify($,null,2)}
73
- `)}async function V9(Z,$){await Q3(i0(Z)),await AZ(Z,null,{serialize:()=>$,durable:!0,durability:"file-only-on-windows"})}async function Q3(Z){if(process.platform==="win32")return;await $X(Z,{recursive:!0,mode:448}),await ZX(Z,448)}async function G9(Z,$,J){let X=performance.now();for(;;){let z=null;try{z=await QZ({name:Z,path:$,ttlMs:r0,renew:!0})}catch(G){if(G.code!=="ENOENT")throw G}if(z)return z;if(performance.now()-X>=J)throw new i1("lock-timeout",`${Z} lock at ${$}`);await new Promise((G)=>setTimeout(G,QX))}}async function BZ(Z){try{return await a0(Z),!0}catch($){let J=$.code;if(J==="ENOENT"||J==="ENOTDIR")return!1;throw $}}
74
- export{S1 as ja,u as ka,K8 as la,k as ma,M6 as na,l9 as oa,_5 as pa,SB as qa,_8 as ra,IB as sa,RB as ta,A8 as ua,O5 as va,C6 as wa,d9 as xa,i9 as ya,o9 as za,cZ as Aa,t9 as Ba,B1 as Ca,y1 as Da,r8 as Ea,Z2 as Fa,$2 as Ga,sZ as Ha,J2 as Ia,f1 as Ja,G2 as Ka,vQ as La,gQ as Ma,fQ as Na,hQ as Oa,xQ as Pa,mQ as Qa,eQ as Ra,p7 as Sa,zW as Ta,GW as Ua,m2 as Va,BW as Wa,QW as Xa,WW as Ya,YW as Za,sQ as _a,Q1 as $a,U$ as ab,E2 as bb,rQ as cb,a7 as db,iW as eb,t2 as fb,rW as gb,HJ as hb,d1 as ib,UJ as jb,jJ as kb,KY as lb,NY as mb,KJ as nb,MY as ob,qZ as pb,DY as qb,PY as rb,CY as sb,a5 as tb,TY as ub,l1 as vb,B0 as wb,l5 as xb,H0 as yb,d5 as zb,zY as Ab,E0 as Bb,wJ as Cb,pJ as Db,lJ as Eb,EY as Fb,dJ as Gb,bY as Hb,xY as Ib,eY as Jb,ZH as Kb,$H as Lb};
67
+ ${G[z]??"The server returned a no-op result. No reset was confirmed."}`)}var U$=s("quota"),A7="the account holds a tombstone from the removed vault custody, not a credential";function C2(Z){return Z?.status===401}async function iQ(Z,$={}){let J=Z.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let X=[],z=Z.logger??U$,G=(U)=>{X.push(U);let q={pid:process.pid,accountId:U.account,status:U.ok?"ok":"error",...U.error?{error:U.error}:{}};if(U.ok)z.debug("quota refresh succeeded",q);else z.warn("quota refresh failed",q)},B=Z.skipFresherThanMs,Q=!1,Y;if(B!==void 0)try{Y=await Z.readSidebarState()}catch{}let W=new Map(Y?.fallbacks.map((U)=>[U.id,U])??[]),H=(...U)=>B!==void 0&&U.some((q)=>typeof q==="number"&&Number.isFinite(q)&&q<=Z.now()&&Z.now()-q<B),V=await Z.loadAccounts(Z.paths).catch(()=>{return}),j=V?.mainAccountId??Z.storageMainAccountId,F;if(!$.accountKey||$.accountKey==="main")try{let U=await Z.getAuth();if(E7(U)){if(F=b7(V),!F)G({account:"main",ok:!1,error:x1(U)?A7:"main account row is missing from the account pool"})}else if(U.type==="oauth"){let q=Y&&j!==void 0&&Y.main.mainAccountId===j?Y.main.quota:void 0;if(H(Z.quotaManager.peekMainForPolicy(j)?.checkedAt,q?.primary?.checkedAt,q?.secondary?.checkedAt,q?.checkedAt))G({account:"main",ok:!0});else{if(!U.access||(U.expires??0)<Z.now()){let N=await Z.refreshMainWithLease();U={...U,access:N.access,expires:N.expires}}if(U.access)if(Z.respectBackoff&&Z.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let N=await J({accessToken:U.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:j,accountKey:"main"});Z.quotaManager.setMain(U.access,{quota:N,refreshAfter:Z.now()+300000,checkedAt:Z.now()},j,!0),Q=!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:TZ(U)})}if(V)for(let U of V.accounts){let q=F!==void 0&&U===F;if(!q&&$.accountKey&&($.accountKey==="main"||U.id!==$.accountKey))continue;if(!q&&Z.isOAuthAccountFn(U)&&R7(V,U)){if($.accountKey)G({account:U.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let K=q?U.accountId??j:void 0,N=(M,O,_)=>{if(q)Z.quotaManager.setMain(O,M,K,!0);else Z.quotaManager.setFallback(U.id,M,O,!0,_)};if(U.enabled===!1||!Z.isOAuthAccountFn(U)){if($.accountKey)G({account:U.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let M=W.get(U.id),O=U.accountId,_=q?Y&&K!==void 0&&Y.main.mainAccountId===K?Y.main.quota:void 0:M&&O!==void 0&&M.accountId===O?M.quota:void 0;if(H(q?Z.quotaManager.peekMainForPolicy(K)?.checkedAt:Z.quotaManager.peekFallbackForPolicy(U.id,O)?.checkedAt,_?.primary?.checkedAt,_?.secondary?.checkedAt,_?.checkedAt)){G({account:U.id,ok:!0});continue}if(Z.respectBackoff&&(q?Z.quotaManager.isBackedOff():Z.quotaManager.isFallbackBackedOff(U.id,U.access))){G({account:U.id,ok:!0});continue}let D=U.lastRefreshError;if(S7(D,U.refresh,Z.now())){G({account:U.id,ok:!1,error:I7(D,Z.now()),permanent:!0});continue}if(x1(U)){G({account:U.id,ok:!1,error:A7});continue}let T;try{T=q?await Z.fallbackManager.refreshAccount(U,V,{asPoolMain:!0}):await Z.fallbackManager.refreshAccount(U,V)}catch(L){U$.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:U.id,error:TZ(L)}),T=U}if(!T.access||(T.expires??0)<Z.now()){G({account:U.id,ok:!1,error:"no usable access token"});continue}let A;try{A=await J({accessToken:T.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:T.accountId,accountKey:U.id})}catch(L){if(!C2(L))throw L;if(U$.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:U.id}),T=await Z.fallbackManager.refreshAccount(U,V,q?{force:!0,asPoolMain:!0}:{force:!0}),!T.access){G({account:U.id,ok:!1,error:"no usable access token after forced refresh"});continue}A=await J({accessToken:T.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:T.accountId,accountKey:U.id})}N({quota:A,refreshAfter:Z.now()+300000,checkedAt:Z.now()},T.access,T.accountId),Q=!0,G({account:U.id,ok:!0})}catch(M){G({account:U.id,ok:!1,error:TZ(M)})}}if($.accountKey&&$.accountKey!=="main"&&!X.some((U)=>U.account===$.accountKey))X.push({account:$.accountKey,ok:!1,error:"account not found"});if(B===void 0||Q){let U=await Z.loadAccounts(Z.paths);await Z.writeSidebarState(Z.quotaManager,U)}return X}import{types as T2}from"node:util";var _2=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,L2=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function h7(Z){return Z.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,($,J,X)=>{if(J)return String.fromCharCode(Number.parseInt(J,16));return{b:"\b",f:"\f",n:`
68
+ `,r:"\r",t:"\t"}[X]??X??$})}function O2(Z,$){if(!$)return Z;let J=Z.split($).join("[credential]"),X=$.replace(/\s/g,"");if(!X)return J;let z=J.replace(/\s/g,"");if(!z.includes(X))return J;let G=[];for(let Y=0;Y<J.length;Y++){let W=J[Y]??"";if(!/\s/.test(W))G.push(Y)}let B=[],Q=0;for(let Y=z.indexOf(X);Y>=0;Y=z.indexOf(X,Y+X.length)){let W=G[Y]??Q,H=(G[Y+X.length-1]??W)+1;B.push(J.slice(Q,W),"[credential]"),Q=H}return B.length?B.join("")+J.slice(Q):J}function y7(Z,$){let J=O2(Z,$);return g7(J).replaceAll("***REDACTED***","[credential]")}function Q1(Z,$){let J=y7(Z,$),X=h7(J),z=y7(X,$);return z===X?J:z}function k7(Z){let $=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(Z);if(!$)return;let J=$[3]??"",X=($[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=$[4]??"0",Q=B.startsWith("-")||B.startsWith("+")?1:0;while(B[Q]==="0")Q++;let Y=B.slice(Q)||"0";if(Y.length>16)return;let W=BigInt((B.startsWith("-")?"-":"")+Y)-BigInt(J.length)+BigInt(X.length-G);return`${$[1]}${X.slice(z,G)}e${W}`}function f7(Z,$){let J=$?k7($):void 0;return Z.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(X)=>{if(!X.startsWith('"'))return $&&(X===$||J!==void 0&&k7(X)===J||($==="Infinity"||$==="-Infinity")&&/^[-\d]/.test(X)&&String(Number(X))===$)?'"[credential]"':X;let z=h7(X.slice(1,-1)),G=Q1(z,$);return G===z?X:JSON.stringify(G)})}function q$(Z,$){let J=f7(Z,$);try{return JSON.parse(Z),J}catch{return Q1(J,$)}}var A2=16384,S2=65536,I2=[/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 R2(Z){try{let $=m(JSON.parse(Z),"request_id");if(typeof $==="string")return $;if(typeof $!=="number")return;let J=0,X,z=!0,G=!1,B;for(let Q of Z.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Y=Q[0];if(Y==="{"||Y==="["){J++;continue}if(Y==="}"||Y==="]"){J--;continue}if(J!==1)continue;if(Y===","){z=!0,G=!1,X=void 0;continue}if(Y===":"){G=!0;continue}if(z&&Y.startsWith('"')){X=JSON.parse(Y),z=!1;continue}if(G&&X==="request_id"&&!Y.startsWith('"'))B=Y;G=!1}return B}catch{return}}function E2(Z,$){let J=q$(Z,$);if(Buffer.byteLength(J,"utf8")<=S2)return J;let X=I2.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(m(G,"type")==="error")z.type="error";let B=m(G,"error"),Q={};for(let W of["code","type"]){let H=m(B,W);if(typeof H==="string")Q[W]=H.slice(0,256)}if(Object.keys(Q).length)z.error=Q;let Y={};for(let W of["workspace","limitName"]){let H=m(m(G,"metadata"),W);if(typeof H==="string")Y[W]=H.slice(0,256)}if(Object.keys(Y).length)z.metadata=Y}catch{}return JSON.stringify(z)}function g5(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;for(let J=0;$&&J<16;J++){if(T2.isProxy($))return!1;$=Object.getPrototypeOf($)}return $===null}function m(Z,$){if(!g5(Z))return;let J=Object.getOwnPropertyDescriptor(Z,$);return J&&"value"in J?J.value:void 0}function m1(Z,$){return Q1(Z,$).slice(0,A2)}function W1(Z,$){let J=Object.getOwnPropertyDescriptor(Z,$)?.get;if(!J)throw Error(`Missing native ${$} accessor`);return J}var b2=W1(DOMException.prototype,"message"),y2=W1(DOMException.prototype,"name");function j$(Z,$){let J=m(Z,"message"),X=m(Z,"name");if(g5(Z)&&Z instanceof DOMException)try{J=b2.call(Z),X=y2.call(Z)}catch{}let z=Error(m1(typeof J==="string"?J:typeof Z==="string"?Z:"Provider request failed",$));for(let V of Object.getOwnPropertyNames(z))if(V!=="message")Reflect.deleteProperty(z,V);Object.defineProperty(z,"name",{value:typeof X==="string"?m1(X,$):"Error",configurable:!0,writable:!0});let G=(V,j,F)=>{let U=m(V,F);if(typeof U==="string"||typeof U==="number"&&Number.isFinite(U)||typeof U==="boolean")Object.defineProperty(j,F,{value:typeof U==="string"?m1(U,$):U,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=m(Z,V);if(typeof j==="number"&&Number.isFinite(j))G(Z,z,V)}for(let V of["code","type","isRetryable"])G(Z,z,V);for(let V of["error","data"]){let j=m(Z,V),F=Object.create(null);for(let q of["type","code","message","resets_at","resets_in_seconds"])G(j,F,q);let U=m(j,"error");if(g5(U)){let q=Object.create(null);for(let K of["type","code","message","resets_at","resets_in_seconds"])G(U,q,K);F.error=q}if(Object.keys(F).length)Object.defineProperty(z,V,{value:F,enumerable:!0})}let B=m(Z,"responseHeaders");if(B&&typeof B==="object"){let V={};for(let j of["retry-after-ms","retry-after"]){let F=m(B,j);if(typeof F==="string")V[j]=m1(F,$)}Object.defineProperty(z,"responseHeaders",{value:V,enumerable:!0})}let Q=m(Z,"responseBody");if(typeof Q==="string")Object.defineProperty(z,"responseBody",{value:E2(Q,$),enumerable:!0});let Y=m(Z,"request_id"),W=m(B,"x-request-id"),H=typeof Y==="string"?Y:typeof W==="string"?W:typeof Q==="string"?R2(q$(Q,$)):void 0;if(typeof H==="string")Object.defineProperty(z,"request_id",{value:m1(H,$),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(V);if(m(Z,j)===!0)Object.defineProperty(z,j,{value:!0})}return z}function k2(Z,$){if(!Z.includes("error")&&(!Z.includes("\\u00")||!_2.test(Z)&&!L2.test(Z)))return Z;let J;try{J=JSON.parse(Z)}catch{return Z}if(J?.type==="error"||J?.error||J?.response?.error)return f7(Z,$);return Z}var v2=W1(Response.prototype,"status"),g2=W1(Response.prototype,"statusText"),h2=W1(Response.prototype,"headers"),f2=W1(Response.prototype,"body"),x2=Response.prototype.text,v7=Headers.prototype.entries;async function eQ(Z,$,J="http"){try{let F=function(U){let q=j&&U.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,q+U.slice(q.length).replace(/^data: ?([^\r\n]*)/gm,(K,N)=>K.slice(0,K.length-N.length)+k2(N,$))};if(!g5(Z))throw Error("Invalid provider response");let X=v2.call(Z),z=h2.call(Z),G=f2.call(Z),B=new Headers;for(let[U,q]of v7.call(z))B.append(U,q);let Q={status:X,statusText:Q1(g2.call(Z),$),headers:B};if(X<200||X>299){for(let[q,K]of v7.call(z)){if(Q1(q,$?.toLowerCase())!==q){Q.headers.delete(q);continue}try{Q.headers.set(q,Q1(K,$))}catch{Q.headers.delete(q)}}Q.headers.delete("content-length");let U=await x2.call(Z);return new Response(q$(U,$),Q)}if(!G||J==="http")return Z;Q.headers.delete("content-length");let Y=ReadableStream.prototype.getReader.call(G),W=new TextDecoder("utf-8",{ignoreBOM:!0}),H=new TextEncoder,V="",j=!0;return new Response(new ReadableStream({async pull(U){try{for(;;){let q=await Y.read();V+=W.decode(q.value,{stream:!q.done});let K=!1;for(;;){let N=/\r?\n\r?\n/.exec(V);if(!N)break;let M=N.index+N[0].length;U.enqueue(H.encode(F(V.slice(0,M)))),V=V.slice(M),K=!0}if(q.done){if(V)U.enqueue(H.encode(F(V)));U.close();return}if(K)return}}catch(q){U.error(j$(q,$))}},async cancel(U){try{await Y.cancel(U)}catch(q){throw j$(q,$)}finally{Y.releaseLock()}}}),Q)}catch(X){throw j$(X,$)}}function JW(Z,$,J){let X=Z.get($.sessionId),z=new Set($.validPinnedAccountIds);if(X&&!$.excludeAccountIds.includes(X.accountId)&&x7(X,z,$.wireAccountIdByAccount[X.accountId])){if($.persist){let Y=$.quotaCheckedAtByAccount[X.accountId];J($.sessionId,{accountId:X.accountId,inputBytes:$.requestBytes,...X.wireIdentity!==void 0?{wireIdentity:X.wireIdentity}:{},...Y!==void 0?{quotaCheckedAt:Y}:{}})}return{accountId:X.accountId}}let G=new Map(Object.entries($.quotaCheckedAtByAccount)),B=m7(Z,G,$.sessionId),Q=$.select(B);if(!Q)return;if($.persist){let Y=$.wireAccountIdByAccount[Q.accountId];J($.sessionId,{accountId:Q.accountId,inputBytes:$.requestBytes,...Y!==void 0?{wireIdentity:Y}:{},...Q.quotaCheckedAt!==void 0?{quotaCheckedAt:Q.quotaCheckedAt}:{}})}return{accountId:Q.accountId}}import{statSync as m2}from"node:fs";var l7=30000,w2=8,u2=1800000;function d7(Z){return Z.identity?`identity:${Z.identity}`:`row:${Z.id}`}function QW(Z){try{let $=m2(Z);return`${$.ino}:${$.size}:${$.mtimeMs}`}catch{return"-"}}function WW(Z){let $=Z.credential;if($?.type!=="oauth")return;return{access:$.access??"",expires:$.expires,refresh:$.refresh}}function p2(Z,$){try{return w7(Z,$)}catch{return Z}}function YW(Z,$,J){let X=d7($);Z.set(X,[...Z.get(X)??[],{credentialEpoch:$.credentialEpoch,identity:$.identity,observation:J}].slice(-w2))}function HW(Z,$,J){let X=Z;for(let z of $.get(d7(Z))??[]){if(!(J-z.observation.checkedAt<=u2)||z.credentialEpoch!==Z.credentialEpoch||z.identity!==Z.identity)continue;X={...X,quota:p2(X.quota,z.observation)}}return X}function VW(Z,$,J,X){let z=w1(Z);if(typeof $?.status==="number"||u7($)){let B=p7({error:$,now:J,refreshToken:Z,...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+l7,tokenHash:z,retryCount:X?.tokenHash===z?X.retryCount:0}}function UW(Z,$,J,X){let z=new Map;for(let G of Z){if(X(G,J))continue;let B=$.get(G.id);z.set(G.id,B&&B.nextRetryAt>J?B.nextRetryAt:J+l7)}return z}import{readdir as d2,readFile as c2}from"node:fs/promises";import{homedir as s2}from"node:os";import{join as H1}from"node:path";var K$=Symbol.for("@cortexkit/openai-auth/runtime-layout-runs"),N$=globalThis,F$=globalThis,l2=N$[K$];N$[K$]??={};var Y1=N$[K$];Y1.legacyGeneration??=l2===void 0&&F$[Symbol.for("@cortexkit/openai-auth/runtime-layouts")]===void 0&&(F$[Symbol.for("@cortexkit/openai-auth/opencode-vaults")]!==void 0||F$[Symbol.for("__openaiAuthRpcServers")]!==void 0||("__openaiAuthRpcServers"in globalThis));Y1.runs??=new Map;Y1.logged??=new Set;var EZ=Object.assign(Y1,{runs:Y1.runs,logged:Y1.logged});function o(){return EZ.legacyGeneration===!0}function h5(){return process.env.XDG_STATE_HOME||H1(s2(),".local","state")}function a2(Z=h5()){return H1(Z,"cortexkit","openai-auth","processes")}function n2(Z=h5()){return H1(Z,"cortexkit","openai-auth","rpc")}function i2(Z){try{return process.kill(Z,0),!0}catch($){return $.code==="EPERM"}}function c7(Z){let $=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(Z.trim());if(!$)return;return{core:[Number($[1]),Number($[2]),Number($[3])],pre:$[4]?$[4].split("."):[]}}function s7(Z,$){let J=c7(Z),X=c7($);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 Q=/^\d+$/.test(G),Y=/^\d+$/.test(B);if(Q&&Y){let W=Number(G)-Number(B);if(W!==0)return Math.sign(W)}else if(Q!==Y)return Q?-1:1;else if(G!==B)return G<B?-1:1}return 0}async function D$(Z){try{return{ok:!0,names:await d2(Z)}}catch($){let J=$.code;if(J==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:J,error:`${Z}: ${String($)}`}}}async function a7(Z,$){let J;try{J=await c2(Z,"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===$&&typeof X.version==="string"){let z=X.layouts;return{kind:"ok",version:X.version,...z!==null&&typeof z==="object"&&!Array.isArray(z)?{layouts:z}:{}}}}catch{}return{kind:"unreadable"}}async function i7(Z){let $=Z.isAlive??i2,J=Z.selfPid??process.pid,X=new Map,z=(j)=>{let F=j.pid==="unknown"?`dir:${j.detail}`:j.pid;if(!X.has(F))X.set(F,j)};if(Z.layoutMove&&J===process.pid&&o())z({pid:J,version:"unknown",detail:"an older plugin generation ran in this process"});let G=(j)=>{try{return $(j)}catch{return!0}},B=(j,F)=>{let U=F.exec(j),q=U?Number(U[1]):Number.NaN;return Number.isSafeInteger(q)&&q>=1?q:void 0},Q=a2(Z.stateHome),Y=await D$(Q);if(!Y.ok)z({pid:"unknown",version:"unknown",detail:Y.error});for(let j of Y.ok?Y.names:[]){let F=B(j,/^(\d+)\.json$/);if(F===void 0||F===J)continue;let U=H1(Q,j),q=await a7(U,F);if(q.kind==="gone")continue;if(!G(F))continue;if(q.kind==="unreadable"){z({pid:F,version:"unknown",detail:U});continue}let K=s7(q.version,Z.currentVersion);if(K===void 0||K<0){z({pid:F,version:q.version,detail:U});continue}if(Z.layoutMove===!0&&(q.layouts===void 0||Object.values(q.layouts).includes("legacy")))z({pid:F,version:q.version,detail:U})}let W=Z.rpcDir??n2(Z.stateHome),H=await D$(W);if(!H.ok)z({pid:"unknown",version:"unknown",detail:H.error});for(let j of H.ok?H.names:[]){if(!n7(j))continue;let F=H1(W,j),U=await D$(F);if(!U.ok){if(U.code==="ENOTDIR")continue;z({pid:"unknown",version:"unknown",detail:U.error});continue}for(let q of U.names){let K=B(q,/^port-(\d+)\.json$/);if(K===void 0||K===J||!G(K))continue;let N=H1(F,q),M=await a7(N,K);if(M.kind==="gone")continue;let O=M.kind==="ok"?M.version:"unknown",_=s7(O,Z.currentVersion);if(_===void 0||_<0)z({pid:K,version:O,detail:N})}}let V=(j)=>j.pid==="unknown"?Number.POSITIVE_INFINITY:j.pid;return X.size===0?{open:!0}:{open:!1,blockers:[...X.values()].sort((j,F)=>V(j)-V(F))}}import{createHash as r2}from"node:crypto";import{existsSync as o2,realpathSync as M$}from"node:fs";import{homedir as e7}from"node:os";import{basename as t2,dirname as e2,join as zZ,resolve as T$}from"node:path";var _$="openai-auth-sessions.json",L$="openai-auth-sessions-opencode2.json",f5="layout.json",O$="config-dir.json";function x5(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return ZJ()}function ZJ(){return zZ(process.env.XDG_CONFIG_HOME||zZ(e7(),".config"),"opencode")}function m5(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||zZ(x5(),P$)}function V1(Z,$){let J=T$(Z);return $==="win32"||$==="darwin"?J.toLowerCase():J}function r7(Z){try{return M$.native(Z)}catch{try{return zZ(M$.native(e2(Z)),t2(Z))}catch{return}}}function w5(Z,$,J=process.platform){if(V1(Z,J)===V1($,J))return!0;let X=r7(Z),z=r7($);return X!==void 0&&z!==void 0&&V1(X,J)===V1(z,J)}function o7(Z){try{return M$.native(Z)}catch{return T$(Z)}}var t7=new Map;function u5(Z=x5()){let $=h5(),J=zZ(e7(),".config","opencode"),X=`${Z}\x00${J}\x00${$}`,z=t7.get(X);if(z&&l5(z))return z;let G=o7(Z);if(z&&z.key===G)return z;let B=G===o7(J),Q=zZ($,"cortexkit","openai-auth"),Y={key:G,configDir:Z,stateHomeDir:B?zZ(Q,"opencode"):zZ(Q,`opencode-${r2("sha256").update(G).digest("hex").slice(0,16)}`),isDefaultConfigDir:B};return t7.set(X,Y),Y}var Z0=Symbol.for("@cortexkit/openai-auth/runtime-layouts"),$0=globalThis,A$=$0[Z0]??new Map;$0[Z0]=A$;function J0(Z){return`${Z.stateHomeDir}\x00${Z.key}`}function p5(Z,$){A$.set(J0(Z),o()?"legacy":$)}function l5(Z){return A$.get(J0(Z))}function X0(Z=x5()){if(o())return Z;let $=u5(Z);return(l5($)??(o2(zZ($.stateHomeDir,f5))?"state-home":"legacy"))==="state-home"?$.stateHomeDir:Z}function tW(Z){return zZ(X0(),Z==="opencode1"?_$:L$)}function S$(Z){let $=zZ(x5(),P$);return Z===$||V1(Z,process.platform)===V1($,process.platform)}function z0(Z=m5()){let $=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if($)return $;return S$(Z)?void 0:C$(Z)}function G0(Z=m5()){return S$(Z)?void 0:Z}function $J(Z=m5()){let $=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if($){if(w5(Z,$))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${T$(Z)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return $}if(!S$(Z))return C$(Z);return zZ(X0(),u1)}function eW(Z=m5()){return{configPath:Z,statePath:$J(Z)}}import{createHash as YJ}from"node:crypto";import{readFileSync as HJ}from"node:fs";import{readFile as VJ}from"node:fs/promises";import{resolve as UJ}from"node:path";import{createHash as JJ}from"node:crypto";import{readFile as XJ}from"node:fs/promises";import{homedir as zJ}from"node:os";import{join as B0,resolve as GJ}from"node:path";var BJ="openai",Q0=250,l1="main-refresh";function R$(Z){if(typeof Z.access!=="string"||typeof Z.refresh!=="string")return;let $=Buffer.from(Z.access),J=Buffer.from(Z.refresh),X=(z)=>{let G=Buffer.alloc(4);return G.writeUInt32BE(z.length),G};return JJ("sha256").update(X($)).update($).update(X(J)).update(J).digest("hex")}function j0(Z){if(!Z||typeof Z!=="object")return;let $=Z;if($.type!=="oauth")return;return{type:"oauth",...typeof $.access==="string"?{access:$.access}:{},...typeof $.refresh==="string"?{refresh:$.refresh}:{},...typeof $.expires==="number"?{expires:$.expires}:{},...typeof $.accountId==="string"?{accountId:$.accountId}:{}}}function q0(Z){let $=j0(Z);if(typeof $?.access!=="string"||typeof $.refresh!=="string")return;return{access:$.access,refresh:$.refresh,...typeof $.expires==="number"?{expires:$.expires}:{}}}function W0(Z){if(nZ(Z)&&Z.type==="api"&&typeof Z.key==="string")return{kind:"api"};let $=j0(Z);if(!$)return{kind:"indeterminate"};return x1($)?{kind:"tombstone",oauth:$}:{kind:"real",oauth:$}}async function Y0(Z){return Z.auth.get({path:{id:BJ}})}async function H0(Z){return Object.keys(await Z.auth.all()).length>0}async function F0(Z){let $=await Y0(Z.client);if($!==void 0)return W0($);let J=await H0(Z.client),X=Z.now();if(await Z.sleep(Q0),Z.now()-X<Q0)return{kind:"indeterminate"};let z=await Y0(Z.client);if(z!==void 0)return W0(z);let G=await H0(Z.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function d5(Z=process.env,$=zJ()){let J=Z.XDG_DATA_HOME||B0($,".local","share");return B0(J,"opencode","auth.json")}function nZ(Z){return!!Z&&typeof Z==="object"&&!Array.isArray(Z)}var V0=(Z)=>Z===void 0||typeof Z==="string";function QJ(Z){if(!nZ(Z))return!1;switch(Z.type){case"oauth":return typeof Z.refresh==="string"&&typeof Z.access==="string"&&typeof Z.expires==="number"&&Number.isSafeInteger(Z.expires)&&Z.expires>=0&&V0(Z.accountId)&&V0(Z.enterpriseUrl);case"api":return typeof Z.key==="string"&&(Z.metadata===void 0||nZ(Z.metadata)&&Object.values(Z.metadata).every(($)=>typeof $==="string"));case"wellknown":return typeof Z.key==="string"&&typeof Z.token==="string";default:return!1}}async function I$(Z,$=process.env){let J=$.OPENCODE_AUTH_CONTENT;if(J)try{let z=JSON.parse(J);return nZ(z)?z:{}}catch{}let X;try{X=JSON.parse(await XJ(Z,"utf8"))}catch{return{}}if(!nZ(X))return{};return Object.fromEntries(Object.entries(X).filter(([,z])=>QJ(z)))}function U0(Z){if(!Z.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(Z.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class c5 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function WJ(Z){let $=Z.env??process.env,J=Z.path??d5($),X=new Map;return{path:GJ(J),migrationDisabledReason:()=>U0($)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(z){let G=(await I$(J,$))[z.path.id];return X.set(z.path.id,JSON.stringify(G)),G},async all(){return I$(J,$)},async set(z){if(U0($))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let G=(await I$(J,$))[z.path.id];if(p1(z.body)&&(!X.has(z.path.id)||X.get(z.path.id)!==JSON.stringify(G)))throw new c5;let B=await Z.set(z);if(nZ(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 QY(Z,$={}){let J=nZ(Z)?Z.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:WJ({...$,set:(z)=>X.call(J,z)})}}var U1="openai",jJ="common-auth-placeholder:v1:openai",d1=Object.freeze({type:"oauth",access:"",refresh:jJ,expires:0});function p1(Z){if(!GZ(Z))return!1;return Z.type===d1.type&&Z.access===d1.access&&Z.refresh===d1.refresh&&Z.expires===d1.expires}var s5="openaiAuthPool",qJ=120000,L0="pool-migration",FJ="slot-transfer-origin-unknown",KJ="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.",o5=Object.freeze({mainRefreshTtlMs:qJ,fallbackTtlMs:T0,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function a5(Z,$,J){return Z.kind==="placeholder"&&!$&&!J.pending}class iZ extends Error{constructor(Z){super(`timed out waiting for the legacy ${Z} lock`);this.name="LegacyLockContention"}}function GZ(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function NJ(Z){let $=Z.now??Date.now;return{paths:Z.paths,slot:Z.slot,now:$,sleep:Z.sleep??((J)=>new Promise((X)=>setTimeout(X,J))),newId:Z.newId??(()=>crypto.randomUUID()),log:Z.log??s("pool-migration"),...Z.vaultServes?{vaultServes:Z.vaultServes}:{},locks:{...o5,...Z.legacyLocks},leaseWait:Z.leaseWait??{timeoutMs:4000,pollMs:50},store:S1({provider:U1,configPath:Z.paths.configPath,statePath:Z.paths.statePath,quota:i5,now:$,...Z.store}),onStep:async(J)=>{await Z.onStep?.(J)}}}async function q1(Z){let $;try{$=await VJ(Z,"utf8")}catch(X){if(X.code==="ENOENT")return{};throw X}let J=JSON.parse($);if(!GZ(J))throw Error("config root is not an object");return J}async function c1(Z,$,J,X,z){let G=performance.now();for(;;){if(z?.aborted)throw new iZ($);let B=await QZ({name:$,path:J,ttlMs:X,renew:Z.locks.renew,...Z.locks.renewIntervalMs!==void 0?{renewIntervalMs:Z.locks.renewIntervalMs}:{}});if(B){if(!z?.aborted)return B;throw await B.release(),new iZ($)}if(performance.now()-G>=Z.locks.timeoutMs)throw new iZ($);await Z.sleep(Z.locks.retryMs)}}async function MY(Z,$,J={}){let X={...o5,...J},z=performance.now();for(;;){let G=await QZ({name:l1,path:Z,ttlMs:X.mainRefreshTtlMs,renew:X.renew,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}});if(G)try{return await $()}finally{await G.release().catch(()=>{})}if(performance.now()-z>=X.timeoutMs)throw new iZ(l1);await new Promise((B)=>setTimeout(B,X.retryMs))}}async function s1(Z,$){let J=Z.locks.saveTtlMs,X=await c1(Z,"save",Z.paths.configPath,J);try{let z=await c1(Z,"save",Z.paths.statePath,J);try{let G=await q1(Z.paths.configPath);if(!await $(G))return;await AZ(Z.paths.configPath,G,{beforeRename:async()=>{await X.assertOwned(),await z.assertOwned()}})}finally{await z.release().catch(()=>{})}}finally{await X.release().catch(()=>{})}}function DJ(Z){if(!GZ(Z))return;let{rowId:$,operation:J,rowFingerprint:X,slotFingerprint:z}=Z,{credentialFingerprint:G,carryLegacyMain:B,recordedAt:Q,identity:Y}=Z;if(typeof $!=="string"||!$)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:$,operation:J,rowFingerprint:X,slotFingerprint:z,credentialFingerprint:G,...typeof Y==="string"&&Y?{identity:Y}:{},carryLegacyMain:B===!0,recordedAt:typeof Q==="number"?Q:0}}function O0(Z,$){if(!GZ(Z)||!$)return!1;return qZ(Z).pending?.credentialFingerprint===YZ({type:"oauth",refresh:$})}function PY(Z,$){let J;try{J=JSON.parse(HJ(Z,"utf8"))}catch{return!1}return O0(J,$)}class MJ extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var PJ=600000;async function CY(Z,$,J={}){let X=J.now??Date.now,z=(Y)=>{let W=qZ(Y).pending;return W&&O0(Y,$)&&X()-W.recordedAt>=PJ?W:void 0},G=z(await q1(Z.configPath));if(!G)return!1;let B={...o5,...J.legacyLocks},Q=await QZ({name:L0,path:Z.configPath,ttlMs:B.mainRefreshTtlMs});if(!Q)return!1;try{let Y=await q1(Z.configPath),W=qZ(Y).migratedAt!==void 0,H=await S1({provider:U1,configPath:Z.configPath,statePath:Z.statePath,quota:i5,now:X}).read();if(W&&H.status!=="ready")return!1;let V;if(H.status==="ready"){let F=H.rows.find((q)=>q.id===G.rowId&&!q.invalid),U=F?.fingerprint??null;if(W&&F&&U===G.credentialFingerprint)return!1;if(F&&U!==G.credentialFingerprint&&U!==G.rowFingerprint)V=J.slotAccess!==void 0?R$({type:"oauth",access:J.slotAccess,refresh:$}):G.slotFingerprint}let j=!1;if(await s1({paths:Z,locks:B,sleep:(F)=>new Promise((U)=>setTimeout(U,F))},(F)=>{let U=qZ(F),q=z(F);if(!q||q.recordedAt!==G.recordedAt)return!1;let{pending:K,...N}=U;return t5(F,V!==void 0?{...N,declinedSlotFingerprint:V}:N),j=!0,!0}),j)(J.log??s("pool-migration")).warn(V!==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 j}finally{await Q.release().catch(()=>{})}}function qZ(Z){let $=Z[s5];if(!GZ($))return{};let J=DJ($.pending);return{...typeof $.migratedAt==="number"?{migratedAt:$.migratedAt}:{},...J?{pending:J}:{},...typeof $.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:$.declinedSlotFingerprint}:{}}}function t5(Z,$){let X={...GZ(Z[s5])?Z[s5]:{}};for(let z of["migratedAt","pending","declinedSlotFingerprint"])delete X[z];Object.assign(X,$),Z[s5]=X}function CJ(Z){let $=Z?T5(Z):void 0;return $?_5($):void 0}function TJ(Z){let $=R$({type:"oauth",...Z}),J=CJ(Z.access);return{kind:"real",credential:Z,fingerprint:$,credentialFingerprint:YZ({type:"oauth",refresh:Z.refresh}),...J?{identity:J}:{}}}function A0(Z){if(p1(Z))return{kind:"placeholder",...GZ(Z)&&typeof Z.accountId==="string"?{origin:Z.accountId}:{}};let $=q0(Z);if(!$?.refresh.trim())return{kind:"empty"};return TJ($)}async function a1(Z){let $=await F0({client:{auth:{get:(J)=>Z.slot.get(J),all:()=>Z.slot.all()}},now:Z.now,sleep:Z.sleep});if($.kind==="real")return A0($.oauth);return $.kind==="slot-absent"||$.kind==="indeterminate"?{kind:$.kind}:{kind:$.kind}}async function TY(Z,$){if(!p1($))return!1;let J=await q1(Z.configPath),X=await S1({provider:U1,configPath:Z.configPath,statePath:Z.statePath,quota:i5}).read();if(X.status==="error")return!1;let z=X.status==="ready"?X.rows.some((G)=>G.id==="main"):X.roster.some((G)=>GZ(G)&&G.id==="main");return a5({kind:"placeholder"},z,qZ(J))}async function _J(Z){let $=Z.now()+Z.leaseWait.timeoutMs;for(;;){let J=await a1(Z);if(J.kind!=="real")return J;if(!await S0(Z,J.credential.refresh))return J;if(Z.now()>=$)return{kind:"retry"};await Z.sleep(Z.leaseWait.pollMs)}}async function S0(Z,$){let J=await r5(Z.paths),X=J?.refresh?.mainRefreshLeaseUntil;return Boolean(X&&X>Z.now()&&J?.refresh?.mainRefreshLeaseTokenHash===w1($))}function LJ(Z){return Z.length>0&&Z.trim()===Z&&!["__proto__","constructor","prototype","main"].includes(Z)}function OJ(Z,$,J,X,z){let G=J.identity?{identity:J.identity}:{},B=$.find((H)=>!H.invalid&&H.fingerprint===J.credentialFingerprint);if(B)return{rowId:B.id,operation:"rotate",rowFingerprint:B.fingerprint??null,...G,carryLegacyMain:Z==="migrate"&&B.id==="main"};let Q=$.find((H)=>H.id==="main");if(!Q||!Q.invalid&&!Q.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...G,carryLegacyMain:Z==="migrate"};if(J.identity){let H=$.find((V)=>!V.invalid&&V.type==="oauth"&&V.enabled&&V.identity===J.identity);if(H)return{rowId:H.id,operation:"replace",rowFingerprint:H.fingerprint??null,...G,carryLegacyMain:Z==="migrate"&&H.id==="main"}}let Y=new Set($.map((H)=>H.id));return{rowId:X??(J.identity&&LJ(J.identity)&&!Y.has(J.identity)?J.identity:z()),operation:"add",rowFingerprint:null,...G,carryLegacyMain:!1}}function AJ(Z,$,J,X,z,G,B){let Q=$.pending;if(Q){let Y=J.find((V)=>V.id===Q.rowId&&!V.invalid),W=Y?.fingerprint??null,H=X.kind==="real"&&X.fingerprint===Q.slotFingerprint;if(Y&&W===Q.credentialFingerprint)return{kind:"finish",record:Q};if((Y||Q.rowFingerprint===null)&&W===Q.rowFingerprint)return H&&X.kind==="real"?{kind:"transfer",record:Q,credential:X.credential,fresh:!1}:{kind:"drop-record"};if(!Y)return{kind:"drop-record"};return H?{kind:"ambiguous",record:Q}:{kind:"drop-record"}}if(X.kind==="indeterminate")return{kind:"drop-record"};if(X.kind!=="real")return{kind:"nothing",slot:X.kind};if($.declinedSlotFingerprint===X.fingerprint)return{kind:"nothing",slot:"declined"};return{kind:"transfer",record:{...OJ(Z,J,X,z,B),slotFingerprint:X.fingerprint,credentialFingerprint:X.credentialFingerprint,recordedAt:G},credential:X.credential,fresh:!0}}async function SJ(Z,$,J){let X={type:"oauth",access:J.access,refresh:J.refresh,...J.expires!==void 0?{expires:J.expires}:{}},z=$.identity?{identity:$.identity}:{},G={extraLocks:n5(Z.paths,$.rowId,Z.locks)};if($.operation==="add")await Z.store.add({id:$.rowId,credential:X,...z},G);else if($.operation==="replace")await Z.store.replace($.rowId,X,z,G);else{let B=await Z.store.read(),Q=B.status==="ready"?B.rows.find((Y)=>Y.id===$.rowId):void 0;await Z.store.rotate($.rowId,X,Q?.identity===void 0?z:{},G)}}async function IJ(Z,$){let J=await Z.store.read();if(J.status!=="ready")return;let X=J.rows.find((z)=>z.id===$.rowId&&!z.invalid);return X?.fingerprint===$.credentialFingerprint?X:void 0}function RJ(Z,$){let J=[],X=[["primary",Z.primary],["secondary",Z.secondary]],z=0;for(let[Q,Y]of X){if(!Y||!Number.isFinite(Y.checkedAt)||!Number.isFinite(Y.usedPercent))continue;z=Math.max(z,Y.checkedAt),J.push({checkedAt:Y.checkedAt,readings:[{label:Q,usedPercent:Y.usedPercent,...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{},...Number.isFinite(Y.windowMinutes)?{windowMinutes:Y.windowMinutes}:{}}]})}let G=$??(z||void 0),B=Z.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&&Z.spendControlCleared)J.push({checkedAt:G,budget:{kind:"cleared"}});return J.sort((Q,Y)=>Q.checkedAt-Y.checkedAt)}async function EJ(Z,$){let J=await r5(Z.paths);if(!J)return;let X=J.quota?.mainQuotaToken,z=$.credential?.type==="oauth"?$.credential.access:void 0,B=!X||z!==void 0&&X===M0(z)?J.quota?.mainQuota:void 0;if(B&&$.credentialEpoch!==void 0){let H={credentialEpoch:$.credentialEpoch,...$.identity!==void 0?{identity:$.identity}:{}};for(let V of RJ(B,J.quota?.mainQuotaCheckedAt))try{await Z.store.recordQuota($.id,H,V)}catch(j){Z.log.warn("legacy main quota not carried to the pool row",{rowId:$.id,error:j instanceof Error?j.message:String(j)})}}let Q=J.refresh?.mainLastRefreshError,Y=J.accounts.find((H)=>H.id===$.id);if(!Y||!P0(Y)||Y.corrupt)return;if(!Q&&!B)return;let W={...J,accounts:[{...Y,...Y.lastRefreshError||!Q?{}:{lastRefreshError:Q},...Y.quota||!B?{}:{quota:B}}]};try{await C0(W,Z.paths,{accounts:[$.id]})}catch(H){Z.log.warn("legacy main backoff not carried to the pool row",{rowId:$.id,error:H instanceof Error?H.message:String(H)})}}async function j1(Z,$,J={}){await s1(Z,(X)=>{let z=qZ(X);if(delete X.mainAccountId,$==="migrate"&&z.migratedAt===void 0)bJ(X);return t5(X,{...z.migratedAt!==void 0||$==="migrate"?{migratedAt:z.migratedAt??Z.now()}:{},...J.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:J.declinedSlotFingerprint}:z.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:z.declinedSlotFingerprint}:{}}),!0})}function bJ(Z){let $=Z.routing;if($===void 0)Z.routing={mode:"main-first"};else if(GZ($)&&$.mode===void 0)Z.routing={...$,mode:"main-first"}}async function b$(Z){await s1(Z,($)=>{let J=qZ($);if(!J.pending)return!1;let{pending:X,...z}=J;return t5($,z),!0})}async function yJ(Z,$){await s1(Z,(J)=>{let X=qZ(J);if($.identity)J.mainAccountId=$.identity;return t5(J,{...X,pending:$}),!0})}async function kJ(Z,$,J,X){let z=await c1(Z,l1,Z.paths.configPath,Z.locks.mainRefreshTtlMs);try{return await vJ(Z,$,J,X)}finally{await z.release().catch(()=>{})}}async function vJ(Z,$,J,X){let z=(W)=>({status:"completed",rowId:J.rowId,operation:X,placeholder:W}),G=await a1(Z);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!==E$(Z))return{status:"foreign-placeholder"};return await j1(Z,$),await Z.onStep("after-record-clear"),z("already-present")}if(Object.keys(await Z.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 b$(Z),await Z.onStep("after-record-clear"),{status:"restart"};if(G.kind!=="real"||G.fingerprint!==J.slotFingerprint)return await j1(Z,$),await Z.onStep("after-record-clear"),z("slot-moved-on");await Z.onStep("before-placeholder-write");let B=await Z.slot.get({path:{id:U1}}),Q=B===void 0||B===null?void 0:A0(B);if(Q?.kind!=="real"||Q.fingerprint!==J.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await Z.slot.set({path:{id:U1},body:{...d1,accountId:E$(Z)}})}catch(W){if(W instanceof c5)return{status:"retry",reason:"slot-changed"};throw W}await Z.onStep("after-placeholder-write");let Y=await Z.slot.get({path:{id:U1}});if(!p1(Y))return{status:"retry",reason:"placeholder-overwritten"};if(GZ(Y)&&Y.accountId===void 0)return{status:"untagged-placeholder"};if(GZ(Y)&&Y.accountId!==E$(Z))return{status:"foreign-placeholder"};return await j1(Z,$),await Z.onStep("after-record-clear"),z("written")}async function gJ(Z,$,J){let{record:X}=J;if(J.fresh)await yJ(Z,X),await Z.onStep("after-record-write");if(await S0(Z,J.credential.refresh))return{status:"restart"};let z=await a1(Z);if(z.kind!=="real"||z.fingerprint!==X.slotFingerprint)return{status:"restart"};return await SJ(Z,X,J.credential),await Z.onStep("after-row-write"),I0(Z,$,X,J.fresh?X.operation:"resumed")}async function I0(Z,$,J,X){let z=await IJ(Z,J);if(!z)return{status:"retry",reason:"verify-failed"};if(await Z.onStep("after-verify"),J.carryLegacyMain)await EJ(Z,z),await Z.onStep("after-carry-over");let G=await kJ(Z,$,J,X);if(G.status==="untagged-placeholder"){await Z.store.disable(J.rowId,FJ,{extraLocks:n5(Z.paths,J.rowId,Z.locks),attribution:{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}}}),await j1(Z,$);let B=`${Z.paths.configPath}\x00${J.rowId}`;if(!D0.has(B))D0.add(B),Z.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${KJ}`,{rowId:J.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(G.status!=="foreign-placeholder")return G;return await Z.store.remove(J.rowId,{extraLocks:n5(Z.paths,J.rowId,Z.locks),protect:(B,Q)=>Q.row?.fingerprint!==J.credentialFingerprint?"the transfer row changed before rollback":void 0}),await b$(Z),await y$(Z),{status:"refused",reason:"placeholder-without-main"}}var K0=new Set,N0=new Set,D0=new Set;function E$(Z){return`openai-auth-pool:${YJ("sha256").update(UJ(Z.paths.configPath)).digest("hex")}`}async function hJ(Z){try{let $=await Z();return $.open?[]:$.blockers}catch($){return[{pid:"unknown",version:"unknown",detail:$ instanceof Error?$.message:String($)}]}}async function R0(Z,$,J){let X=NJ(Z),z=X.slot.migrationDisabledReason?.();if(z){let W=X.slot.path??d5();if(!N0.has(W))N0.add(W),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 q1(X.paths.configPath)}catch(W){return{status:"error",reason:W instanceof Error?W.message:String(W)}}let B=await E0(X,$,G);if(B){if(B.status==="already-migrated"&&"mainAccountId"in G)await y$(X);return B}if(J){let W=await hJ(J);if(W.length>0){let H=`${X.paths.configPath}\x00${W.map((V)=>`${V.pid}@${V.version}`).join(",")}`;if(!K0.has(H))K0.add(H),X.log.info("account pool migration deferred: an older openai-auth version is running",{blockers:W});return{status:"deferred",reason:"older-version-running",blockers:W}}}let Q,Y;try{Y=await c1(X,"pool-slot-transfer",X.slot.path??d5(),X.locks.mainRefreshTtlMs,Z.signal),Q=await c1(X,L0,X.paths.configPath,X.locks.mainRefreshTtlMs,Z.signal)}catch(W){if(await Y?.release().catch(()=>{}),W instanceof iZ)return{status:"retry",reason:"lock-contention"};throw W}try{return await fJ(X,$)}catch(W){if(W instanceof iZ)return{status:"retry",reason:"lock-contention"};if(W instanceof R)return{status:"retry",reason:W.kind==="lock-contention"?"lock-contention":`store-${W.kind}`};throw W}finally{await Q?.release().catch(()=>{}),await Y?.release().catch(()=>{})}}async function E0(Z,$,J){let X=qZ(J);if(X.pending)return;if($==="migrate"&&X.migratedAt!==void 0){let z=await Z.store.read();if(z.status==="ready"&&!z.rows.some((G)=>G.id==="main")&&!X.pending&&a5(await a1(Z),z.rows.some((G)=>G.id==="main"),X))return{status:"refused",reason:"placeholder-without-main"};return{status:"already-migrated"}}if($==="adopt"&&X.migratedAt===void 0)return{status:"not-migrated"};return}async function fJ(Z,$){let J;for(let X=0;X<4;X++){let z=await q1(Z.paths.configPath),G=await E0(Z,$,z);if(G){if(G.status==="already-migrated")await y$(Z);return G}let B=await Z.store.read(),Q=qZ(z);if(B.status==="pending-migration"){if(a5(await a1(Z),B.roster.some((V)=>GZ(V)&&V.id==="main"),Q))return{status:"refused",reason:"placeholder-without-main"};await Z.store.initialize(),await Z.onStep("after-pool-key-write"),B=await Z.store.read()}if(B.status!=="ready")return{status:"error",reason:B.status==="error"?`${B.file}: ${B.reason}`:"pool still pending migration"};let Y=await _J(Z);if(Y.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(Y.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(a5(Y,B.rows.some((V)=>V.id==="main"),Q))return{status:"refused",reason:"placeholder-without-main"};let W=AJ($,Q,B.rows,Y,J,Z.now(),Z.newId);if(W.kind==="nothing"){if($==="migrate")await j1(Z,$),await Z.onStep("after-marker-write");return{status:"nothing-to-import",slot:W.slot}}if(W.kind==="drop-record"){await b$(Z),await Z.onStep("after-record-clear");continue}if(W.kind==="ambiguous")return await j1(Z,$,{declinedSlotFingerprint:W.record.slotFingerprint}),await Z.onStep("after-record-clear"),Z.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:W.record.rowId}),{status:"ambiguous",rowId:W.record.rowId};if(W.kind==="transfer"&&W.fresh)J=W.record.rowId;let H=W.kind==="finish"?await I0(Z,$,W.record,"resumed"):await gJ(Z,$,W);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function y$(Z){await s1(Z,($)=>{if(!("mainAccountId"in $))return!1;if(qZ($).pending)return!1;return delete $.mainAccountId,!0})}function _Y(Z){return R0(Z,"migrate",Z.fence)}function LY(Z){return R0(Z,"adopt")}class b0 extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function n5(Z,$,J={}){let X={...o5,...J},z={renew:X.renew,timeoutMs:X.timeoutMs,retryMs:X.retryMs,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}};return[{name:l1,path:Z.configPath,ttlMs:X.mainRefreshTtlMs,...z},{name:_0($),path:Z.configPath,ttlMs:X.fallbackTtlMs,...z}]}async function OY(Z,$,J,X={}){let z=Z.now??Date.now,G=Z.sleep??((Y)=>new Promise((W)=>setTimeout(W,Y))),B=Z.leaseWait??{timeoutMs:4000,pollMs:50},Q=async(Y,W)=>{let H=w1(Y.refresh),V=async()=>{let j=await r5(Z.paths),F=j?.refresh?.mainRefreshLeaseUntil;return Boolean(F&&F>z()&&j?.refresh?.mainRefreshLeaseTokenHash===H)};if(await V()){let j=z()+B.timeoutMs;while(z()<j&&await V())await G(B.pollMs);throw new b0}return J(Y,W)};return Z.store.refresh($,Q,{...X,extraLocks:n5(Z.paths,$,Z.legacyLocks)})}function y0(){let Z=crypto.getRandomValues(new Uint8Array(16)),$=Date.now();Z[0]=$/1099511627776&255,Z[1]=$/4294967296&255,Z[2]=$/16777216&255,Z[3]=$/65536&255,Z[4]=$/256&255,Z[5]=$&255,Z[6]=(Z[6]??0)&15|112,Z[8]=(Z[8]??0)&63|128;let J=Array.from(Z,(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 xJ,mkdirSync as k0,readFileSync as mJ,renameSync as wJ,writeFileSync as uJ}from"node:fs";import{dirname as v0}from"node:path";var k$="sessions",pJ=1e4,lJ=5000,dJ=25;async function cJ(Z,$=lJ){let J=performance.now()+$;for(;;){let X=await QZ({name:k$,path:Z,ttlMs:pJ});if(X||performance.now()>=J)return X;await new Promise((z)=>setTimeout(z,dJ))}}function sJ(Z){let $=new Map,J=JSON.parse(mJ(Z,"utf8"));if(!k(J.sessions))return $;for(let[X,z]of Object.entries(J.sessions)){if(!k(z)||typeof z.threadID!=="string")continue;$.set(X,z.threadID)}return $}function kY(Z,$=y0){let J=new Map,X;try{X=sJ(Z)}catch{return J}for(let[z,G]of X)J.set(z,{threadID:G,turnID:$(),windowID:`${G}:0`});return J}function aJ(Z,$){let J=`${Z}.tmp-${process.pid}`;k0(v0(Z),{recursive:!0});let X={version:1,sessions:Object.fromEntries([...$].map(([z,G])=>[z,{threadID:G}]))};uJ(J,`${JSON.stringify(X,null,2)}
69
+ `,{encoding:"utf8",mode:384}),xJ(J,384),wJ(J,Z)}var e5=new Map;function vY(Z,$){let X=(e5.get(Z)??Promise.resolve()).then(async()=>{let z=null;try{if(k0(v0(Z),{recursive:!0}),z=await cJ(Z),!z)return;aJ(Z,[...$.entries()].map(([G,B])=>[G,B.threadID]))}catch{}finally{await z?.release().catch(()=>{})}});return e5.set(Z,X),X.then(()=>{if(e5.get(Z)===X)e5.delete(Z)}),X}import{randomUUID as nJ}from"node:crypto";import{chmod as iJ,mkdir as rJ,rename as oJ,rm as v$,writeFile as tJ}from"node:fs/promises";import{homedir as eJ}from"node:os";import{join as $9}from"node:path";function g$(){let Z=process.env.XDG_STATE_HOME||$9(eJ(),".local","state");return $9(Z,"cortexkit","openai-auth","processes")}function g0(Z=process.pid,$=g$()){return $9($,`${Z}.json`)}var Z9=0,J9,h0=Symbol.for("@cortexkit/openai-auth/process-layouts"),f0=globalThis,X9=f0[h0]??new Map;f0[h0]=X9;function x0(){return{...Object.fromEntries(X9),...o()?{"*":"legacy"}:{}}}function ZX(){if(o())return!0;for(let Z of X9.values())if(Z==="legacy")return!0;return!1}async function m0(Z,$){await rJ(Z,{recursive:!0,mode:448}),await iJ(Z,448);let J=g0($.pid,Z),X=$9(Z,`0${$.pid}.json`),z=o()?[X,J]:[J];if(!o())await v$(X,{force:!0}).catch(()=>{});for(let G of z){let B=`${G}.${nJ()}.tmp`;try{await tJ(B,`${JSON.stringify($)}
70
+ `,{mode:384}),await oJ(B,G)}catch(Q){throw await v$(B,{force:!0}).catch(()=>{}),Q}}return J}async function uY(Z){let $=Z.pid??process.pid,J=Z.dir??g$();J9??=(Z.now??Date.now)(),Z9++;let X;try{X=await m0(J,{pid:$,version:Z.version,startedAt:J9,layouts:x0()})}catch(G){Z.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,Z9=Math.max(0,Z9-1),Z9>0)return;if(ZX())return;await v$(g0($,J),{force:!0}).catch((G)=>{Z.logger.warn("process heartbeat not removed",{dir:J,error:G instanceof Error?G.message:String(G)})})}}}async function z9(Z){let $=o()?"legacy":Z.layout;if(X9.set(Z.key,$),$!=="legacy")return;J9??=(Z.now??Date.now)(),await m0(Z.dir??g$(),{pid:Z.pid??process.pid,version:Z.version,startedAt:J9,layouts:x0()})}import{createHash as $X}from"node:crypto";import{realpathSync as JX}from"node:fs";import{chmod as XX,mkdir as zX,readdir as n0,readFile as FZ,rmdir as i0,stat as r0,unlink as r1}from"node:fs/promises";import{basename as f$,dirname as Q9,isAbsolute as GX,join as h,relative as BX,resolve as W9}from"node:path";var QX="runtime-layout",F1="layout-moving.json",o0=1e4,G9=15000,WX=4*G9+o0,YX=50,HX=5,VX=50,UX=[0,10,20,40,80,100],w0=500,jX="openai-auth keeps its files in OpenCode's config folder until every running OpenCode using it has restarted on this version.",u0="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 t extends Error{stateDir;errorClass;constructor(Z,$,J=qX(Z,$)){super(J);this.stateDir=Z;this.errorClass=$;this.name="RuntimeLayoutRefusal"}}function qX(Z,$){if($==="ERR_PRIVATE_FILES_SECURITY")return`openai-auth cannot start: ${Z} is not a folder only your user can access, or it is a link, so the plugin will not use it (${$}). 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 p0(Z,$){return new t(Z,"foreign-folder",`openai-auth cannot start: ${Z} belongs to another OpenCode config folder, not ${$}. It was left untouched. Move it aside, then restart OpenCode.`)}function Y9(Z,$){return new t(Z,"credential-conflict",`openai-auth cannot start: runtime credentials conflict between ${$.old} and ${$.next}. Keep the newer one, delete the other, then restart OpenCode.`)}function JH(){let Z=EZ.notice;if(!Z||Z.shown)return;return Z.shown=!0,Z.text}function LZ(Z,$){if(EZ.logged.has(Z))return;EZ.logged.add(Z),$()}function bZ(Z){if(Z instanceof t)return Z.errorClass;let $=Z?.code;if(typeof $==="string"&&$)return $;return Z instanceof Error?Z.name:typeof Z}function FX(Z){let{path:$,stage:J}=Z??{};return{...typeof $==="string"&&$?{file:f$($)}:{},...typeof J==="string"&&J?{stage:J}:{}}}class i1 extends Error{code;constructor(Z,$){super($);this.code=Z;this.name="LayoutMoveError"}}class x$ extends i1{path;constructor(Z){super("old-credential-kept",`${Z} could not be removed`);this.path=Z}}function t0(Z,$,J,X){LZ(`${Z.key}\x00cleanup`,()=>$.warn("openai-auth could not finish removing its old files from OpenCode's config folder; it tries again at the next start",{configDir:Z.configDir,step:J,errorClass:bZ(X),...FX(X)}))}function XH(Z){let $=u5(),J=l5($);if(J)return Promise.resolve(J);let X=`${$.stateHomeDir}\x00${$.key}`,z=EZ.runs.get(X);if(!z)z=KX($,Z).catch((G)=>{if(G instanceof t)throw G;throw new t($.stateHomeDir,bZ(G))}).finally(()=>{EZ.runs.delete(X)}),EZ.runs.set(X,z);return z}async function KX(Z,$){let J=$.log??s("runtime-layout");if(o()){p5(Z,"legacy"),LZ("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 z9({key:Z.key,layout:"legacy",version:$.version})}catch(K){J.warn("process heartbeat not written",{errorClass:bZ(K)})}return"legacy"}let X=Z.stateHomeDir,z=h(X,f5),G=w$(Z),B=DX(),Q=B.length>0,Y=B.some((K)=>e0(K,X)),W=$.fence??NX($.version),H=async()=>{return await z9({key:Z.key,layout:"state-home",version:$.version}),p5(Z,"state-home"),"state-home"},V=await n1(z,X);if(await a0(Z,V),V?.oldFilesRemoved&&!Y){await kX(Z,G,B,V,J);let K=await BZ(h(X,F1)).catch(()=>!0),N=!Q&&(await z3(G).catch(()=>[!0])).length>0;if(!K&&!N)return H()}let j=await W3(Z.configDir,X),F;try{if(!j)await H3(X);F=await B9(QX,z,$.layoutLockWaitMs??WX)}catch(K){if(V=await n1(z,X),V&&!Y)return H();throw new t(X,bZ(K))}let U=F,q=async()=>{try{await U.assertOwned(),await z9({key:Z.key,layout:"legacy",version:$.version})}catch(K){throw new t(X,bZ(K))}return p5(Z,"legacy"),"legacy"};try{if(V=await n1(z,X),await a0(Z,V),!j)await vX(Z);if(Y)return LZ(`${Z.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 q();if(V){if(!Q&&!j)await PX(Z,G,z,V,U,{fence:W,log:J,steps:$.steps});else if(V.oldFilesRemoved)await CX(Z,U,$.steps,J);return await H()}if(Q)return await q();if(j)return LZ(`${Z.key}\x00aliased`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: its state folder is that same folder",{configDir:Z.configDir,stateDir:X})),await q();let K=await W();if(!K.open)return l0(Z,K.blockers,J),await q();let N=!1;try{let M=await MX(Z,G,z,U,{fence:W,log:J,steps:$.steps,onMarker:()=>{N=!0}});if(M.kind==="deferred")return l0(Z,M.blockers,J),await q();if(M.kind==="refused")return LZ(`${Z.key}\x00refused`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: it will not move them",{reason:M.reason,paths:M.paths,stateDir:X})),await q();if(M.moved)J.info("openai-auth moved its runtime files out of OpenCode's config folder",{from:Z.configDir,to:X});return await H()}catch(M){if(M instanceof t)throw M;if(N&&await n1(z,X))return await H();return LZ(`${Z.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:Z.configDir,errorClass:bZ(M)})),await q()}}finally{await U.release().catch(()=>{})}}function NX(Z){return()=>i7({currentVersion:Z,layoutMove:!0})}function l0(Z,$,J){LZ(`${Z.key}\x00deferred`,()=>J.info(jX,{configDir:Z.configDir,blockers:$}))}function DX(){let Z=z0();if(Z===void 0)return[];let $=G0();return[Z,O5(Z),...$?[$]:[]]}function e0(Z,$){let J=BX(d0($),d0(Z));if(J==="")return!0;if(!J.startsWith("..")&&!GX(J))return!0;return w5(Z,$)}function d0(Z){let $=W9(Z),J=[];for(;;){try{return h(JX.native($),...J)}catch{}let X=Q9($);if(X===$)return W9(Z);J.unshift(f$($)),$=X}}async function MX(Z,$,J,X,z){let G=Z.stateHomeDir,B=await $3(Z,$),Q=!1;try{let Y=await z.fence();if(!Y.open)return{kind:"deferred",blockers:Y.blockers};let W=await Q3(Z,$);if(W.length>0)return{kind:"refused",reason:"same-physical-file",paths:W};let H=await gX(G),V=(await IX($)).filter((K)=>!H.has(K));if(V.length>0)return{kind:"refused",reason:"destination-in-use",paths:V};let j=await B3($);await X.assertOwned(),await hX(G,[...new Set([...H,...j.map((K)=>K.next)])]);let F=new Set(j.map((K)=>K.next));for(let K of H){if(F.has(K))continue;await X.assertOwned(),await r1(K).catch((N)=>{if(N.code!=="ENOENT")throw N})}for(let K of j)await X.assertOwned(),await RX(K);await z.steps?.afterCopy?.(),await X.assertOwned();for(let K of B)await K.assertOwned();let U=await LX($,j),q={version:1,oldDir:Z.key,...U?{keptVaultState:U}:{}};z.onMarker(),await h$(J,q),await z.steps?.afterMarker?.(),await X.assertOwned();try{await Y3(Z,j,X,{log:z.log,keptVaultState:U,steps:z.steps}),await G3($,X,B,z.steps)}catch(K){if(!(K instanceof x$))throw K;return t0(Z,z.log,"remove-old-copies",K),{kind:"moved",moved:j.length>0}}return Q=!0,await X.assertOwned(),await h$(J,{...q,oldFilesRemoved:!0}),await m$(G,X,z.steps),{kind:"moved",moved:j.length>0}}finally{for(let Y of B.reverse())await Y.release().catch(()=>{});if(Q)await Z3($,X,z.steps)}}async function PX(Z,$,J,X,z,G){let B=[],Q=!1,Y="fence";try{if(!(await G.fence()).open)return;if(Y="data-locks",B=await $3(Z,$),Y="fence",!(await G.fence()).open)return;Y="same-file-check";let W=await Q3(Z,$);if(W.length>0){LZ(`${Z.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:W}));return}if(Y="remove-old-copies",await z.assertOwned(),!X.oldFilesRemoved)await Y3(Z,await B3($),z,{log:G.log,keptVaultState:X.keptVaultState,steps:G.steps});Y="remove-old-temps",await G3($,z,B,G.steps),Q=!0,Y="marker",await z.assertOwned(),await h$(J,{...X,oldFilesRemoved:!0}),Y="manifest",await m$(Z.stateHomeDir,z,G.steps)}catch(W){if(W instanceof t)throw W;t0(Z,G.log,Y,W)}finally{for(let W of B.reverse())await W.release().catch(()=>{});if(Q)await Z3($,z,G.steps)}}async function CX(Z,$,J,X){try{await m$(Z.stateHomeDir,$,J)}catch(z){LZ(`${Z.key}\x00manifest`,()=>X.warn(`openai-auth could not remove ${F1} from its state folder; it tries again at the next start`,{stateDir:Z.stateHomeDir,errorClass:bZ(z)}))}}async function m$(Z,$,J){let X=h(Z,F1);if(!await BZ(X))return;await J?.beforeRemove?.(X),await $.assertOwned(),await fX(Z)}async function Z3(Z,$,J){try{await J?.beforeRemove?.(Z.vault.old),await $.assertOwned(),await i0(Z.vault.old)}catch{}}async function $3(Z,$){let J=[];try{if(await BZ(Z.configDir)){if(J.push(await B9("save",$.state.old,G9)),await BZ($.vault.old))J.push(await B9("claustrum-roster-write",lZ($.vault.old,"opencode").rosterPath,G9));for(let X of $.sessions)J.push(await B9(k$,X.old,G9))}return J}catch(X){for(let z of J.reverse())await z.release().catch(()=>{});throw X}}function w$(Z){let $=h(Z.configDir,u1),J=h(Z.stateHomeDir,u1);return{state:{old:$,next:J},vault:{old:O5($),next:O5(J)},sessions:[_$,L$].map((X)=>({old:h(Z.configDir,X),next:h(Z.stateHomeDir,X)}))}}var TX=/^[0-9a-f]{64}$/;function J3(Z){return $X("sha256").update(Z).digest("hex")}function H9(Z){return{old:lZ(Z.vault.old,"opencode").statePath,next:lZ(Z.vault.next,"opencode").statePath}}var c0=d9("opencode"),_X="opencode-enrollment-no-token.json";async function X3(Z){try{let $=await L5(Z,c0);return $.state==="blocked"&&$.code==="missing_token"&&$.proposedName===c0}catch{return!1}}async function LX(Z,$){let J=H9(Z);if(!$.some((z)=>z.old===J.old))return;return await X3({statePath:J.next,tokenPath:h(Z.vault.next,_X)})?J3(await FZ(J.next)):void 0}async function OX(Z,$){if(!$)return!1;try{return J3(await FZ(Z))===$}catch{return!1}}async function u$(Z,$){if(!$)return!1;let J=lZ(Z.vault.old,"opencode");if(await OX(J.statePath,$))return!0;return X3(J)}async function zH(Z){let $=u5(),J=w$($);if(W9(Z)!==W9(J.vault.next))return;let X=$.stateHomeDir,z=await n1(h(X,f5),X);if(!z?.keptVaultState||z.oldDir!==$.key)return;let G=H9(J).old;if(!await u$(J,z.keptVaultState))return;await r1(G).catch((B)=>{if(B.code!=="ENOENT")throw B}),await i0(J.vault.old).catch(()=>{})}function AX(Z){return Z.includes(".lock")||Z.includes(".tmp")}var SX=/^[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 z3(Z){let $=lZ(Z.vault.old,"opencode"),J=[Z.state.old,...Z.sessions.map((z)=>z.old),$.rosterPath,$.statePath,$.tokenPath],X=[];for(let z of new Set(J.map(Q9))){let G;try{G=await n0(z,{withFileTypes:!0})}catch(Q){if(Q.code==="ENOENT")continue;throw Q}let B=J.filter((Q)=>Q9(Q)===z).map((Q)=>`${f$(Q)}.`);for(let Q of G)if(Q.isFile()&&B.some((Y)=>Q.name.startsWith(Y)&&SX.test(Q.name.slice(Y.length))))X.push(h(z,Q.name))}return X}async function G3(Z,$,J,X){for(let z of await z3(Z)){await X?.beforeRemove?.(z),await $.assertOwned();for(let G of J)await G.assertOwned();await r1(z).catch((G)=>{if(G.code!=="ENOENT")throw G})}}async function V9(Z){let $;try{$=await n0(Z,{withFileTypes:!0})}catch(J){let X=J.code;if(X==="ENOENT"||X==="ENOTDIR")return[];throw J}return $.filter((J)=>J.isFile()&&!AX(J.name)).map((J)=>J.name).sort()}async function B3(Z){let $=[];if(await BZ(Z.state.old))$.push(Z.state);for(let J of await V9(Z.vault.old))$.push({old:h(Z.vault.old,J),next:h(Z.vault.next,J)});for(let J of Z.sessions)if(await BZ(J.old))$.push(J);return $}async function IX(Z){let $=[];if(await BZ(Z.state.next))$.push(Z.state.next);for(let J of await V9(Z.vault.next))$.push(h(Z.vault.next,J));for(let J of Z.sessions)if(await BZ(J.next))$.push(J.next);return $}async function Q3(Z,$){let J=[[Z.configDir,Z.stateHomeDir],[$.vault.old,$.vault.next],[$.state.old,$.state.next],...$.sessions.map((z)=>[z.old,z.next])];for(let z of await V9($.vault.old))J.push([h($.vault.old,z),h($.vault.next,z)]);let X=[];for(let[z,G]of J)if(await W3(z,G))X.push(z);return X}async function W3(Z,$){let J=async(z)=>{try{let G=await r0(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(Z);return X!==void 0&&X===await J($)}async function RX(Z){let $=await FZ(Z.old),J=$.toString("utf8");if(!Buffer.from(J,"utf8").equals($))throw new i1("not-utf8",`${Z.old} is not UTF-8 text`);if(await U9(Z.next,J),!(await FZ(Z.next)).equals($))throw new i1("copy-mismatch",`${Z.next} does not match ${Z.old}`)}async function Y3(Z,$,J,X){let z=[],G=[],B=w$(Z),Q=H9(B).old,Y=[...$.filter((H)=>H.old!==Q),...$.filter((H)=>H.old===Q)];for(let H of Y){if(await J.assertOwned(),H.old===Q){if(await u$(B,X.keptVaultState))continue;if(G.length>0)continue;if(X.keptVaultState&&await EX(H.old,H.next))continue}let V=H.old===B.state.old||e0(H.old,B.vault.old);if(!await yX(H,Z.stateHomeDir,V,()=>bX(H.old,J,X.steps)))(V?G:z).push(H.old)}if(z.length>0)X.log.warn("openai-auth left old files in OpenCode's config folder; it no longer reads them",{configDir:Z.configDir,kept:z});let[W]=G;if(W!==void 0)throw new x$(W)}async function EX(Z,$){try{return(await FZ(Z)).equals(await FZ($))}catch{return!1}}async function bX(Z,$,J){await J?.beforeRemove?.(Z),await $.assertOwned()}function s0(Z){let $=Z?.code;return process.platform==="win32"&&($==="EBUSY"||$==="EPERM"||$==="EACCES")}async function yX(Z,$,J,X){let z=performance.now();for(let G of UX){if(G>0)await new Promise((Q)=>setTimeout(Q,G));let B;try{B=(await FZ(Z.old)).equals(await FZ(Z.next))}catch(Q){if(Q.code==="ENOENT"&&!await BZ(Z.old))return!0;if(s0(Q)){if(performance.now()-z>=w0)return!1;continue}if(J)throw Y9($,Z);return!1}if(!B){if(J)throw Y9($,Z);return!1}await X();try{return await r1(Z.old),!0}catch(Q){if(Q.code==="ENOENT")return!0;if(!s0(Q)||performance.now()-z>=w0)return!1}}return!1}async function kX(Z,$,J,X,z){let G=(Q)=>J.some((Y)=>w5(Y,Q));if(!G($.state.old)&&await BZ($.state.old))throw Y9(Z.stateHomeDir,$.state);if(!G($.vault.old)){let Q=H9($).old;for(let Y of await V9($.vault.old)){let W=h($.vault.old,Y);if(W===Q&&await u$($,X.keptVaultState))continue;if(!G(W))throw Y9(Z.stateHomeDir,{old:W,next:h($.vault.next,Y)})}}let B=[];try{for(let Q of $.sessions)if(await BZ(Q.old))B.push(Q.old)}catch{}if(B.length===0)return;LZ(`${Z.key}\x00reappeared`,()=>{EZ.notice={text:`${u0} Old folder: ${Z.configDir}`,shown:!1},z.warn(u0,{configDir:Z.configDir,stateDir:Z.stateHomeDir,found:B})})}async function n1(Z,$){let J,X;for(let z=0;z<HX;z++){if(z>0)await new Promise((G)=>setTimeout(G,VX));try{J=await FZ(Z,"utf8");break}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;X=G}}if(J===void 0)throw new t($,bZ(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"&&TX.test(z.keptVaultState)?{keptVaultState:z.keptVaultState}:{}}}catch{}throw new t($,"malformed-marker",`openai-auth cannot start: ${Z} is malformed. The old files are still in OpenCode's config folder. Delete layout.json, then restart OpenCode.`)}async function a0(Z,$){let J=Z.stateHomeDir;if($?.oldDir!==void 0&&$.oldDir!==Z.key)throw p0(J,Z.key);let X;try{X=await FZ(h(J,O$),"utf8")}catch(G){let B=G.code;if(B==="ENOENT"||B==="ENOTDIR")return;throw new t(J,bZ(G))}let z;try{z=JSON.parse(X)?.configDir}catch{}if(z!==Z.key)throw p0(J,Z.key)}async function vX(Z){let $=h(Z.stateHomeDir,O$);if(await BZ($))return;await U9($,`${JSON.stringify({version:1,configDir:Z.key},null,2)}
71
+ `)}async function gX(Z){let $;try{$=await FZ(h(Z,F1),"utf8")}catch(J){if(J.code==="ENOENT")return new Set;throw J}try{let J=JSON.parse($);if(Array.isArray(J?.files))return new Set(J.files.filter((X)=>typeof X==="string"))}catch{}return new Set}async function hX(Z,$){await U9(h(Z,F1),`${JSON.stringify({version:1,files:$},null,2)}
72
+ `)}async function fX(Z){await r1(h(Z,F1)).catch(($)=>{if($.code!=="ENOENT")throw $})}async function h$(Z,$){await U9(Z,`${JSON.stringify($,null,2)}
73
+ `)}async function U9(Z,$){await H3(Q9(Z)),await AZ(Z,null,{serialize:()=>$,durable:!0,durability:"file-only-on-windows"})}async function H3(Z){if(process.platform==="win32")return;await zX(Z,{recursive:!0,mode:448}),await XX(Z,448)}async function B9(Z,$,J){let X=performance.now();for(;;){let z=null;try{z=await QZ({name:Z,path:$,ttlMs:o0,renew:!0})}catch(G){if(G.code!=="ENOENT")throw G}if(z)return z;if(performance.now()-X>=J)throw new i1("lock-timeout",`${Z} lock at ${$}`);await new Promise((G)=>setTimeout(G,YX))}}async function BZ(Z){try{return await r0(Z),!0}catch($){let J=$.code;if(J==="ENOENT"||J==="ENOTDIR")return!1;throw $}}
74
+ export{S1 as ja,u as ka,M8 as la,k as ma,P6 as na,d9 as oa,O5 as pa,lZ as qa,EB as ra,S8 as sa,bB as ta,yB as ua,R8 as va,A5 as wa,_6 as xa,c9 as ya,r9 as za,t9 as Aa,sZ as Ba,e9 as Ca,B1 as Da,y1 as Ea,e8 as Fa,X2 as Ga,z2 as Ha,aZ as Ia,G2 as Ja,h1 as Ka,W2 as La,fQ as Ma,xQ as Na,mQ as Oa,wQ as Pa,uQ as Qa,pQ as Ra,JW as Sa,d7 as Ta,QW as Ua,WW as Va,p2 as Wa,YW as Xa,HW as Ya,VW as Za,UW as _a,iQ as $a,Q1 as ab,j$ as bb,k2 as cb,eQ as db,i7 as eb,tW as fb,$J as gb,eW as hb,jJ as ib,d1 as jb,FJ as kb,KJ as lb,MY as mb,PY as nb,MJ as ob,CY as pb,qZ as qb,TY as rb,_Y as sb,LY as tb,n5 as ub,OY as vb,l1 as wb,W0 as xb,d5 as yb,U0 as zb,c5 as Ab,QY as Bb,y0 as Cb,lJ as Db,cJ as Eb,sJ as Fb,kY as Gb,aJ as Hb,vY as Ib,uY as Jb,JH as Kb,XH as Lb,zH as Mb};