@cortexkit/opencode-openai-auth 1.20.3 → 1.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-D0oxrTkl.d.ts → codex-request-WGAY0gn4.d.ts} +9 -10
  3. package/dist/index-0cht4a77.js +64 -0
  4. package/dist/{index-eb631m0m.js → index-0cpz8t4q.js} +2 -2
  5. package/dist/{index-gxa94644.js → index-0hk39zee.js} +2 -2
  6. package/dist/{index-8ap9gr0h.js → index-7v9tyyrn.js} +2 -2
  7. package/dist/{index-66eejhpe.js → index-dmdmb1pp.js} +1 -1
  8. package/dist/{index-tn1ve0gx.js → index-ecqb42ev.js} +2 -2
  9. package/dist/{index-6a1t612m.js → index-fgt2dy20.js} +1 -1
  10. package/dist/{index-t66h86ed.js → index-hxp3dm9e.js} +2 -2
  11. package/dist/{index-t15pb3n2.js → index-j28pt8dy.js} +1 -1
  12. package/dist/{index-kakqxnt5.js → index-jq1efs0q.js} +11 -11
  13. package/dist/{index-ahbghz6c.js → index-r891a915.js} +2 -2
  14. package/dist/index-s1tk4br4.js +75 -0
  15. package/dist/{index-qtaqp1bf.js → index-vqy1mwn3.js} +1 -1
  16. package/dist/{index-dsytdx0r.js → index-wwp78jx3.js} +1 -1
  17. package/dist/index.d.ts +1 -2
  18. package/dist/index.js +1 -1
  19. package/dist/openai-auth.schema.json +22 -0
  20. package/dist/rpc/port-file.js +1 -1
  21. package/dist/rpc/protocol.js +1 -1
  22. package/dist/rpc/rpc-client.js +1 -1
  23. package/dist/rpc/rpc-dir.js +1 -1
  24. package/dist/sidebar-state.js +1 -1
  25. package/dist/{token-y8xp4cbz.js → token-8afntt1a.js} +1 -1
  26. package/dist/token-util-htrre2k8.js +1 -0
  27. package/dist/tui-preferences.js +1 -1
  28. package/dist/v2/server.d.ts +1 -1
  29. package/dist/v2/server.js +3 -3
  30. package/package.json +4 -4
  31. package/src/tui-compiled/raw/shared/29d709188b920a92-client-options.js +18 -0
  32. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +2 -1
  33. package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +4 -5
  34. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +3 -2
  35. package/src/tui-compiled/runtime/shared/29d709188b920a92-client-options.js +18 -0
  36. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +2 -1
  37. package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +4 -5
  38. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +3 -2
  39. package/dist/index-a7eep73q.js +0 -64
  40. package/dist/index-vjb3rsqh.js +0 -75
  41. package/dist/token-util-qgycqbjw.js +0 -1
@@ -0,0 +1,75 @@
1
+ import{$d as c3,Ae as T7,Bf as A1,Ee as g4,Fe as f4,Gf as L7,Hd as e0,Id as B8,If as O7,Jd as j6,Jf as _7,Kd as B5,Lf as c8,Md as d4,Mf as s8,Nd as I0,Od as $7,Of as k4,Pd as b0,Pf as g7,Rd as Y5,Re as b1,Rf as Z7,Sd as W5,Td as V5,Ue as L1,Vd as G8,Ve as P7,Wd as Q8,We as u8,Xd as o6,Yd as v0,Zd as w3,Zf as f7,_d as u3,ae as o5,be as t5,de as c4,ee as E9,fe as u2,hf as y$,ie as e5,jf as p8,ke as $Z,kf as a4,le as ZZ,me as x4,mf as l8,ne as JZ,nf as I1,pe as XZ,pf as E1,qe as zZ,qf as p0,re as y4,se as o7,sf as F6,te as GZ,ue as QZ,vf as d8,we as Y8,wf as K7,xe as g1,ye as W8,ze as C7}from"./index-jq1efs0q.js";import{dg as W3,eg as P0,fg as V3,gg as w6,hg as d0,jg as H3,kg as U3}from"./index-hxp3dm9e.js";import{yg as K8}from"./index-0hk39zee.js";import{zg as QJ}from"./index-7v9tyyrn.js";import{Gg as l7,Ig as M$,Jg as f1,Kg as C$,Lg as x0}from"./index-dmdmb1pp.js";import{Og as o3,Tg as t}from"./index-0cpz8t4q.js";import{$g as Y3,Ug as Z4,Wg as p6}from"./index-ecqb42ev.js";class b extends Error{operation;rowId;phase;retryable;kind;committed;constructor($){super($.message??`${$.operation} failed (${$.kind}, ${$.phase})`,$.cause===void 0?void 0:{cause:$.cause});this.name="PoolOperationError",this.operation=$.operation,this.rowId=$.rowId,this.phase=$.phase,this.retryable=$.retryable,this.kind=$.kind,this.committed=$.committed}}class Z1 extends Error{operation;constructor($){super(`${$} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=$}}var S2="identity-contradicted: ",I6="duplicate-identity";function i0($,Z,J){let X=$.rosterRow(Z);if(!X)return;X.enabled=!1;let z=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");$.setEntry(Z,{...z,disabledReason:G?z.disabledReason:J})}function J1($,Z){let J=$.rosterRow(Z);if(!J)return;J.enabled=!0;let X=$.entry(Z);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,$.setEntry(Z,z)}}function A2($,Z){let J=$.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===Z),X=[];for(let z of J.slice(1))i0($,z.id,"duplicate-identity"),X.push(z.id);return X}function Q2($,Z,J){let X=$.rosterRow(Z);if(!X)return[];return X.accountId=J,A2($,J)}import{AsyncLocalStorage as s$}from"node:async_hooks";var a1=new s$,n$=new s$;function n($){if(a1.getStore()!==void 0)throw new Z1($)}function a$(){if(a1.getStore()?.storeLocksReleased===!1||n$.getStore())throw new Z1("updateLimitsNamespace")}function G0($){return n$.run(!0,$)}function Q0($,Z,J=!1){return a1.run({operation:$,storeLocksReleased:J&&a1.getStore()?.storeLocksReleased!==!1},async()=>await Z())}async function i$($,Z,J,X,z){if(!Z)return;try{await Q0($,()=>Z(J,X),!0)}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:J,error:G instanceof Error?G.message:String(G)})}}import{setTimeout as q3}from"node:timers/promises";function B2($,Z,J){if(J!==void 0)throw new b({operation:$,rowId:Z,kind:"row-staged",phase:$==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${Z} is reserved for roster publication`})}import{createHash as X1}from"node:crypto";var v="commonAuthPool",r0=1,N0="rows",i1="retiredEpochs",z1=1,b6=300000,g=v;function mJ($){let Z=JSON.parse(JSON.stringify($)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(S(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J(Z)}function Y2($){return X1("sha256").update(mJ($)).digest("hex")}function r$($){if(!S($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function wJ($){if(!S($)||typeof $.reservation!=="string"||!$.reservation||typeof $.disabledReason!=="string")return;if(Object.keys($).some((Z)=>!["reservation","label","disabledReason","providerState"].includes(Z)))return;if("label"in $&&typeof $.label!=="string")return;if("providerState"in $&&(typeof $.providerState!=="string"||!/^[a-f0-9]{64}$/.test($.providerState)))return;return $}var r="commonAuthProviderState";function S($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var uJ=new Set(["__proto__","constructor","prototype"]);function E2($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(uJ.has($))return"id is a reserved object key";return}function k6($){let Z=typeof $==="string"?$.trim():"";if(!Z)return!1;try{let J=new URL(Z);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function o$($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function D0($){return X1("sha256").update(o$($)).digest("hex")}function E0($){return X1("sha256").update(`credential-stamp\x00${o$($)}`).digest("hex")}function f0($){let Z=$.type==="oauth"?["oauth",typeof $.access==="string"?$.access:null,$.refresh,typeof $.expires==="number"&&Number.isFinite($.expires)?$.expires:null]:["api",$.apiKey,$.baseURL.trim(),$.authHeader??"authorization-bearer"];return X1("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function x6($,Z,J,X={}){return{credentialEpoch:Z,digest:E0($),dispatch:f0($),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function R2($,Z){let J=$?.credentialBound?G0(()=>$.credentialBound?.(Z)):Z;return X1("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function G1($,Z,J,X){if(!Z||J===void 0)return;if(!S($)||!Object.hasOwn($,r))return;let z=e($[g]);if(!z||z.providerState===void 0||z.digest!==E0(Z)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function s($){return Number.isSafeInteger($)&&$>=1}function e($){if(!S($))return;let Z=$.credentialEpoch;if(!s(Z))return;if(typeof $.digest!=="string")return;if("dispatch"in $&&typeof $.dispatch!=="string")return;if("replace"in $&&$.replace!==!0)return;if("providerState"in $&&typeof $.providerState!=="string")return;let J="staged"in $?wJ($.staged):void 0;if("staged"in $&&!J)return;let X={...J?{staged:J}:{},...typeof $.dispatch==="string"?{dispatch:$.dispatch}:{},...$.replace===!0?{replace:!0}:{},...typeof $.providerState==="string"?{providerState:$.providerState}:{}};if(!("binding"in $))return"dispatch"in $||"replace"in $||"providerState"in $||"staged"in $?void 0:{credentialEpoch:Z,digest:$.digest};let z=$.binding;if(!S(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!k6(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...X,binding:{...typeof z.identity==="string"?{identity:z.identity}:{},...typeof z.baseURL==="string"?{baseURL:z.baseURL.trim()}:{},...z.authHeader==="authorization-bearer"||z.authHeader==="x-api-key"?{authHeader:z.authHeader}:{}}}}function pJ($,Z,J){if($.identity!==J)return!1;if($.baseURL!==void 0&&(Z.type!=="api"||Z.baseURL!==$.baseURL))return!1;if($.authHeader!==void 0&&(Z.type!=="api"||Z.authHeader!==$.authHeader))return!1;return!0}function lJ($,Z,J,X){if(!$)return"none";if(!S(X)||!Object.hasOwn(X,g))return"missing";let z=e(X[g]);if(!z)return"malformed";if(z.digest!==E0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!pJ(z.binding,$,J))return"mismatched";if(z.dispatch!==f0($))return"mismatched";return"bound"}function y6($){if(!$.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in $)return{status:"error",reason:"config file is not valid JSON"};let Z=$.value;if(!S(Z))return{status:"error",reason:"config root is not an object"};if("accounts"in Z&&!Array.isArray(Z.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(v in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let J=Z[v];if(!S(J))return{status:"error",reason:`${v} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${v}.schemaVersion is invalid`};if(X>r0)return{status:"error",reason:`${v}.schemaVersion ${X} is newer than ${r0}`};if(N0 in J&&!S(J[N0]))return{status:"error",reason:`${v}.${N0} is not an object`};return{status:"ready",exists:!0,config:Z}}function t$($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!S($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!S($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function I2($){return Array.isArray($.accounts)?$.accounts:[]}function e$($){let Z=$[v];if(!S(Z))return{};let J=Z[N0];return S(J)?J:{}}function dJ($){return S($.accounts)?$.accounts:{}}function cJ($){if(!S($))return"not an object";let Z=E2($.id);if(Z)return Z;if($.type==="api")return k6($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function sJ($,Z){if(!S($))return;let J=$.credentialEpoch;if(!s(J))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let X="quota"in $&&Z.decode?G0(()=>Z.decode?.($.quota)):$.quota;if("quota"in $&&!G0(()=>Z.validate(X)))return;if("staged"in $&&!r$($.staged))return;return{credentialEpoch:J,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:X}:{}}}function nJ($,Z){if(!S(Z))return;if($.type==="api"){let X=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if($.corrupt===!0)return;let J=Z.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.lastRefreshedAt==="number"?{lastRefreshedAt:Z.lastRefreshedAt}:{}}}function r1($,Z){return I2($).find((J)=>S(J)&&J.id===Z)}function $3($){if(!S($[v]))$[v]={};return $[v]}function g6($){let Z=$3($);if(!S(Z[N0]))Z[N0]={};return Z[N0]}function R0($,Z){let J=e$($),X=Object.hasOwn(J,Z)?J[Z]:void 0;return S(X)?X:void 0}function o1($,Z,J){Object.defineProperty(g6($),Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function Z3($,Z){let J=$[v];if(!S(J))return;let X=J[i1];if(!S(X)||!Object.hasOwn(X,Z))return;let z=X[Z];return s(z)?z:void 0}function J3($,Z){let J=R0($,Z)?.credentialEpoch;return s(J)?J:void 0}function t1($,Z){return Math.max(Z3($,Z)??0,J3($,Z)??0)+1}function X3($,Z){let J=[...Z];if(J.length===0)return;let X=$3($),z=S(X[i1])?X[i1]:{},G={},Q=(Y,B)=>Object.defineProperty(G,Y,{value:B,enumerable:!0,writable:!0,configurable:!0});for(let[Y,B]of Object.entries(z))if(s(B))Q(Y,B);for(let Y of J)Q(Y,Math.max(Z3($,Y)??0,J3($,Y)??1));X[i1]=G}function o0($,Z,J,X){let z=e$($),G=dJ(Z),Q=new Set,Y=[];for(let B of I2($)){let W=cJ(B),H=S(B)&&typeof B.id==="string"?B.id:void 0,V=H===void 0?void 0:z[H],U=S(V)&&Object.hasOwn(V,"staged"),j=U?r$(V.staged):void 0;if(W||!S(B)||H===void 0||Q.has(H)){if(H!==void 0&&!Q.has(H))Q.add(H);if(H!==void 0)Y.push({id:H,type:S(B)&&B.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,H),candidate:!1,invalid:"roster",stamp:"none",...j?{staged:j}:{}});continue}Q.add(H);let q=B.type==="api"?"api":"oauth",F=Object.hasOwn(z,H),K=F?sJ(z[H],J):void 0,N=nJ(B,G[H]),D=B.enabled!==!1,T=K?K.credentialEpoch:F?void 0:1,M=typeof B.accountId==="string"&&B.accountId?B.accountId:void 0,P={id:H,type:q,enabled:D,needsFirstReading:K?K.needsFirstReading:q==="oauth",hasEntry:F,candidate:!1,...typeof B.label==="string"?{label:B.label}:{},...typeof B.addedAt==="number"?{addedAt:B.addedAt}:{},...M!==void 0?{identity:M}:{},...N?{credential:N,fingerprint:D0(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...j?{staged:j}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...aJ(G[H],N,T,M,X),stamp:lJ(N,T,M,G[H])};if(F&&!K)P.invalid="entry";else P.candidate=D&&N!==void 0&&!U;Y.push(P)}return Y}function aJ($,Z,J,X,z){if(!S($)||!Object.hasOwn($,r))return{};let G=G1($,Z,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=$[r];if(!z||!G0(()=>z.validate(Q)))return{providerStateDropped:"invalid"};if(R2(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function h($){return $.identity??$.id}function Q1($,Z){if($===void 0||$>Z+b6)return Z;return Math.max(Z,$+1)}function f6($,Z){return Q1($,Z)>Z+b6}function b2($){let{id:Z,credential:J,identity:X,label:z,addedAt:G}=$;return{id:Z,...z!==void 0?{label:z}:{},type:J.type,addedAt:G,...X!==void 0?{accountId:X}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}}}function z3($,Z){if($.type==="api")return{apiKey:$.apiKey};return{...$.access!==void 0?{access:$.access}:{},refresh:$.refresh,...$.expires!==void 0?{expires:$.expires}:{},...Z!==void 0?{lastRefreshedAt:Z}:{}}}function G3($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function Q3($,Z={}){if(!S($))return"credential must be an object";if($.type==="oauth"){if(typeof $.refresh!=="string"||!$.refresh.trim())return"oauth credential needs a refresh token";return}if($.type==="api"){if(typeof $.apiKey!=="string"||!$.apiKey.trim())return"api credential needs an api key";if($.apiKey.trim()!==$.apiKey)return"api key must not carry surrounding whitespace";if(!(Z.baseURLOptional&&$.baseURL===void 0)&&!k6($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var e1="transition",B3="transitionMark";function iJ($){if(!S($))return;let Z=$[e1];if(!S(Z))return;if(typeof Z.mark!=="string"||Z.mark.length===0)return;if(Z.enabled===!0)return{mark:Z.mark,enabled:!0};if(Z.enabled===!1&&typeof Z.reason==="string")return{mark:Z.mark,enabled:!1,reason:Z.reason};return}function B1($,Z,J){if(J.enabled)J1($,Z);else i0($,Z,J.reason??"");if(!$.rosterRow(Z))return;let X=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...X,[B3]:J.mark}),!J.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)A2($,z.identity)}function rJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function oJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function tJ($,Z,J,X={}){let z=S(Z.accounts)?Z.accounts:{},G=new Map;for(let Q of o0($,Z,J)){if(Q.invalid||Q.staged||!Q.credential)continue;let Y=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!S(Y))continue;let B=e(Y[g]);if(!B?.binding)continue;if(B.digest!==E0(Q.credential))continue;let W=Q.credentialEpoch??1;if(B.credentialEpoch>W){if(!oJ(B))continue;if(X.requireCredentialStamps){if(B.dispatch===void 0)continue;if(B.dispatch!==f0(rJ(Q.credential,B.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...B,binding:B.binding}})}else if(B.credentialEpoch===W&&B.dispatch!==void 0&&B.dispatch===f0(Q.credential)&&B.binding.identity!==void 0&&Q.identity===void 0)G.set(Q.id,{kind:"identity",identity:B.binding.identity});else if(B.credentialEpoch===W&&B.binding.identity===Q.identity){if(X.requireCredentialStamps&&B.dispatch!==f0(Q.credential))continue;let H=iJ(Y[g]);if(H&&R0($,Q.id)?.[B3]!==H.mark)G.set(Q.id,{kind:"transition",transition:H})}}return G}function v6($,Z,J,X){let G={...$.entry(Z)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(S2))delete G.disabledReason;$.setEntry(Z,G);let Q=$.rosterRow(Z);if(!Q)return;if(X.identity!==void 0)Q.accountId=X.identity;else delete Q.accountId;if(X.baseURL!==void 0)Q.baseURL=X.baseURL;if(X.authHeader!==void 0)Q.authHeader=X.authHeader}function h6($,Z,J,X={}){let z=tJ($,Z,J,X);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),Q={rows:()=>o0(G,Z,J),rosterRow:(Y)=>r1(G,Y),entry:(Y)=>R0(G,Y),setEntry:(Y,B)=>o1(G,Y,B)};for(let[Y,B]of z)if(B.kind==="replace")v6(Q,Y,B.stamp.credentialEpoch,B.stamp.binding);for(let[Y,B]of z)if(B.kind==="identity")Q2(Q,Y,B.identity);else if(B.kind==="transition")B1(Q,Y,B.transition);else if(B.stamp.binding.identity!==void 0)A2(Q,B.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function m6($,Z,J,X={}){let{config:z,torn:G}=h6($,Z,J,X),Q=o0(z,Z,J,X.providerState);for(let Y of Q){if(G.includes(Y.id))Y.torn=!0,Y.candidate=!1;if(X.requireCredentialStamps&&Y.stamp!=="bound")Y.unbound=!0,Y.candidate=!1}return Q}var eJ=[5,10,20,40,80,160,320,400];async function $4($){for(let Z=0;;Z++)try{return await Y3($,Z4)}catch(J){if(J.code==="ENOENT")return;let X=eJ[Z];if(X===void 0||!p6(J))throw J;await q3(X)}}function u6($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function j3($){return y6(u6(await $4($)))}async function a($){for(let Z=0;Z<3;Z++){let J,X,z;try{J=await $4($.configPath),X=await $4($.statePath),z=await $4($.configPath)}catch(Y){if(p6(Y))break;throw Y}if(J!==z){if(Z<2)await q3(2+Math.floor(Math.random()*4));continue}let G=y6(u6(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=t$(u6(X));if(Q.status==="error")return{status:"error",file:"state",reason:Q.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:Q.exists,config:G.config,state:Q.state,rows:m6(G.config,Q.state,$.codec,{requireCredentialStamps:$.requireCredentialStamps===!0,...$.providerState?{providerState:$.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function Z0($,Z,J,X="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:$.reason});return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,retryable:!1,kind:$.status==="pending-migration"?"pending-migration":"load-error",message:$.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${$.file} file cannot be loaded: ${$.reason}`})}class F3{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,J,X,z){this.ctx=$,this.snapshot=Z,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return m6(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row($){return this.rows().find((Z)=>Z.id===$)}reservation($){if(this.rosterRow($)){let J=this.entry($);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let Z=this.stateAccount($)?.[g];return S(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){B2(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),r1(this.config,$)}dropRosterRows($){let Z=this.roster(),J=Z.filter((X)=>!(S(X)&&X.id===$));return this.config.accounts=J,Z.length-J.length}entries(){return g6(this.config)}entry($){return this.entries(),R0(this.config,$)}setEntry($,Z){o1(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=h6(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if(Z.length===0)return;this.config=$,await this.commitConfig({counted:!1})}stateAccount($){let Z=S(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn(Z,$)?Z[$]:void 0;return S(J)?J:void 0}dropStateAccount($){if(S(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!S(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,$,{value:Z,enumerable:!0,writable:!0,configurable:!0})}async commitConfig($={}){let Z=this.roster(),J=new Set;for(let B of Z)if(S(B)&&typeof B.id==="string")J.add(B.id);let X=new Set;for(let B of I2(this.snapshot.config))if(S(B)&&typeof B.id==="string"&&!J.has(B.id))X.add(B.id);for(let B of Object.keys(this.entries()))if(!J.has(B))X.add(B);X3(this.config,X);let z=this.entries(),G={};for(let[B,W]of Object.entries(z))if(J.has(B))Object.defineProperty(G,B,{value:W,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[v],Y={...this.config,version:z1,accounts:Z,[v]:{...Q,schemaVersion:r0,[N0]:G}};await this.write(this.ctx.configPath,Y,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let B of X)this.ctx.removedIds.add(B);this.config=Y}),this.config=Y}async commitState($,Z={}){let J={...this.state,version:z1,accounts:S(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,Z.durable??!1),this.state=J,$)this.progress.committed=$}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await w6(this.ctx.statePath)}catch($){throw new b({operation:this.info.operation,rowId:this.info.rowId,phase:"before-first-write",kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await w6(this.ctx.configPath)}async write($,Z,J,X=!0,z=!1,G){await V3($,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 K3($,Z){let J=new v0($.lockDefaults,$.lockEnv),X={writes:0};try{for(let Y of $.storeLocks)await J.acquire(Y);let z=await a($);if(z.status==="error")throw Z0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[Y,B]of Object.entries(z.config))if(!Z.includes(Y))G[Y]=B;G.version=z1,G[v]={schemaVersion:r0,[N0]:{}};let Q={operation:"initialize",rowId:void 0};return await P0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",Q),await J.assertAll()}}),X.writes++,await $.onStep?.("after-config-write",Q),"initialized"}catch(z){throw t0(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function w($,Z,J,X,z,G={}){let Q=Z.held.length;try{for(let W of $.storeLocks)await Z.acquire(W);let Y=await a($);if(Y.status!=="ready")throw Z0(Y,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let B=new F3($,Y,Z,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))B.assertNotStaged(X.rowId);if(G.completeTorn??!0)await B.completeTorn();return await z(B)}finally{await Z.releaseTo(Q)}}function t0($,Z,J,X){let z=Z==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if(Z==="publishRoster"&&X.publicationDecided)return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:z,kind:"publication-incomplete",retryable:!0,message:"The publication may already be decided. Replay the same plan or check publication(operationId).",cause:$});if(Z==="publishRoster"&&$ instanceof W3)return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof b){if($.phase===z&&$.rowId===J&&$.operation===Z&&$.committed===G)return $;return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:$.kind==="after-persist-hook"?$.phase:z,retryable:$.retryable,kind:$.kind,...$.committed??G?{committed:$.committed??G}:{},message:$.message,...$.cause!==void 0?{cause:$.cause}:{}})}let Q={operation:Z,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof U3)return new b({...Q,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${Z} lost a lease after its first write; the intermediate stays on disk`:`${Z} lost a lease before writing; nothing was written`});if($ instanceof H3)return new b({...Q,retryable:!0,kind:"lock-contention",message:$.message});return new b({...Q,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function l($,Z,J,X,z){let G=new v0($.lockDefaults,$.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(Y){let B=t0(Y,Z,J,Q);if(B.kind!=="after-persist-hook")await i$(Z,X,J,B,$.logger);throw B}finally{await G.releaseAll()}}function J0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(h(Z))}`,path:$.ctx.statePath}}async function M0($,Z,J){let X=await a($.ctx);if(X.status!=="ready")throw Z0(X,Z,J);let z=X.rows.find((W)=>W.id===J),G=R0(X.config,J),Q=X.state.accounts,Y=S(Q)&&Object.hasOwn(Q,J)?Q[J]:void 0,B=S(Y)?Y[g]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))B2(Z,J,G.staged);if(!z&&S(B)&&Object.hasOwn(B,"staged"))B2(Z,J,B.staged);if(!z)throw B0(Z,J);return{result:X,row:z}}function B0($,Z){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function o($,Z){if(Z.unbound)throw _($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function _($,Z,J,X,z=!1){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function l6($,Z){if(!s(Z?.credentialEpoch))throw _("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function Y1($,Z,J){if(!J)throw B0("pull",$);if(J.invalid)throw _("pull",$,"invalid-row",`row ${$} is invalid`);if(!J.credential)throw _("pull",$,"no-credential",`row ${$} holds no credential`);if(o("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==Z.credentialEpoch||J.identity!==Z.identity)throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${$} was issued for a credential the row no longer holds`})}function W1($,Z,J,X){let z=G0(()=>$.codec.merge(J,X));if(!G0(()=>$.codec.validate(z)))throw _("pull",Z,"invalid-quota","the quota codec rejected the merged map");return z}async function J4($,Z,J,X){let{ctx:z}=$,G=new v0(z.lockDefaults,z.lockEnv),Q={writes:0};try{l6(Z,J),await w(z,G,Q,{operation:"pull",rowId:Z},async(Y)=>{Y.assertNotStaged(Z);let B=Y.row(Z);Y1(Z,J,B);let W=Y.entry(Z);if(!W)throw B0("pull",Z);let H=W1(z,Z,W.quota,X);Y.setEntry(Z,{...W,quota:H,needsFirstReading:!1}),await Y.commitConfig()},{completeTorn:!1})}catch(Y){throw t0(Y,"pull",Z,Q)}finally{await G.releaseAll()}}async function N3($,Z,J={}){a$();let{ctx:X}=$;await l(X,"updateLimitsNamespace",void 0,void 0,async(z,G)=>{for(let V of X.storeLocks)await z.acquire(V);let Q=await a(X);if(Q.status!=="ready")throw Z0(Q,"updateLimitsNamespace",void 0);let Y=Q.rows.map(({id:V,credentialEpoch:U,identity:j})=>({id:V,credentialEpoch:U,identity:j})),B=await Q0("updateLimitsNamespace",()=>Z(structuredClone(Q.config.commonAuthLimits),Y)),W={...Q.config,commonAuthLimits:B},H={operation:"updateLimitsNamespace",rowId:void 0};try{await P0(X.configPath,W,{beforeRename:async()=>{await X.onStep?.("before-config-write",H),await z.assertAll(),J.beforePublish?.()}})}catch(V){if(V&&typeof V==="object"&&"published"in V&&V.published===!0)J.onPublished?.();throw V}G.writes++,J.onPublished?.(),await X.onStep?.("after-config-write",H)})}function h0($,Z,J,X,z="the provider state"){if(!$)throw _(Z,J,"invalid-input","the store was opened without a provider-state codec");let G;try{let Q=JSON.stringify(X);G=Q===void 0?void 0:JSON.parse(Q)}catch{G=void 0}if(G===void 0)throw _(Z,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!G0(()=>$.validate(G)))throw _(Z,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function V1($,Z,J,X,z){if(X===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:h0($,Z,J,G0(()=>$.merge?.(structuredClone(X),structuredClone(z))),"the merged provider state")}}function D3($,Z,J,X,z){let G=$?.onReplace,Q=G?G0(()=>G(Z.providerState===void 0?void 0:structuredClone(Z.providerState),{id:Z.id,credentialEpoch:J,...Z.identity!==void 0?{previousIdentity:Z.identity}:{},...X!==void 0?{identity:X}:{},...z!==void 0?{incoming:structuredClone(z)}:{}})):z;if(Q===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:Q};return{kind:"set",value:h0($,"replace",Z.id,Q,"the provider state onReplace returned")}}function P3($,Z,J,X,z){if(Z.kind==="set")return R2($,Z.value);if(Z.kind==="clear")return;return G1(J,X?.credential,z,X?.identity)}async function M3($,Z,J,X,z={}){n("updateProviderState");let{ctx:G}=$,Q="updateProviderState";return l(G,Q,Z,z.onFailure,async(Y,B)=>{let W=G.providerState;if(!W)throw _(Q,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw _(Q,Z,"invalid-input","a mutator is required");let H=S(J)?J.credentialEpoch:void 0;if(!s(H))throw _(Q,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await M0($,Q,Z);await Y.acquire(J0($,V));for(let U of z.extraLocks??[])await Y.acquire(U);return w(G,Y,B,{operation:Q,rowId:Z},async(U)=>{let j=U.row(Z);if(!j)throw B0(Q,Z);if(h(j)!==h(V))throw _(Q,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(j.invalid)throw _(Q,Z,"invalid-row",`row ${Z} failed validation`);if(!j.credential)throw _(Q,Z,"no-credential",`row ${Z} holds no credential`);if(o(Q,j),(j.credentialEpoch??1)!==H||j.identity!==J.identity)throw _(Q,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let F=await d6(U,W,Q,j,X);if(F.kind!=="changed")return{id:Z,outcome:"unchanged",...F.kind==="unchanged"&&F.value!==void 0?{providerState:F.value}:{}};return U.setStateAccount(Z,F.account),await U.commitState(),F.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:F.value}})})}var C3=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function d6($,Z,J,X,z,G=!1){let{id:Q,credential:Y}=X;if(!Y)throw _(J,Q,"no-credential",`row ${Q} holds no credential`);let B=X.credentialEpoch??1,W=$.stateAccount(Q),H=W?.[g],V=e(H);if(!S(H)||!V?.binding||V.digest!==E0(Y)||V.credentialEpoch!==B||V.binding.identity!==X.identity)throw _(J,Q,"unbound-credential",`row ${Q}'s credential carries no stamp of this store to bind a provider state to (stamp ${X.stamp}); rotate or replace it first`);let U=X.providerState===void 0?void 0:structuredClone(X.providerState),j=await Q0(J,()=>z(U,X));if(G&&j===C3)return{kind:"declined"};let q=j===void 0?void 0:h0(Z,J,Q,j,"the provider state the mutator returned"),F=W!==void 0&&Object.hasOwn(W,r);if(q===void 0?!F:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(q))return{kind:"unchanged",...q!==void 0?{value:q}:{}};let K={...W};if(q===void 0){delete K[r];let N={...H};delete N.providerState,K[g]=N}else{K[r]=q;let N=R2(Z,q);if(V.providerState!==N)K[g]={...H,providerState:N}}return{kind:"changed",...q!==void 0?{value:q}:{},account:K}}import{randomUUID as T3}from"node:crypto";async function Q4($,Z,J){if(!J)return;let X=$.rows().map((G)=>{let{id:Q,type:Y,label:B,enabled:W,disabledReason:H,identity:V,credentialEpoch:U,stamp:j,staged:q,torn:F,invalid:K}=G;return{id:Q,type:Y,label:B,enabled:W,disabledReason:H,identity:V,credentialEpoch:U,stamp:j,staged:q,torn:F,invalid:K}}),z=await Q0($.info.operation,()=>J({id:Z,row:X.find((G)=>G.id===Z),rows:X,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw _($.info.operation,Z,"row-protected",z)}var $X=["access","refresh","expires","lastRefreshedAt","apiKey"];function ZX($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function JX($,Z,J){if(J.type!=="api")return J;let X=$.rosterRow(Z);if(!S(X)){if(J.baseURL===void 0)throw _($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=$.row(Z)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:ZX(X),Q=J.baseURL?.trim()??G.baseURL,Y=J.authHeader??G.authHeader;if(Q!==G.baseURL||Y!==G.authHeader)throw _($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:Q,authHeader:Y}}function L3($,Z,J,X){let z=$.rosterRow(Z),G=$.row(Z),Q=X??(G?G.identity:S(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...Q!==void 0?{identity:Q}:{},...J.type==="api"?{baseURL:J.baseURL,authHeader:J.authHeader??"authorization-bearer"}:{}}}function X4($,Z,J,X,z={}){let G=JX(Z,J,X),Q=Z.stateAccount(J),Y=z.providerState??{kind:"keep"},B=Z.row(J)?.credentialEpoch??Z.entry(J)?.credentialEpoch,W=typeof B==="number"?B:1,H=P3($.ctx.providerState,Y,Q,Q&&Object.hasOwn(Q,r)?Z.row(J):void 0,W),V=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,U=G.type==="oauth"?z.stamp??Q1(V,$.ctx.now()):void 0,j={...Q??{}};for(let K of $X)delete j[K];if(z.clearErrors)delete j.lastRefreshError,delete j.lastQuotaRefreshError,delete j.quota;if(Y.kind==="clear")delete j[r];else if(Y.kind==="set")j[r]=Y.value;let q=G3(G,U),F={...j,...z3(G,U),[g]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[e1]:z.transition}:{},...x6(q,W,z.binding??L3(Z,J,q,z.identity),{replace:z.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:q,account:F}}async function z4($,Z,J){return $.setStateAccount(Z,J.account),await $.commitState(J.stored),J.stored}async function B4($,Z,J,X,z={}){return z4(Z,J,X4($,Z,J,X,z))}async function XX($,Z,J){if(!Z.credential||Z.stamp!=="bound")return;let X=$.stateAccount(Z.id),z=G1(X,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...X??{},[g]:x6(Z.credential,Z.credentialEpoch??1,L3($,Z.id,Z.credential,J),z!==void 0?{providerState:z}:{})}),await $.commitState()}function s6($,Z,J){let X=$==="add"?E2(Z):void 0;if(X)throw _($,Z,"invalid-input",X);let z=Q3(J,{baseURLOptional:$==="rotate"});if(z)throw _($,Z,"invalid-input",z)}function Y4($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if(X&&X.type!==J.type)throw _($,Z,"type-mismatch",`row ${Z} holds a ${J.type} credential`);return J}function x2($,Z,J){if(J!==void 0&&!s(S(J)?J.credentialEpoch:void 0))throw _($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function W4($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw _($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function G4($,Z){return _($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function H1($,Z){return _($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function zX($,Z,J,X){let{id:z,credential:G,identity:Q}=J;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!k2(Z.state,z))return;let Y=()=>{throw _("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},B=Z.stateAccount(z),W=e(B?.[g]);if(!W?.binding||W.dispatch===void 0||W.replace)return Y();if(G.type==="api"&&(W.binding.baseURL===void 0||W.binding.authHeader===void 0))return Y();let H=G.type==="api"?{...G,baseURL:W.binding.baseURL,authHeader:W.binding.authHeader}:G,[V]=o0({accounts:[b2({id:z,credential:H,identity:W.binding.identity,addedAt:0})],[v]:{rows:{[z]:{credentialEpoch:t1(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return Y();if(Q!==void 0&&Q!==V.identity)return Y();if(E0(G)!==W.digest)return Y();if(G.type==="api"){if(G.baseURL.trim()!==W.binding.baseURL)return Y();if((G.authHeader??"authorization-bearer")!==W.binding.authHeader)return Y()}else if(f0(G)!==W.dispatch)return Y();if(W.providerState!==void 0&&V.providerState===void 0)return Y();if(X!==void 0&&R2($.ctx.providerState,X)!==W.providerState)return Y();return V}function GX($,Z,J,X){let{id:z,credential:G,identity:Q,label:Y}=J,B=Z.rosterRow(z),W=()=>{throw _("add",z,B?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},H=Z.stateAccount(z),V=e(H?.[g]),U=V?.staged;if(!V?.binding||!U||V.replace||V.dispatch===void 0)return W();if(B&&(B.type!==G.type||B.label!==Y||B.accountId!==Q))return W();if(U.reservation!==J.stage?.reservation||U.label!==Y||U.disabledReason!==J.disabled?.reason||V.binding.identity!==Q)return W();let j=X===void 0?void 0:Y2(X),q=H?.[r],F=q===void 0?void 0:Y2(q);if(U.providerState!==j||U.providerState!==F)return W();if(E0(G)!==V.digest||f0(G)!==V.dispatch)return W();let K=B?Z.config:{accounts:[{...b2({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:U.label,addedAt:0}),enabled:!1}],[v]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:U.disabledReason,staged:{reservation:U.reservation}}}}},N=o0(K,Z.state,$.ctx.codec,$.ctx.providerState).find((D)=>D.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==U.label||N.identity!==V.binding.identity||N.disabledReason!==U.disabledReason||N.staged?.reservation!==U.reservation)return W();if(B)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if(t1(Z.config,z)!==V.credentialEpoch)return W();return Z.roster().push({...b2({id:z,credential:G,identity:Q,label:Y,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:U.disabledReason,staged:{reservation:U.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function O3($,Z,J={}){n("add");let{ctx:X}=$,{id:z,credential:G,identity:Q,label:Y}=Z,B=Z.stage!==void 0||Z.disabled!==void 0,W=await l(X,"add",z,J.onFailure,async(H,V)=>{s6("add",z,G);let U=J.onExisting??"rotate";if(Z.stage!==void 0&&U==="rotate")throw _("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(U)||Z.stage!==void 0&&(Y!==void 0&&typeof Y!=="string"||Q!==void 0&&(typeof Q!=="string"||!Q))||Z.disabled!==void 0&&(!S(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!S(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||U==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw _("add",z,"invalid-input","staging requires a reservation and a disabled reason");let j=Z.providerState===void 0?void 0:h0(X.providerState,"add",z,Z.providerState);if(await H.acquire(J0($,{id:z,identity:Q})),G.type==="oauth")await H.acquire(J.providerLock??$.providerLock);for(let q of J.extraLocks??[])await H.acquire(q);return w(X,H,V,{operation:"add",rowId:z},async(q)=>{await Q4(q,z,J.protect);let F=S(q.state.accounts)?q.state.accounts:{},K=Object.entries(F).find(([I,f])=>{if(I===z||q.rosterRow(I)||!S(f))return!1;let c=f[g];if(!S(c)||!Object.hasOwn(c,"staged"))return!1;return G.type==="oauth"?f.refresh===G.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===G.apiKey.trim()});if(K)throw _("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw _("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&U!=="rotate"&&(q.rosterRow(z)||k2(q.state,z)))return GX($,q,Z,j);if(U==="rotate"){q.assertNotStaged(z);let I=q.rows().find((f)=>f.fingerprint===D0(G));if(I)q.assertNotStaged(I.id)}if(U==="refuse"){let I=q.rows().find((a0)=>a0.fingerprint===D0(G)||a0.id===z&&a0.credential),f=S(q.state.accounts)?q.state.accounts:{},c=Object.entries(f).find(([,a0])=>{if(!S(a0))return!1;if(G.type==="oauth")return a0.refresh===G.refresh;return typeof a0.apiKey==="string"&&a0.apiKey.trim()===G.apiKey.trim()})?.[0],c$=I?.id??c??z;if(I||c!==void 0||k2(q.state,z))throw _("add",c$,"credential-exists",`row ${c$} already holds this secret or id`)}if(U==="stage-duplicate"&&(q.rosterRow(z)||k2(q.state,z)))throw _("add",z,"id-exists",`row ${z} already exists`);let N=zX($,q,Z,j),D=q.rows(),T=D0(G),M=U==="rotate"&&!N&&D.find((I)=>I.invalid===void 0&&I.fingerprint===T);if(M){if(q.assertNotStaged(M.id),o("add",M),Q!==void 0&&M.identity!==void 0&&Q!==M.identity)throw G4("add",M.id);let I=X4($,q,M.id,G,{...j!==void 0?{providerState:V1(X.providerState,"add",M.id,M.providerState,j)}:{}});await q.completeTorn(),q.assertNotStaged(M.id);let f=await z4(q,M.id,I);return{id:M.id,outcome:"rotated",credential:f,credentialEpoch:M.credentialEpoch??1}}let P=D.find((I)=>I.id===z);if(P){if(P.invalid)throw _("add",z,"invalid-row",`row ${z} is invalid`);if(P.credential)throw _("add",z,"id-exists",`row ${z} already holds a credential`);if(o("add",P),P.type!==G.type)throw _("add",z,"type-mismatch",`row ${z} is a ${P.type} row`);if(Q!==void 0&&P.identity!==void 0&&Q!==P.identity)throw G4("add",z);if(!P.hasEntry)q.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let I=X4($,q,z,G,{clearErrors:!0,...j!==void 0?{providerState:{kind:"set",value:j}}:{}});await q.completeTorn();let f=await z4(q,z,I);if(!P.hasEntry)await q.commitConfig();return{id:z,outcome:"completed",credential:f,credentialEpoch:P.credentialEpoch??1}}let O=t1(q.config,z);if(!s(O))throw _("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let C=N?.identity??Q;q.roster().push(b2({id:z,credential:G,...C!==void 0?{identity:C}:{},...Y!==void 0?{label:Y}:{},addedAt:X.now()})),q.setEntry(z,{credentialEpoch:O,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let L="added";if(Z.disabled)i0(q,z,Z.disabled.reason),L="added-disabled";if(!Z.disabled&&C!==void 0&&G.type==="oauth"){if(D.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===C))i0(q,z,I6),L="added-disabled"}if(N?.credential)return await q.commitConfig(),{id:z,outcome:L,credential:N.credential,credentialEpoch:N.credentialEpoch??O};q.dropStateAccount(z);let A=X4($,q,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...Y!==void 0?{label:Y}:{},...j!==void 0?{providerState:Y2(j)}:{}}}:{},...j!==void 0?{providerState:{kind:"set",value:j}}:{}});if(U==="rotate")await q.completeTorn();let x=await z4(q,z,A);return await q.commitConfig(),{id:z,outcome:L,credential:x,credentialEpoch:O}},{completeTorn:!1})});if(!B&&G.type==="oauth"&&(W.outcome==="added"||W.outcome==="completed"))$.firePull(W.id,"add");return W}async function _3($,Z,J,X={},z={}){n("replace");let{ctx:G}=$,Q=await l(G,"replace",Z,z.onFailure,async(Y,B)=>{s6("replace",Z,J),x2("replace",Z,z.attribution);let W=X.providerState===void 0?void 0:h0(G.providerState,"replace",Z,X.providerState),{row:H}=await M0($,"replace",Z);if(await Y.acquire(J0($,H)),J.type==="oauth")await Y.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await Y.acquire(V);return w(G,Y,B,{operation:"replace",rowId:Z},async(V)=>{if(z.attribution!==void 0)W4("replace",Z,V.row(Z),z.attribution),await V.completeTorn();let U=Y4("replace",Z,V.row(Z),J);if(h(U)!==h(H))throw H1("replace",Z);let j=V.entry(Z)?.credentialEpoch,q=(typeof j==="number"?j:1)+1;if(!s(q))throw _("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let F=D3(G.providerState,U,q,X.identity,W),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(v6(V,Z,q,K),X.identity!==void 0)A2(V,X.identity);let N=await B4($,V,Z,J,{clearErrors:!0,binding:K,providerState:F});return await V.commitConfig(),{id:Z,credential:N,credentialEpoch:q}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")$.firePull(Z,"replace");return Q}async function S3($,Z,J,X={},z={}){n("rotate");let{ctx:G}=$;return l(G,"rotate",Z,z.onFailure,async(Q,Y)=>{s6("rotate",Z,J),x2("rotate",Z,z.attribution);let B=X.providerState===void 0?void 0:h0(G.providerState,"rotate",Z,X.providerState),{row:W}=await M0($,"rotate",Z);if(await Q.acquire(J0($,W)),X.identity!==void 0&&J.type==="oauth")await Q.acquire(z.providerLock??$.providerLock);for(let H of z.extraLocks??[])await Q.acquire(H);return w(G,Q,Y,{operation:"rotate",rowId:Z},async(H)=>{if(z.attribution!==void 0)W4("rotate",Z,H.row(Z),z.attribution),await H.completeTorn();let V=Y4("rotate",Z,H.row(Z),J);if(h(V)!==h(W))throw H1("rotate",Z);if(o("rotate",V),X.identity!==void 0&&V.identity!==void 0&&X.identity!==V.identity)throw G4("rotate",Z);let U=X.identity!==void 0&&V.identity===void 0?X.identity:void 0,j=await B4($,H,Z,J,{identity:U,...B!==void 0?{providerState:V1(G.providerState,"rotate",Z,V.providerState,B)}:{}}),q=!1;if(!V.hasEntry)H.setEntry(Z,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),q=!0;if(X.identity!==void 0&&V.identity!==X.identity)Q2(H,Z,X.identity),q=!0;if(q)await H.commitConfig();return{id:Z,credential:j}},{completeTorn:z.attribution===void 0})})}async function A3($,Z,J,X,z){n(Z);let{ctx:G}=$,Q=G.providerState,Y=z.attribution,B=z.providerState;return l(G,Z,J,z.onFailure,async(W,H)=>{if(x2(Z,J,Y),B!==void 0){if(typeof B!=="function")throw _(Z,J,"invalid-input","the provider-state mutator must be a function");if(Y===void 0)throw _(Z,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!Q)throw _(Z,J,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await M0($,Z,J);await W.acquire(J0($,V));for(let U of z.extraLocks??[])await W.acquire(U);return w(G,W,H,{operation:Z,rowId:J},async(U)=>{await Q4(U,J,z.protect),U.assertNotStaged(J);let j=U.row(J),q=X.enabled?Y4("enable",J,j):j;if(!q||!U.rosterRow(J))throw B0(Z,J);if(h(q)!==h(V))throw H1(Z,J);if(Y!==void 0)W4(Z,J,q,Y);if(X.enabled&&q.disabledReason?.startsWith(S2))throw _("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let F=!X.enabled||!q.enabled||q.disabledReason!==void 0;if(X.enabled&&F&&q.type==="oauth"){let M=q.identity===void 0?void 0:U.rows().find((P)=>P.id!==J&&P.invalid===void 0&&P.type==="oauth"&&P.enabled&&P.identity===q.identity);if(M)throw _("enable",J,"duplicate-identity",`row ${M.id} is enabled with the same identity as row ${J}`)}if(B===void 0||Q===void 0){if(await U.completeTorn(),!F)return{id:J};if(X.enabled)J1(U,J);else i0(U,J,X.reason);return await U.commitConfig(),{id:J}}if(!q.credential)throw _(Z,J,"no-credential",`row ${J} holds no credential`);o(Z,q);let K=await d6(U,Q,Z,q,B,!0);if(K.kind==="declined")return{id:J,declined:!0};await U.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(F){if(X.enabled)J1(U,J);else i0(U,J,X.reason);await U.commitConfig()}return N}if(!F)return U.setStateAccount(J,K.account),await U.commitState(),N;let D=X.enabled?{mark:T3(),enabled:!0}:{mark:T3(),enabled:!1,reason:X.reason},T=K.account[g];return U.setStateAccount(J,{...K.account,[g]:{...T,[e1]:D}}),await U.commitState(),B1(U,J,D),await U.commitConfig(),N},{completeTorn:!1})})}function E3($,Z,J,X={}){return A3($,"disable",Z,{enabled:!1,reason:J},X)}function R3($,Z,J={}){return A3($,"enable",Z,{enabled:!0},J)}async function I3($,Z,J={}){n("remove");let{ctx:X}=$;return l(X,"remove",Z,J.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw _("remove",Z,"invalid-input","id must be non-empty");let Q=J.attribution;if(x2("remove",Z,Q),J.staged!==void 0&&(!S(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw _("remove",Z,"invalid-input","a staged removal needs a reservation");let Y=await a(X);if(Y.status!=="ready")throw Z0(Y,"remove",Z);let B=Y.rows.find((H)=>H.id===Z);if(!B&&!k2(Y.state,Z))throw B0("remove",Z);let W=h(B??{id:Z});await z.acquire(J0($,B??{id:Z}));for(let H of J.extraLocks??[])await z.acquire(H);return w(X,z,G,{operation:"remove",rowId:Z},async(H)=>{let V=H.reservation(Z);if(V!==void 0){if(!S(V)||!J.staged||V.reservation!==J.staged.reservation)throw _("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(J.staged)throw _("remove",Z,"attribution",`row ${Z} is no longer reserved`);let U=H.row(Z),j=k2(H.state,Z);if(!U&&!j)throw B0("remove",Z);if(h(U??{id:Z})!==W)throw H1("remove",Z);if(Q!==void 0)if(U)V4(Z,U,Q);else QX($,H,Z,Q);let q=J.protect;if(q){let F={row:U,config:H.snapshot.config,state:H.snapshot.state},K=await Q0("remove",()=>q(Z,F));if(K!==void 0)throw _("remove",Z,"row-protected",K)}if(U){if(Q===void 0)await H.completeTorn();H.dropRosterRows(Z),await H.commitConfig()}if(j)H.dropStateAccount(Z),await H.commitState();return{id:Z,outcome:U?"removed":"completed"}},{completeTorn:!1})})}function V4($,Z,J,X="remove"){if(W4(X,$,Z,J),Z.torn)throw _(X,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw _(X,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function QX($,Z,J,X){let z=()=>_("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=Z.stateAccount(J),Q=e(G?.[g]);if(!G||!Q?.binding||Q.dispatch===void 0||Q.replace)throw z();let Y;if(typeof G.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw z();Y={type:"api",apiKey:G.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof G.refresh==="string")Y={type:"oauth",refresh:G.refresh};else throw z();let[B]=o0({accounts:[b2({id:J,credential:Y,identity:Q.binding.identity,addedAt:0})],[v]:{rows:{[J]:{credentialEpoch:Q.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!B?.credential||B.invalid||B.stamp!=="bound")throw z();if(Q.credentialEpoch!==X.credentialEpoch||Q.binding.identity!==X.identity)throw _("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function k2($,Z){let J=$.accounts;return S(J)&&Object.hasOwn(J,Z)}function c6($){return S($)&&typeof $.id==="string"?$.id:void 0}function BX($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let J=new Set;for(let G of $){let Q=c6(G);if(Q!==void 0)J.add(Q)}let X=new Set;for(let G of Z){if(typeof G!=="string")return"ids must be an array of roster ids";if(X.has(G))return`id ${G} appears more than once`;if(!J.has(G))return`id ${G} is not in the roster`;X.add(G)}let z=[...J].filter((G)=>!X.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function YX($,Z){let J=new Map;for(let G of $){let Q=c6(G);if(Q===void 0)continue;let Y=J.get(Q);if(Y)Y.push(G);else J.set(Q,[G])}let X=Z.flatMap((G)=>J.get(G)??[]),z=0;return $.map((G)=>c6(G)===void 0?G:X[z++])}async function b3($,Z,J={}){n("reorder");let{ctx:X}=$,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let Y of J.extraLocks??[])await G.acquire(Y);return w(X,G,Q,{operation:"reorder",rowId:void 0},async(Y)=>{let B=Y.roster(),W=BX(B,Z);if(W)throw new b({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:W});let H=[...Z],V=YX(B,H);if(V.every((U,j)=>U===B[j]))return{ids:H,outcome:"unchanged"};return Y.config.accounts=V,await Y.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function k3($,Z,J,X,z={}){return n("recordIdentity"),l($.ctx,"recordIdentity",Z,z.onFailure,async(G,Q)=>{if(typeof J!=="string"||J.length===0)throw _("recordIdentity",Z,"invalid-input","identity must be non-empty");let Y=S(X)?X.credentialEpoch:void 0;if(!s(Y))throw _("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:B}=await M0($,"recordIdentity",Z);await G.acquire(J0($,B)),await G.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await G.acquire(W);return w($.ctx,G,Q,{operation:"recordIdentity",rowId:Z},async(W)=>{let H=Y4("recordIdentity",Z,W.row(Z));if(h(H)!==h(B))throw H1("recordIdentity",Z);if(o("recordIdentity",H),(H.credentialEpoch??1)!==Y)throw _("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==J)throw G4("recordIdentity",Z);if(H.identity===void 0)await XX(W,H,J);let V=Q2(W,Z,J);return await W.commitConfig(),{id:Z,disabled:V}})})}function y3($){let Z=$[v];return S(Z)&&S(Z.publications)?Z.publications:{}}function g3($,Z){let J=y3($);if(!Object.hasOwn(J,Z))return;let X=J[Z];if(!S(X)||X.operationId!==Z||typeof X.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(X.planDigest)||!["committed","cleaned"].includes(String(X.phase))||!Array.isArray(X.removed)||!Array.isArray(X.finalized)||X.removed.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch))||X.finalized.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw _("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function f3($,Z){let J=await a($.ctx);if(J.status!=="ready")throw Z0(J,"publishRoster",Z);return g3(J.config,Z)}function WX($,Z){let J=()=>{throw _("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId||!Array.isArray(Z.remove)||!Array.isArray(Z.finalize)||!Array.isArray(Z.order))J();let X=new Set;for(let z of[...Z.remove,...Z.finalize]){if(!S(z)||typeof z.id!=="string"||E2(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),x2("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of Z.remove)if($.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();for(let z of Z.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))J();if(Z.order.some((z)=>typeof z!=="string"||E2(z))||new Set(Z.order).size!==Z.order.length)J()}function v3($,Z){$.entries();let J=$.config[v],X={...y3($.config)};Object.defineProperty(X,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function VX($,Z,J){let X=new Set;for(let Q of I2($.config)){if(!S(Q)||typeof Q.id!=="string")continue;if(X.has(Q.id))throw _("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(Q.id)}let z=new Set(Z.remove.map((Q)=>Q.id)),G=J.filter((Q)=>Q.invalid!=="roster"&&!z.has(Q.id));if(G.length!==Z.order.length||Z.order.some((Q)=>!G.some((Y)=>Y.id===Q))||G.some((Q)=>!Z.order.includes(Q.id)))throw _("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function x3($,Z){await $.assertAll();for(let X of Z.removed)if(e($.stateAccount(X.id)?.[g])?.credentialEpoch===X.credentialEpoch&&!$.rosterRow(X.id))$.dropStateAccount(X.id);for(let X of Z.finalized){let z=$.stateAccount(X.id),G=e(z?.[g]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let Q={...z[g]};delete Q.staged,$.setStateAccount(X.id,{...z,[g]:Q})}}await $.commitState(void 0,{durable:!0});let J={...Z,phase:"cleaned"};return v3($,J),await $.commitConfig({durable:!0}),J}async function h3($,Z,J={}){return n("publishRoster"),l($.ctx,"publishRoster",Z?.operationId??"",J.onFailure,async(X,z)=>{if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw _("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=Y2(Z),Q=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((Y)=>S(Y)&&typeof Y.id==="string");for(let Y=0;;Y++){let B=await a($.ctx);if(B.status!=="ready")throw Z0(B,"publishRoster",Z.operationId);let W=new Map(Q.map(({id:V})=>[V,h(B.rows.find((U)=>U.id===V)??{id:V})]));for(let V of[...new Set(W.values())].sort())await X.acquire(J0($,{id:V}));await X.acquire(J.providerLock??$.providerLock);for(let V of J.extraLocks??[])await X.acquire(V);let H=await w($.ctx,X,z,{operation:"publishRoster",rowId:Z.operationId},async(V)=>{let U=V.rows();if(Q.some(({id:P})=>h(U.find((O)=>O.id===P)??{id:P})!==W.get(P)))return;let j=g3(V.config,Z.operationId);if(j){if(j.planDigest!==G)throw _("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(j.phase==="cleaned")return{outcome:"already-cleaned",receipt:j};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await x3(V,j)}}WX($,Z);let q=VX(V,Z,U),F=[];for(let P of Z.remove){V.assertNotStaged(P.id);let O=U.find((C)=>C.id===P.id);if(!O)throw _("publishRoster",P.id,"attribution","the removed row no longer exists");if(V4(P.id,O,P.attribution,"publishRoster"),!O.credential||P.fingerprint!==void 0&&D0(O.credential)!==P.fingerprint)throw _("publishRoster",P.id,"attribution","the removed secret no longer matches");F.push(O)}let K=[];for(let P of Z.finalize){let O=U.find((f)=>f.id===P.id),C=e(V.stateAccount(P.id)?.[g]);if(!O||O.staged?.reservation!==P.reservation||C?.staged?.reservation!==P.reservation||O.enabled)throw _("publishRoster",P.id,"row-staged","the finalized row is not disabled under this reservation");let L=V.stateAccount(P.id),A=V.rosterRow(P.id),x=L?.[r],I=x===void 0?void 0:Y2(x);if(!C?.staged||C.staged.label!==A?.label||C.staged.disabledReason!==O.disabledReason||C.staged.providerState!==I)throw _("publishRoster",P.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");V4(P.id,O,P.attribution,"publishRoster"),K.push(O)}let N=q.find((P)=>P.torn);if(N)throw _("publishRoster",Z.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let D=new Set;for(let P of q){if(!(Z.finalize.find((C)=>C.id===P.id)?.enabled??P.enabled)||P.type!=="oauth"||P.identity===void 0)continue;if(D.has(P.identity))throw _("publishRoster",P.id,"invalid-input","the final enabled roster repeats a known identity");D.add(P.identity)}for(let P of q)if(P.identity!==void 0&&P.fingerprint!==void 0&&q.some((O)=>O.id!==P.id&&O.identity!==void 0&&O.identity!==P.identity&&O.fingerprint===P.fingerprint))throw _("publishRoster",P.id,"attribution","the resulting pool gives the same secret different known identities");for(let P of K)if(P.identity!==void 0&&F.some((O)=>O.identity!==void 0&&O.identity!==P.identity&&O.fingerprint===P.fingerprint))throw _("publishRoster",P.id,"attribution","the staged secret belonged to a different known identity");await Q4(V,Z.operationId,J.protect);let T={operationId:Z.operationId,planDigest:G,phase:"committed",removed:F.map((P)=>({id:P.id,credentialEpoch:P.credentialEpoch??1})),finalized:Z.finalize.map((P,O)=>({id:P.id,credentialEpoch:K[O]?.credentialEpoch??1,reservation:P.reservation,enabled:P.enabled}))};for(let P of Z.remove)V.dropRosterRows(P.id);for(let P of Z.finalize){let O=V.rosterRow(P.id);O.enabled=P.enabled;let C={...V.entry(P.id)};if(delete C.staged,P.enabled)delete C.disabledReason;else C.disabledReason=P.disabledReason;V.setEntry(P.id,C)}let M=V.roster().filter((P)=>!S(P)||typeof P.id!=="string"||U.find((O)=>O.id===P.id)?.invalid==="roster");return V.config.accounts=[...Z.order.map((P)=>V.rosterRow(P)),...M],v3(V,T),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await x3(V,T)}},{completeTorn:!1});if(H)return H;if(await X.releaseAll(),Y>=1)throw _("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class n6{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,J,X,z){this.rt=$,this.hook=Z,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire($,Z){if(!this.hook)return;if(Z==="load"){if(this.firedAtLoad.has($))return;this.firedAtLoad.add($)}let J=this.run($,Z);this.inflight.add(J),J.finally(()=>this.inflight.delete(J))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run($,Z){let J=this.rt(),{ctx:X}=J,z=new v0(X.lockDefaults,X.lockEnv),G={writes:0};try{let Q=await w(X,z,G,{operation:"pull",rowId:$},async(W)=>{if(W.reservation($)!==void 0)return;await W.completeTorn();let H=W.row($);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)o("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.hasEntry)W.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let V=W.row($);if(!V?.credential||V.credentialEpoch===void 0)return;return{id:$,credential:V.credential,credentialEpoch:V.credentialEpoch,...V.identity!==void 0?{identity:V.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!Q){this.firedAtLoad.delete($);return}await X.hold?.("pull-before-request",$);let Y;try{Y=await this.hook?.(Q)}catch(W){throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await(J.publishQuota??((W,H,V)=>J4(J,W,H,V)))($,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},Y)}catch(Q){this.firedAtLoad.delete($);let Y=t0(Q,"pull",$,G);if(this.onFailure)try{await this.onFailure($,Y)}catch(B){this.logger?.warn("pull failure hook threw",{rowId:$,error:B instanceof Error?B.message:String(B)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:Y.kind})}finally{await z.releaseAll()}}}var m3=100,H4=128;class a6{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=u3){this.rt=$,this.timeoutMs=Z,this.clock=J,this.logger=$.ctx.logger??t("store")}async record($,Z,J){try{this.assertOpen($),l6($,Z);let X=structuredClone({id:$,attribution:Z,observation:J}),{row:z,result:G}=await M0(this.rt,"pull",$);Y1($,X.attribution,z),W1(this.rt.ctx,$,this.overlayRow({...z,quota:R0(G.config,$)?.quota}).quota,X.observation),await this.room($),this.assertOpen($);let Q=this.pending.get($)??[];if(Q.push(X),this.pending.set($,Q),Q.length>=H4)this.flushNow();else this.schedule(m3)}catch(X){throw t0(X,"pull",$,{writes:0})}}queued($){return this.pending.get($)?.length??0}async room($){if(this.queued($)<H4)return;let{ctx:Z}=this.rt,J=Math.max(0,...Z.storeLocks.map((z)=>z.timeoutMs??Z.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued($)>=H4){this.assertOpen($),this.flushNow();let z=X-performance.now();if(z<=0)throw _("pull",$,"lock-contention",`pool quota queue for ${$} is full (${H4} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let Q=()=>{clearTimeout(Y),this.wake.delete(Q),G()},Y=setTimeout(Q,z);this.wake.add(Q)})}}assertOpen($){if(this.closed)throw _("pull",$,"invalid-input","pool quota writer is closed")}overlayRow($){let Z=$;for(let J of this.pending.get($.id)??[])try{Y1($.id,J.attribution,$),Z={...Z,quota:W1(this.rt.ctx,$.id,Z.quota,J.observation),needsFirstReading:!1}}catch{}return Z}overlay($){return $.map((Z)=>this.overlayRow(Z))}schedule($){if(this.running||this.timer||!this.pending.size||this.stopped)return;let Z=this.closed?0:(this.committedAt??-1/0)+w3-this.clock.now();if(this.timer=this.clock.schedule(Math.max($,Z),()=>{return this.timer=void 0,this.flush()}),!this.closed)this.timer.unref?.()}cancelTimer(){this.timer?.cancel(),this.timer=void 0}flushNow(){if(this.running)return;this.cancelTimer(),this.flush()}flush(){if(this.running||this.stopped||!this.pending.size)return this.running??Promise.resolve();let $=[...this.pending.values()].flat(),Z={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new v0(Z.lockDefaults,Z.lockEnv);return this.running=(async()=>{try{await w(Z,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let Q of $){let{id:Y,attribution:B,observation:W}=Q,H=JSON.stringify([Y,B.credentialEpoch,B.identity]);try{z.assertNotStaged(Y),Y1(Y,B,z.row(Y))}catch(j){if(!(j instanceof b))throw j;if(!this.warned.has(H))this.warned.add(H),this.warn("pool quota publication dropped; account binding changed",{id:Y,kind:j.kind});continue}let V=z.entry(Y);if(!V)continue;let U;try{U=W1(Z,Y,V.quota,W)}catch(j){let q=`codec:${H}`;if(!this.warned.has(q))this.warned.add(q),this.warn("pool quota publication dropped; the quota codec refused it",{id:Y,error:j instanceof Error?j.message:String(j)});continue}z.setEntry(Y,{...V,quota:U,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set($);for(let[z,G]of this.pending){let Q=G.filter((Y)=>!X.has(Y));if(Q.length)this.pending.set(z,Q);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()):m3;this.schedule(X)}})(),this.running}warn($,Z){try{this.logger.warn($,Z)}catch{}}close(){if(this.closing)return this.closing;return this.closed=!0,this.closing=this.drain(),this.closing}async drain(){this.cancelTimer();let $,Z,J=new Promise((X)=>{Z=()=>{if(!this.pending.size)X()},this.wake.add(Z),Z()});try{this.flush(),await Promise.race([J,new Promise((X)=>{$=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout($),this.cancelTimer(),this.wake.delete(Z),this.pending.size)this.warn("pool quota drain timed out; pending readings left",{accounts:this.pending.size,readings:[...this.pending.values()].reduce((X,z)=>X+z.length,0)});this.pending.clear();for(let X of this.wake)X()}}}import{randomUUID as HX}from"node:crypto";function i6($,Z){if(B2("refresh",$,Z?.staged),!Z)throw _("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw _("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw _("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw _("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function p3($){return _("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function l3($,Z,J,X={}){n("refresh");let{ctx:z}=$;return l(z,"refresh",Z,X.onFailure,async(G,Q)=>{let{row:Y}=await M0($,"refresh",Z);i6(Z,Y);let B=await X.refuse?.(Y);if(B!==void 0)return{status:"refused",rowId:Z,reason:B};let W=h(Y),H;for(let q=0;;q++){await G.acquire(J0($,{id:Z,identity:W===Z?void 0:W})),await G.acquire(X.providerLock??$.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await w(z,G,{writes:0},{operation:"refresh",rowId:Z},async(N)=>{let D=i6(Z,N.row(Z));if(o("refresh",D),!D.hasEntry)N.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),D=i6(Z,N.row(Z));if(h(D)!==W)return{keyNow:h(D)};let T=await X.refuse?.(D);if(T!==void 0)return{refused:T};return{row:D,credential:D.credential,credentialEpoch:D.credentialEpoch,identity:D.identity}});if("refused"in K)return{status:"refused",rowId:Z,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),q>=1)throw _("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);W=K.keyNow;continue}H=K;break}if(f6(H.credential.lastRefreshedAt,z.now()))throw p3(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let V;try{V=await J(H.credential,H.row)}catch(q){throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:q})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw _("refresh",Z,"provider","the provider returned no refresh token",!0);let U=V.providerState===void 0?void 0:h0(z.providerState,"refresh",Z,V.providerState,"the provider state the provider returned"),j=await w(z,G,Q,{operation:"refresh",rowId:Z},async(q)=>{let F=q.row(Z),K=q.entry(Z);if(!F||F.invalid||!K||K.credentialEpoch!==H.credentialEpoch||F.identity!==H.identity)throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${Z} changed credential while its refresh was in flight; the rotation is discarded`});o("refresh",F);let N=await X.refuse?.(F);if(N!==void 0)return{refused:N};let D=z.now(),T=F.credential?.type==="oauth"?F.credential.lastRefreshedAt:void 0;if(f6(T,D))throw p3(Z);let M={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},P=F.identity!==void 0&&V.identity!==void 0&&F.identity!==V.identity?{expectedIdentity:F.identity,returnedIdentity:V.identity}:void 0,O=P?{mark:HX(),enabled:!1,reason:`${S2}${JSON.stringify(P)}`}:void 0,C=F.identity===void 0&&V.identity?V.identity:void 0,L=await B4($,q,Z,M,{stamp:Q1(T,D),transition:O,identity:C,...U!==void 0?{providerState:V1(z.providerState,"refresh",Z,F.providerState,U)}:{}});if(O!==void 0)B1(q,Z,O),await q.commitConfig();let A=F.identity;if(C!==void 0)Q2(q,Z,C),A=C,await q.commitConfig();return{stored:L,identity:A,contradiction:P,refused:void 0}});if(j.refused!==void 0)return{status:"refused",rowId:Z,reason:j.refused};if(j.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...j.contradiction,credential:j.stored};if(X.onPersisted)try{let q=X.onPersisted;await Q0("refresh",()=>q(Z,j.stored),!0)}catch(q){throw new b({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:j.stored,message:"the after-persist hook threw; the rotation stays committed",cause:q})}return{status:"rotated",rowId:Z,credential:j.stored,...j.identity!==void 0?{identity:j.identity}:{}}})}import{isDeepStrictEqual as d3}from"node:util";var j4=Object.freeze(["version","accounts",v]);function U4($){let Z={};for(let[J,X]of Object.entries($))if(!j4.includes(J))q4(Z,J,X);return Z}function q4($,Z,J){Object.defineProperty($,Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function UX($,Z){let J={};for(let[X,z]of Object.entries($))if(j4.includes(X)||X==="commonAuthLimits")q4(J,X,z);else if(Object.hasOwn(Z,X))q4(J,X,Z[X]);for(let[X,z]of Object.entries(Z))if(!Object.hasOwn($,X))q4(J,X,z);return J}function r6($){return new b({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}var qX=new c3;function s3($){return n3($.ctx.configPath)}async function n3($){let Z=async([X=$]=[])=>{let z=await j3(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:U4(z.config)}},J=Z4?await Z():await qX.read([$],Z);return structuredClone(J)}async function a3($,Z,J={}){n("updateSettings");let{ctx:X}=$,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of J.extraLocks??[])await G.acquire(B);let Y=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let B=await a(X);if(B.status!=="ready")throw Z0(B,"updateSettings",void 0);let W=U4(B.config),H=structuredClone(W),V=await Q0("updateSettings",()=>Z(H)),U=V===void 0?H:V;if(!S(U))throw r6("the settings mutator must produce an object");let j=j4.filter((K)=>Object.hasOwn(U,K));if(j.length>0)throw r6(`settings cannot set the pool-owned key(s) ${j.join(", ")}`);if(Object.hasOwn(U,"commonAuthLimits")&&(!Object.hasOwn(W,"commonAuthLimits")||!d3(U.commonAuthLimits,W.commonAuthLimits)))throw r6("settings cannot alter commonAuthLimits; use updateLimitsNamespace");let q=UX(B.config,U);if(d3(U4(q),W))return{settings:W,outcome:"unchanged"};let F={operation:"updateSettings",rowId:void 0};return await P0(X.configPath,q,{beforeRename:async()=>{await X.onStep?.("before-config-write",F),await G.assertAll()}}),Q.writes++,await X.onStep?.("after-config-write",F),{settings:U4(q),outcome:"updated"}}finally{await G.releaseTo(Y)}})}var i3=new Map;function jX($){let Z=i3.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},i3.set($,Z);return Z}function r3($){if($.status==="ready")return{status:"ready",schemaVersion:r0,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function U1($){let Z=jX($.configPath),J={...o6,...$.lockOptions},X={provider:$.provider,configPath:$.configPath,statePath:$.statePath,codec:$.quota,...$.providerState?{providerState:$.providerState}:{},now:$.now??Date.now,storeLocks:$.storeLocks??[{name:"save",path:$.configPath},{name:"save",path:$.statePath}],lockDefaults:J,lockEnv:{...$.onLockEvent?{onLockEvent:$.onLockEvent}:{},...$.onLockStep?{onLockStep:$.onLockStep}:{},...$.onRenewalTimer?{onRenewalTimer:$.onRenewalTimer}:{}},removedIds:Z.removedIds,requireCredentialStamps:$.requireCredentialStamps===!0,requireRemovedFingerprint:$.requireRemovedFingerprint===!0,...$.logger?{logger:$.logger}:{},...$.onStep?{onStep:$.onStep}:{},...$.hold?{hold:$.hold}:{}},z=new n6(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:X,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(W,H)=>z.fire(W,H)},Q=$.coalesceQuota?new a6(G,$.quotaDrainTimeoutMs,$.quotaCommitTimer):void 0,Y=(W,H,V)=>Q?Q.record(W,H,V):J4(G,W,H,V);G.publishQuota=Y;let B=(W)=>{if(W.status==="ready"&&Q)return{...W,rows:Q.overlay(W.rows)};return W};return{async load(){let W=B(await a(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 r3(W)},async read(){return r3(B(await a(X)))},async initialize(W={}){return{status:await K3(X,W.dropKeys??[])}},add:(W,H)=>O3(G,W,H),publishRoster:(W,H)=>h3(G,W,H),publication:(W)=>f3(G,W),replace:(W,H,V,U)=>_3(G,W,H,V,U),rotate:(W,H,V,U)=>S3(G,W,H,V,U),updateProviderState:(W,H,V,U)=>M3(G,W,H,V,U),disable:(W,H,V)=>E3(G,W,H,V),enable:(W,H)=>R3(G,W,H),remove:(W,H)=>I3(G,W,H),reorder:(W,H)=>b3(G,W,H),readSettings:()=>s3(G),updateSettings:(W,H)=>a3(G,W,H),updateLimitsNamespace:(W,H)=>N3(G,W,H),recordIdentity:(W,H,V,U)=>k3(G,W,H,V,U),refresh:(W,H,V)=>l3(G,W,H,V),recordQuota:Y,close:()=>Q?.close()??Promise.resolve(),dispose:()=>Q?.close()??Promise.resolve(),requestReading:(W)=>z.fire(W,"admission"),pullsSettled:()=>z.settled()}}var FX=[/\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 $9($={}){let{redactStrings:Z}=o3({...$,extraValuePatterns:[...FX,...$.extraValuePatterns??[]]});return(J)=>Z(J)}class u extends Error{code;constructor($,Z,J){super(Z,J);this.name="CommandError",this.code=$}}var t3=/^[a-z][a-z0-9-]{0,63}$/,t6={code:"action-failed",text:"That action failed."},KX=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 q1($){if($ instanceof u)return{code:t3.test($.code)?$.code:t6.code,text:$.message};if($ instanceof b)return{code:`pool-${$.kind}`,text:KX.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return t6}var e3="This cannot be undone. Continue?",NX=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function DX($){let Z=$.toLowerCase().replace(/[-_]/g,"");return NX.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function PX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function e6($,Z,J){if(typeof $==="string"){let z=J.redact($);if(z!==$)J.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>e6(z,`${Z}[${G}]`,J));if(!PX($))return $;let X={};for(let[z,G]of Object.entries($)){if(DX(z)){J.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(X,z,{value:e6(G,`${Z}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function $5($,Z,J){let X={redact:J.redact,dropped:[],redacted:[]},z=e6($,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:Z,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:Z,fields:X.redacted});return z}function MX($){return{value:String($.value),label:String($.label)}}function CX($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(MX),...$.value!==void 0?{value:$.value}:{}};case"toggle":return{kind:"toggle",id:$.id,label:$.label,value:$.value===!0};case"number":return{kind:"number",id:$.id,label:$.label,...$.value!==void 0?{value:$.value}:{},...$.min!==void 0?{min:$.min}:{},...$.max!==void 0?{max:$.max}:{},...$.required?{required:!0}:{}};case"text":return{kind:"text",id:$.id,label:$.label,...$.value!==void 0&&!$.masked?{value:$.value}:{},...$.placeholder!==void 0?{placeholder:$.placeholder}:{},...$.masked?{masked:!0}:{},...$.required?{required:!0}:{}}}}function Z9($){if($.irreversible===!0)return{message:$.confirm||e3,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function Z5($){let Z=Z9($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(CX),...Z?{confirm:Z}:{}}}function TX($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function LX($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:TX($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(Z5)}}function OX($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(LX),actions:(Z.actions??[]).map(Z5),...Z.facts!==void 0?{facts:Z.facts}:{}}}function J5($,Z,J){return{command:$,title:Z,sections:J.map(OX)}}function X5($,Z,J,X){return $5({command:$,menu:J5($,Z,J)},$,X)}function z5($,Z,J,X,z){return $5({command:$,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:t3.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:J5($,Z,J)},$,z)}var H5="disabled from the command menu";function _X($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function C0($){return _X($)?{...$}:{}}function SX($){if($.status!=="ready")return[];let Z=new Set;return $.rows.filter((J)=>{if(Z.has(J.id))return!1;return Z.add(J.id),!0})}function AX($,Z){return $.label??Z??$.id}function F4($,Z){return e0($.quota)?b0($.quota,Z):void 0}function U5($,Z){return`${$} ${Z}${$===1?"":"s"}`}var y2="Actions";function EX($){if($.status==="pending-migration")return"The account pool has not been migrated yet.";if($.status==="error")return`The ${$.file} file cannot be read: ${$.reason}`;return}function G5($,Z){switch(Z.outcome){case"added":return`Added ${$}.`;case"added-disabled":return`Added ${$}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${$}.`;case"rotated":return`${$} was already in the pool; its credential was updated.`;case"exists":return`${$} was already in the pool; its credential is unchanged.`}}function Q5($){return q1($).text}function X9($){if($.settings)return $.settings;let{store:Z,extraLocks:J}=$,X=J?{extraLocks:J}:{};return{async read(){let z=await Z.readSettings();return z.status==="error"?{}:z.settings},async update(z){await Z.updateSettings(z,X)}}}async function RX($){let{store:Z}=$,J=await Z.read(),X=await X9($).read(),z=await $.routing?.vaultOrder?.();return{load:J,rows:SX(J),settings:X,...z?{vault:z}:{}}}function K4($,Z){let J=Z.accounts?.describeIdentity?Z.accounts.describeIdentity($):$.identity;return{account:{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...J!==void 0?{identity:J}:{}},name:AX($,J)}}function IX($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=Z.rows.map((V)=>V.id),Q=EX(Z.load),Y=Z.rows.filter((V)=>V.enabled).length,B=Z.rows.map((V,U)=>{let{account:j,name:q}=K4(V,$),F=[V.type==="api"?"API key":"OAuth",...j.identity!==void 0?[j.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,H5,z),`Disabled ${q}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(V.id,z),`Enabled ${q}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((D,T)=>({value:String(T+1),label:String(T+1)})),value:String(U+1)}],run:async({values:D})=>{let T=Number(D.position),M=G.filter((O)=>O!==V.id);return M.splice(T-1,0,V.id),(await J.reorder(M,z)).outcome==="unchanged"?`${q} is already at position ${T}.`:`Moved ${q} to position ${T}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${q}? Its stored credential is deleted.`,run:async()=>{return await J.remove(V.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${q}.`}}),{id:V.id,label:q,detail:F,group:"Accounts",status:K,account:j,actions:N}}),W=$.accounts?.login,H=[];if(W&&!Q)H.push({id:"add",label:W.label??"Add account",group:y2,knobs:W.knobs??[],run:async({values:V,invocation:U})=>{let j=await W.run(V,U);if(j.status==="cancelled")return{ok:!1,text:j.message??"Login cancelled."};if(j.status==="ready"){let q=await J.add(j.account,z);return G5(j.account.label??q.id,q)}return j.completion.then(async(q)=>{if(!q){U.notify("Login cancelled.","warning");return}let F=await J.add(q,z);U.notify(G5(q.label??F.id,F))},(q)=>{U.notify(`Adding the account failed: ${Q5(q)}`,"error")}).catch((q)=>{U.notify(`Adding the account failed: ${Q5(q)}`,"error")}),j.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[Z.rows.length===0?"No accounts yet":`${U5(Z.rows.length,"account")}, ${Y} enabled`],items:Q?[]:B,actions:H}}}function bX($,Z){let J=$.quota?.scope??"all",X=$.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(H,V)=>{if($.quota?.check)await $.quota.check(H,V);else{for(let U of H)$.store.requestReading(U);await $.store.pullsSettled()}},Q=Z.rows.filter((H)=>H.candidate),Y=Q.map((H)=>{let{account:V,name:U}=K4(H,$),j=F4(H,J);return{id:H.id,label:U,group:z,status:I0(j,{now:X,form:"compact"}),detail:I0(j,{now:X,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:q})=>{return await G([H.id],q),`Checked quota for ${U}.`}}]}}),B=Z.rows.filter((H)=>!H.candidate).map((H)=>{let{name:V}=K4(H,$),U=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",j=I0(F4(H,J),{now:X,form:"compact"});return`${V} (${U}): ${j}`}),W=[];if(Q.length>0)W.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:y2,run:async({invocation:H})=>{let V=Q.map((U)=>U.id);return await G(V,H),`Checked quota for ${U5(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:B,items:Y,actions:W}}}async function kX($,Z){try{return await $.reorder(Z)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new u("vault-invalid-order",J.message,{cause:J});throw J}}function J9($){return new u("vault-invalid-order",$)}function xX($){let Z=$.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>Z.filter((z)=>z.id===X||z.label===X);return{ids:Z.map((X)=>X.id),nameOf:(X)=>Z.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let z=Z.find((G)=>G.id===X);return z&&!/[,\n]/.test(z.label)&&J(z.label).length===1?z.label:X},resolve:(X)=>{let z=[];for(let G of X){let Q=J(G);if(Q.length===0)throw J9(`"${G}" is not a vault account.`);if(Q.length>1)throw J9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let Y=Q[0].id;if(z.includes(Y))throw J9(`"${G}" names an account already in the order.`);z.push(Y)}return z}}}function yX($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=X9($),Q=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],Y=C0(Z.settings.routing).mode,B=typeof Y==="string"&&Q.some((N)=>N.value===Y)?Y:"ordered",W=W5(B),H=Z.vault?xX(Z.vault):void 0,V=H?H.ids:Z.rows.map((N)=>N.id),U=(N)=>H?H.nameOf(N):N,j=V5(V,W.placement,$.routing?.formerMainId??Y5),F=[`Mode: ${Q.find((N)=>N.value===B)?.label??B}`];if(V.length>0)F.push(`${H?"Vault account order":"Roster order"}: ${V.map(U).join(", ")}`);if(W.mode==="ordered"&&j.join()!==V.join())F.push(`Tried in order: ${j.map(U).join(", ")}`);let K=[{id:"mode",label:"Change mode",group:y2,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:Q,value:B}],run:async({values:N})=>{let D=String(N.mode);return await G.update((T)=>{T.routing={...C0(T.routing),mode:D};return}),`Routing mode set to ${Q.find((T)=>T.value===D)?.label??D}.`}}];if(V.length>1)K.push({id:"order",label:"Set order",group:y2,knobs:[{kind:"text",id:"order",label:H?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:H?V.map(H.entryOf).join(", "):V.join(", "),required:!0}],run:async({values:N})=>{let T=String(N.order).split(H?/[,\n]+/:/[\s,]+/).map((P)=>P.trim()).filter((P)=>P.length>0),M=Z.vault&&H?await kX(Z.vault,H.resolve(T)):await J.reorder(T,z);return M.outcome==="unchanged"?"The order is unchanged.":`Order set to ${M.ids.map(U).join(", ")}.`}});if($.routing?.sameAccountWait){let D=[{value:"0",label:"Don't wait"},{value:"15",label:"15 minutes"},{value:"max",label:"Until the cache expires"}],T=C0(Z.settings.routing).maxSameAccountWait,M=String(T===0||T==="max"?T:15),P=(O)=>D.find((C)=>C.value===O)?.label??O;F.push(`Longest wait on the same account: ${P(M)}`),K.push({id:"maxSameAccountWait",label:"Longest wait on the same account",group:y2,knobs:[{kind:"choice",id:"maxSameAccountWait",label:"Longest wait on the same account",choices:D,value:M}],run:async({values:O})=>{let C=String(O.maxSameAccountWait),L=C==="max"?"max":Number(C);return await G.update((A)=>{A.routing={...C0(A.routing),maxSameAccountWait:L};return}),`Longest wait on the same account set to ${P(C)}.`}})}return{id:"routing",slot:"routing",title:"Routing",content:{lines:F,actions:K}}}function gX($,Z){if($.limits?.labels)return[...$.limits.labels];let J=$.quota?.scope??"all",X=[];for(let z of Z.rows)for(let G of F4(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function fX($,Z){let J=$.quota?.scope??"all",X=new Map;for(let z of Z.rows)for(let G of F4(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,B5(G));return(z)=>X.get(z)??z}function vX($,Z){let J=X9($),X=C0(Z.settings.killswitch),z=X.enabled===!0,G=C0(X.accounts),Q=gX($,Z),Y=fX($,Z),B=z?"on":"off",W=Z.rows.map((H)=>{let{account:V,name:U}=K4(H,$),j=C0(G[H.id]),q=Q.filter((F)=>typeof j[F]==="number");return{id:H.id,label:U,group:`Floors · killswitch ${B}`,status:q.length===0?"no floors":q.map((F)=>`${Y(F)} ≥${j[F]}%`).join(" · "),account:V,actions:[{id:"floors",label:"Set floors",knobs:Q.map((F)=>({kind:"number",id:F,label:`Minimum % left for ${Y(F)}`,min:0,max:100,...typeof j[F]==="number"?{value:j[F]}:{}})),run:async({values:F})=>{return await J.update((K)=>{let N=C0(K.killswitch),D=C0(N.accounts),T=C0(D[H.id]);for(let M of Q){let P=F[M];if(typeof P==="number")T[M]=P;else if(P===null)delete T[M]}if(Object.keys(T).length>0)D[H.id]=T;else delete D[H.id];if(Object.keys(D).length>0)N.accounts=D;else delete N.accounts;K.killswitch=N;return}),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${B}`],items:W,actions:[{id:"killswitch",label:z?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:y2,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!z}],run:async({values:H})=>{let V=H.enabled===!0;return await J.update((U)=>{U.killswitch={...C0(U.killswitch),enabled:V};return}),`Killswitch ${V?"on":"off"}.`}}]}}}async function q5($){let Z=await RX($);return[IX($,Z),bX($,Z),yX($,Z),vX($,Z)]}var hX=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),z9=["accounts","quota","routing","limits"];function j5($,Z){let{sessionId:J}=$,X=$.notify.bind($);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X(Z(String(z))):X(Z(String(z)),G)})}function mX($,Z){switch($.kind){case"choice":{let J=Z??$.value;if(typeof J==="string"&&$.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${$.label}.`}}case"toggle":{let J=Z??$.value;return typeof J==="boolean"?{value:J}:{problem:`${$.label} must be on or off.`}}case"number":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${$.label} needs a number.`};if($.min!==void 0&&X<$.min)return{problem:`${$.label} must be at least ${$.min}.`};if($.max!==void 0&&X>$.max)return{problem:`${$.label} must be at most ${$.max}.`};return{value:X}}case"text":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${$.label} must be text.`}}}}function wX($,Z){let J={};for(let X of $){let z=Z&&Object.hasOwn(Z,X.id)?Z[X.id]:void 0,G=mX(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function uX($,Z){let J=$.find((z)=>z.id===Z.sectionId);if(!J)return;return(Z.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===Z.itemId)?.actions)?.find((z)=>z.id===Z.actionId)}function W2($){let Z=$.logger??t("commands"),J=$9($.redaction),X={logger:Z,redact:J},z=$.now??Date.now,G=$.extras??[],Q=$.replace??{},Y=z9.filter((U)=>!Q[U]);for(let U of z9)if(Q[U]&&$[U]!==void 0)throw Error(`the ${U} section is replaced; its built-in options cannot also be given`);let B=$.store;if(Y.length>0&&!B)throw Error(`a store is required for the built-in ${Y.join(", ")} section${Y.length>1?"s":""}`);let W=new Set;for(let U of G){if(hX.has(U.id)||W.has(U.id))throw Error(`extra section id ${U.id} is taken`);W.add(U.id)}async function H(U,j,q,F){try{return{id:U,slot:j,title:q.title,content:await q.build(F)}}catch(K){return Z.warn("command menu section failed to build",{command:$.command,section:U,error:J(K instanceof Error?K.message:String(K))}),{id:U,slot:j,title:q.title,content:{lines:["This section could not be loaded."]}}}}async function V(U){let j=B&&Y.length>0?await q5({store:B,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.settings?{settings:$.settings}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],q=[];for(let F of z9){let K=Q[F];if(K)q.push(await H(F,F,K,U));else{let N=j.find((D)=>D.slot===F);if(N)q.push(N)}}if($.cache)q.push(await H("cache","cache",$.cache,U));if($.diagnostics)q.push(await H("diagnostics","diagnostics",$.diagnostics,U));for(let F of G)q.push(await H(F.id,"extra",F,U));return q}return{command:$.command,async open(U){let j=j5(U,J);return X5($.command,$.title,await V(j),X)},async apply(U,j){let q=j5(j,J),F=async(M)=>z5($.command,$.title,await V(q),M,X),K=U.command===$.command?uX(await V(q),U):void 0;if(!K)return F({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=Z9(K);if(N&&U.confirmed!==!0)return F({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let D=wX(K.knobs??[],U.values);if("problem"in D)return F({ok:!1,code:"invalid-input",text:D.problem});let T;try{let M=await K.run({values:D.values,...U.itemId!==void 0?{itemId:U.itemId}:{},invocation:q});T=typeof M==="string"?{ok:!0,text:M}:{ok:M.ok,text:M.text,...M.ok?{}:{code:M.code??"refused"}}}catch(M){let P=q1(M);Z.warn("command menu action failed",{command:$.command,section:U.sectionId,action:U.actionId,code:P.code,error:J(M instanceof Error?M.message:String(M))}),T={ok:!1,...P}}return F(T)}}}function pX($){return $===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($)}function lX($){if($===null||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.command!=="string"||typeof Z.sectionId!=="string"||typeof Z.actionId!=="string")return;if(Z.itemId!==void 0&&typeof Z.itemId!=="string")return;if(Z.sessionId!==void 0&&typeof Z.sessionId!=="string")return;if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return;let J={};if(Z.values!==void 0){if(Z.values===null||typeof Z.values!=="object"||Array.isArray(Z.values))return;for(let[X,z]of Object.entries(Z.values)){if(!pX(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:Z.command,sectionId:Z.sectionId,actionId:Z.actionId,...typeof Z.itemId==="string"?{itemId:Z.itemId}:{},...Z.values!==void 0?{values:J}:{},...Z.confirmed===!0?{confirmed:!0}:{},...typeof Z.sessionId==="string"?{sessionId:Z.sessionId}:{}}}function R($,Z){return $.namespace===Z.namespace&&$.accountId===Z.accountId&&$.incarnation===Z.incarnation}function F5($,Z){if($.kind!==Z.kind)return!1;if($.kind==="model")return Z.kind==="model"&&$.model===Z.model;if($.kind==="family")return Z.kind==="family"&&$.family===Z.family;return!0}function dX($){return{requestId:$.requestId,originalUrl:$.originalUrl,requestStartedAt:$.clockNow,saw429:!1,tried:[],excludedForRequest:[],retains:[],retainedAttempts:[],excludedAttempts:[],switchedAttempts:[],switches:0}}function N4($,Z,J){return $.excludedForRequest.some((X)=>R(X.account,Z)&&F5(X.scope,J))}function g2($,Z){switch(Z.type){case"response":{let J=$.tried.some((X)=>R(X.account,Z.account)&&F5(X.scope,Z.scope))?$.tried:[...$.tried,{account:{...Z.account},scope:{...Z.scope}}];return{...$,tried:J,saw429:$.saw429||Z.status===429,...Z.kind==="payment-balance"?{sawPaymentBalance:!0}:{},lastStatus:Z.status}}case"retain":{if(Z.cause==="credential-recovery"||$.retainedAttempts.includes(Z.attemptId))return $;let J=$.retains.find((X)=>R(X.account,Z.account));return{...$,retainedAttempts:[...$.retainedAttempts,Z.attemptId],retains:[...$.retains.filter((X)=>!R(X.account,Z.account)),{account:{...Z.account},count:(J?.count??0)+1,startedAt:J?.startedAt??Z.clockNow,lastRetainedAt:Z.clockNow}]}}case"exclude":if($.excludedAttempts.includes(Z.attemptId))return $;return{...$,excludedAttempts:[...$.excludedAttempts,Z.attemptId],excludedForRequest:N4($,Z.account,Z.scope)?$.excludedForRequest:[...$.excludedForRequest,{account:{...Z.account},scope:{...Z.scope}}]};case"switch":return $.switchedAttempts.includes(Z.attemptId)?$:{...$,switchedAttempts:[...$.switchedAttempts,Z.attemptId],switches:$.switches+1};case"blocked":return $.blockedSince===void 0?{...$,blockedSince:Z.clockNow}:$;case"selected":{let{blockedSince:J,...X}=$;return X}}}var G9=Object.freeze({refundHybridToken:!0,cancelDiscardedBody:!0,addMark:!1,addCooldown:!1,penalizeHealth:!1,chargeSwitch:!1});function V2($){return $!==void 0&&Number.isFinite($)&&$>=0?$:300000}function D4(){let $=new Map;return{get size(){return $.size},recordAccepted(Z){if(!R(Z.accountKey,Z.currentAccountKey)||!Number.isFinite(Z.lastAcceptedAt))return!1;let J=$.get(Z.sessionId);if(J&&J.lastAcceptedAt>Z.lastAcceptedAt)return!1;let X=typeof Z.ttlMs==="number"?[Z.ttlMs]:Z.ttlMs,z=X?.length?Math.max(...X.map(V2)):V2(void 0);if($.set(Z.sessionId,Object.freeze({accountKey:Object.freeze({...Z.accountKey}),lastAcceptedAt:Z.lastAcceptedAt,ttlMs:z})),$.size>256){let G,Q=Number.POSITIVE_INFINITY;for(let[Y,B]of $)if(B.lastAcceptedAt<Q)G=Y,Q=B.lastAcceptedAt;if(G!==void 0)$.delete(G)}return!0},get(Z){return $.get(Z)},forgetSession(Z){$.delete(Z)}}}function P4($,Z,J){switch($.kind){case"pool":return!0;case"family":return J(Z)===$.family;case"model":return $.model===Z}}var j1=3621000;function m0($){return $===0||$===15||$==="max"?$:15}function F1($){let Z=m0($.maxSameAccountWait),J=$.activity;if(Z===0||!J||!R(J.accountKey,$.accountKey)||!Number.isFinite(J.lastAcceptedAt))return;let X=V2(J.ttlMs),z=J.lastAcceptedAt+X;if(X===0||!Number.isFinite(z))return;return{cacheExpiresAt:z,maxWaitMs:Z==="max"?Number.POSITIVE_INFINITY:900000}}import{createHash as cX}from"node:crypto";function Q9($,Z){let J=cX("sha256").update($).digest().readUInt32BE(0);return 1000*(Math.max(1,Math.ceil(Z/1000))+J%21)}var K5=691200000;function M4($,Z){return N5($,Z,!1)}function N5($,Z,J){if(!Number.isFinite($.maxAgeMs)||$.maxAgeMs<0)return;let X;for(let z of $.candidates){if(!R(z.account,z.readingAccount)||z.identity!==void 0&&z.readingIdentity!==void 0&&z.identity!==z.readingIdentity){if(J)return;continue}let G=z.windows.filter((W)=>W.blockedBy&&P4(W.scope,$.effectiveModel,$.familyOf));if(!G.length){if(J)return;continue}let Q=G.map((W)=>{let H=W.reset,V=H?.observedAt??H?.checkedAt;return H&&V!==void 0&&Number.isFinite(V)&&Z-V<=$.maxAgeMs&&Number.isFinite(H.at)&&H.at>Z?H.at:void 0});if(Q.some((W)=>W===void 0)){if(J)return;continue}let Y=Math.max(...Q);if(X&&X.resetAt<=Y)continue;let B=G.some((W)=>W.blockedBy!=="exhausted"&&W.reset?.at===Y);X={account:z.account,resetAt:Y,checkpoint:{accountKey:{...z.account},decidedAt:Z,blockers:B?[]:G.flatMap((W)=>W.blockedBy==="exhausted"&&W.reset?[{window:W.window,resetAt:W.reset.at}]:[])}}}return X}function D5($,Z){return $.source==="pool"&&$.reason==="quota"&&Z.terminalMetadata==="setting-capped-fresh"}function P5($,Z){let J=$.scan,X=J?.waitForReset?.jitterMs;if($.reason!=="quota"||!J||X===void 0||!Number.isInteger(X)||X<0)return;let z=N5(J,Z,!0);if(!z)return;return{kept:z,delayMs:Math.ceil((z.resetAt-Z)/1000)*1000+X}}function M5($,Z,J){return D5($,Z)&&m0($.scan?.maxSameAccountWait)===0&&!P5($,J)}function C5($,Z,J,X){let z=P5(X,$.now);if(!z&&!D5(X,Z))return;let G=X.scan,Q=m0(G?.maxSameAccountWait),Y=z?.kept??(G&&M4(G,$.now)),B=Y?Y.resetAt-$.now:300000,W=G?.activity,H=G?.accountKey??$.attempted,V=W&&H&&R(W.accountKey,H)?V2(W.ttlMs)||300000:300000,U=z?.delayMs??Math.min(B,Q==="max"?V:900000),j=!z&&Q===0||$.host==="pi"&&$.wake?.kind==="terminal",q=j?Y?B:void 0:U,F=Z.refusals.quota[$.host],K={action:"refuse",reason:"quota",family:$.host==="pi"?"pi-final":j?"json-412":F.family,messageKey:X.messageKey??F.messageKey,retryable:$.host!=="pi"&&!j,hostRetry:$.host==="pi"||j?"veto":"leave",history:J,...q===void 0?{}:{retryAfterMs:q},...Y?{resetAt:Y.resetAt}:{}};if(!Y||j||$.host==="opencode1")return K;let N={delayMs:U,retryAfterMs:U,resetAt:Y.resetAt,target:$.now+U,checkpoint:Y.checkpoint,waitKind:"terminal",reason:"terminal-quota",retryable:!0,hostRetry:"leave",history:J};if($.host==="pi")return{...N,action:"wait-then-reselect"};if($.hostPhase!=="retry")return K;if($.remainingRetries!==void 0&&$.remainingRetries<1)return{action:"pass",reason:"host-retries-exhausted",retryable:!0,hostRetry:"leave",history:J};if($.remainingRetries===void 0||z&&Number.isNaN($.remainingRetries)||U>(z?K5:j1))return K;return{...N,action:"hold",account:Y.account}}function B9($,Z,J){return{accountKey:{...$},decidedAt:Z,blockers:J.filter((X)=>X.confirmed&&Number.isFinite(X.resetAt)).map((X)=>({window:X.window,resetAt:X.resetAt}))}}function T5($,Z,J,X){let{checkpoint:z,target:G}=$;if(!R(Z,z.accountKey)||!Number.isFinite(G)||!Number.isFinite(z.decidedAt)||G<z.decidedAt||!Number.isFinite(X)||X<G)return[];let Q=(Y)=>{let B=Y.resetAt;return Y.confirmed&&B!==void 0&&Number.isFinite(B)&&B<=G&&z.blockers.some((W)=>W.window===Y.window&&Number.isFinite(W.resetAt)&&B<=W.resetAt)};return J.filter((Y)=>Q(Y)&&J.filter((B)=>B.confirmed&&B.window===Y.window).every(Q)).map((Y)=>Y.window)}function C4($,Z){return $!==void 0&&Number.isFinite($)&&$>Z}function f2($,Z){return Z.execution==="engine"&&$.phase==="after-limit"?"veto":"leave"}function k0($,Z,J,X,z){let G=z&&C5($,Z,J,z);if(G)return G;let Q=Z.refusals[X][$.host];return{action:"refuse",reason:X,family:z?.family??Q.family,messageKey:z?.messageKey??Q.messageKey,retryable:z?.retryable??Q.retryable,hostRetry:z?.hostRetry??Q.hostRetry,history:J,...z?.retryAfterMs===void 0?{}:{retryAfterMs:z.retryAfterMs},...z?.resetAt===void 0?{}:{resetAt:z.resetAt}}}function sX($,Z,J,X,z){let G=$.hold;if(Z.shortLimit.holdBound==="disabled"||$.host==="opencode2"&&($.hostPhase!=="retry"||$.remainingRetries===void 0||!($.remainingRetries>=1))||!X?.admitted||!G||G.maxWaitMs<=0||Number.isNaN(G.maxWaitMs)||!Number.isFinite(G.cacheExpiresAt)||G.maxDelayMs!==void 0&&(!Number.isFinite(G.maxDelayMs)||G.maxDelayMs<0)||!z.length||z.some((W)=>!C4(W.resetAt,$.now)))return;let Q=Math.max(...z.map((W)=>W.resetAt)),Y=Z.shortLimit.jitter==="session-sha256"?Q9($.sessionId,Q-$.now):Q-$.now,B=$.now+Y;if(!Number.isFinite(B)||B>Math.min(G.cacheExpiresAt,$.now+G.maxWaitMs)||$.host==="opencode2"&&Y>j1||G.maxDelayMs!==void 0&&Y>G.maxDelayMs)return;return{action:"hold",account:X.account,delayMs:Y,retryAfterMs:Y,target:B,checkpoint:B9(X.account,$.now,z),reason:"confirmed-limit",retryable:!0,hostRetry:$.phase==="pre-send"?"leave":f2($,Z),history:J}}function nX($,Z,J,X){let z=Z.poolWaiting;if(z.kind==="off"||!X.length)return;J=g2(J,{type:"blocked",clockNow:$.clockNow});let Q=X.map((j)=>{let q=j.blockers.filter((F)=>!(F.kind==="soft"&&X.length===1&&z.singleEligibleSoftExemption));if(q.some((F)=>!C4(F.until,$.now)))return;return q.length?{candidate:j,time:Math.max(...q.map((F)=>F.until))}:void 0}).filter((j)=>j!==void 0).reduce((j,q)=>!j||q.time<j.time?q:j,void 0),Y=Q?Q.time-$.now:X.some((j)=>j.blockers.some((q)=>q.kind!=="soft"))?z.hardFallbackMs:void 0,B=$.poolWaitBudgetMs??z.budgetMs,W=$.clockNow-(J.blockedSince??$.clockNow);if(B>0&&(W>=B||Y!==void 0&&Y>B))return k0($,Z,J,"quota",$.terminal);let H=z.requestDeadlineMs-($.clockNow-J.requestStartedAt);if(H<=0)return k0($,Z,J,"incomplete");if(Y===void 0)return k0($,Z,J,"quota",$.terminal);let V=Math.min(Y,H,B>0?B-W:Number.POSITIVE_INFINITY),U=Q?.candidate??X[0];if(!U)return;return{action:"wait-then-reselect",delayMs:V,target:$.now+V,checkpoint:B9(U.account,$.now,U.confirmedBlockers??[]),reason:"pool-blocked",retryable:!0,hostRetry:f2($,Z),history:J}}function Y9($,Z){let J=$.history,X=(C,L=$.phase==="pre-send"?!0:$.failureRetryable??!0,A="leave")=>({action:"pass",reason:C,retryable:L,hostRetry:A,history:J});if($.phase==="after-limit"&&$.host==="opencode2"&&(!$.delivery.owned||!$.delivery.attributable))return X("not-owned");let z=$.status??$.signal?.status;if($.phase==="after-limit"&&$.attempted)J=g2(J,{type:"response",account:$.attempted,scope:$.requestScope,status:z,kind:Z.terminalStatusHistory?.paymentBalance&&$.signalApplicable!==!1&&$.signal&&R($.signal.account,$.attempted)?$.signal.kind:void 0});if($.phase==="after-limit"&&!$.delivery.replayable)return X("unsafe-output",!1,"veto");let G=$.candidates.filter((C)=>C.admitted),Q=G.filter((C)=>!N4(J,C.account,$.requestScope)),Y=Q.find((C)=>$.attempted&&R(C.account,$.attempted)),B=$.signalApplicable!==!1&&$.signal&&$.attempted&&R($.signal.account,$.attempted)?$.signal:void 0;if(Z.requestExclusion==="on"&&B?.kind==="model-unavailable"&&Y)return{action:"exclude-for-request",account:Y.account,scope:$.requestScope,effects:G9,reason:"model-unavailable",retryable:!0,hostRetry:f2($,Z),history:J};if(G.length&&!Q.length)return k0($,Z,J,"model-unavailable");if($.host==="opencode2"&&$.hostPhase==="retry"&&Z.execution==="host"&&$.remainingRetries!==void 0&&$.remainingRetries<1)return $.terminal&&($.terminal.retryable===!1||M5($.terminal,Z,$.now))?k0($,Z,J,$.terminal.reason,$.terminal):X("host-retries-exhausted");if($.wake&&$.phase==="pre-send"){let C=$.wake,L=Q.find((c)=>R(c.account,C.checkpoint.accountKey)),A=L?.confirmedBlockers??(L&&B&&R(B.account,L.account)?B.windows:[]),x=L?T5(C,L.account,A,$.now):[],I=$.hold,f=C.kind==="terminal"||I!==void 0&&Number.isFinite(I.cacheExpiresAt)&&$.now<=I.cacheExpiresAt&&C.target<=I.cacheExpiresAt&&I.maxWaitMs>0&&C.target-C.checkpoint.decidedAt<=I.maxWaitMs;if(L&&Number.isFinite(C.target)&&C.target>=C.checkpoint.decidedAt&&$.now>=C.target&&f&&L.blockers.every((c)=>c.until!==void 0&&Number.isFinite(c.until)&&c.until<=$.now)&&(L.ready||A.some((c)=>c.confirmed))&&A.filter((c)=>c.confirmed).every((c)=>x.includes(c.window)))return{action:"retain",account:L.account,liftedWindows:x,reason:"wait-elapsed",retryable:!0,hostRetry:"leave",history:g2(J,{type:"selected"})}}if($.credentialRecovery&&Y)return{action:"retain",account:Y.account,reason:"credential-recovery",...$.credentialRecovery.retryMs===void 0?{}:{retryMs:$.credentialRecovery.retryMs},retryable:!0,hostRetry:f2($,Z),history:J};let W=Z.unconfirmedRetainLimit,H=$.unconfirmedRetainCount,V=z===429&&W!==void 0&&H!==void 0,U=Z.advance[$.host];if($.phase==="after-limit"&&Z.terminalStatusHistory?.paymentBalance&&(B?.kind==="payment-cap"||z===402&&B?.kind!=="payment-balance"))return X("unhandled-failure");if($.phase==="after-limit"&&!B&&!V&&!$.terminal&&(U.attributedLimitOnly||z===void 0||!U.statuses.includes(z)))return X("unhandled-failure");let j=Q.find((C)=>$.selection&&R(C.account,$.selection.account)&&C.placementEligible),q=j&&(j.ready||Z.poolWaiting.kind==="earliest"&&Z.poolWaiting.singleEligibleSoftExemption&&Q.length===1&&j.blockers.length>0&&j.blockers.every((C)=>C.kind==="soft")),F=q&&(!$.attempted||!R(j.account,$.attempted))?j:void 0,K=(C,L="ready-alternative")=>({action:"reroute",account:C.account,pin:$.selection?.pin??"preserve",reason:L,retryable:!0,hostRetry:f2($,Z),history:g2(J,{type:"selected"})}),N=$.phase==="pre-send"?Y??Q.find((C)=>$.selection&&R(C.account,$.selection.account)):Y,D=(N?.confirmedBlockers??($.phase==="after-limit"?B?.windows:void 0)??[]).filter((C)=>C.confirmed);if(D.length){if(Z.shortLimit.preference==="ready-alternative-first"&&F)return K(F);let C=sX($,Z,J,N,D);if(C)return C}let T=Z.unknown[$.host],M=$.phase==="after-limit"&&!D.length&&(z===429||B?.kind==="rate-limit"||B?.kind==="quota-exhausted"||B?.kind==="capacity"),P=V&&H>=W;if(M&&Y&&(T.affinity==="always"||$.affinity==="sticky")){if(V&&P){if(F)return K(F,"unconfirmed-retry-limit")}else if(V||T.action==="retain"){let C=[...$.retryHintsMs??[],B?.retryAfterMs].filter((L)=>L!==void 0&&Number.isFinite(L)&&(V||L>=0));return{action:"retain",account:Y.account,reason:"unconfirmed-limit",...V?{retryMs:Math.min(60000,...C.map((L)=>Math.max(0,L))),incrementUnconfirmedRetain:!0}:T.hint==="minimum"?{retryMs:Math.min(T.defaultMs,...C)}:{},retryable:!0,hostRetry:f2($,Z),history:J}}else if(T.action==="pass")return X("unconfirmed-limit")}if(F)return K(F);if($.phase==="pre-send"&&q)return K(j);if($.host==="opencode2"&&$.hostPhase==="request"&&Z.markedPool.requestEscape==="ignore-timed-marks-if-all-marked"&&j&&Q.every((C)=>!C.ready)&&Q.every((C)=>C.blockers.length>0&&C.blockers.every((L)=>L.kind==="hard")))return K(j);let O=nX($,Z,J,Q);if(O)return O;if($.phase==="pre-send"&&!Q.length)return k0($,Z,J,$.terminal?.reason??"auth",$.terminal);if($.host==="opencode2"&&$.hostPhase==="retry"&&!$.terminal){if(Z.markedPool.retryExhaustion==="host-delay")return X("host-delay");if(Z.markedPool.retryExhaustion==="same-host-delay"&&Y)return{action:"retain",account:Y.account,reason:"host-delay",retryable:!0,hostRetry:"leave",history:J}}if(Z.terminalPolicy==="status-history"&&Z.terminalStatusHistory&&$.host!=="opencode2"&&!$.terminal){let C=$.phase==="pre-send"&&Q.length>0&&Q.every((x)=>!x.ready),L=Q.filter((x)=>x.placementEligible),A=$.phase==="pre-send"&&Z.terminalStatusHistory.paymentBalance&&L.length>0&&L.every((x)=>!x.ready&&x.blockers.length>0&&x.blockers.every((I)=>I.cause==="payment-balance"&&C4(I.until,$.now)));if(A||C||z===401&&J.saw429||Z.terminalStatusHistory.paymentBalance&&J.saw429&&J.sawPaymentBalance){let x=(A?L:Q).flatMap((I)=>I.blockers.map((f)=>f.until)).filter((I)=>C4(I,$.now));return k0($,Z,J,"quota",{source:"pool",reason:"quota",...A?Z.terminalStatusHistory.paymentBalance:{},retryAfterMs:x.length?Math.max(Z.terminalStatusHistory.minRetryMs,Math.min(...x)-$.now):Z.terminalStatusHistory.defaultRetryMs})}return X("original-response")}if($.terminal)return k0($,Z,J,$.terminal.reason,$.terminal);if(B?.kind==="auth"||B?.kind==="account-access")return k0($,Z,J,"auth");if(B||z===429||Q.some((C)=>C.blockers.length))return k0($,Z,J,"quota");return X("no-override")}function v2($){if(!Number.isFinite($))return"unknown";let Z=Math.ceil(Math.max(0,$)/1000);if(Z<60)return`${Z}s`;let J=Math.ceil(Z/60),X=Math.floor(J/1440);if(X>=100)return"over 99 days";let z=Math.floor(J/60)%24,G=J%60;if(X>0)return`${X}d ${z}h ${G}m`;if(z>0)return`${z}h ${G}m`;return`${G}m`}var h2=({resetAt:$,now:Z})=>v2($-Z);var V9=Symbol.for("@cortexkit/common-auth/limits-envelope-error");class N1 extends Error{[V9]="conflict";constructor(){super("Conflicting limits envelope writers");this.name="LimitsEnvelopeConflictError"}}class D1 extends Error{[V9]="unsupported";constructor(){super("Invalid or unsupported limits namespace schema");this.name="LimitsEnvelopeUnsupportedError"}}function H9($){let Z=$&&typeof $==="object"&&Reflect.get($,V9);return Z==="conflict"||Z==="unsupported"?Z:void 0}function w0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}var H2=($)=>Number.isSafeInteger($)&&$>=0,W9=($)=>typeof $==="number"&&Number.isFinite($),L5=($)=>$===void 0||$==="rate-limit"||$==="payment-balance",K1=($,Z)=>Array.isArray($)&&$.every(Z);function _5($,Z){return w0($)&&$.namespace===Z&&typeof $.accountId==="string"&&typeof $.incarnation==="string"}function O5($,Z){if(!w0($)||!w0($.scope))return!1;let J=$.scope;return _5($.account,Z)&&typeof $.window==="string"&&(J.kind==="pool"||J.kind==="family"&&typeof J.family==="string"||J.kind==="model"&&typeof J.model==="string")}function aX($,Z){return $.namespace===Z&&typeof $.generation==="string"&&H2($.revision)&&H2($.lowWatermark)&&K1($.marks,(J)=>w0(J)&&O5(J.key,Z)&&["latest-evidence","max-until","overwrite"].includes(J.mergeLaw)&&K1(J.entries,(X)=>w0(X)&&L5(X.cause)&&W9(X.until)&&W9(X.evidenceAt)&&H2(X.baseRevision)&&H2(X.committedRevision)))&&K1($.tombstones,(J)=>w0(J)&&O5(J.key,Z)&&H2(J.revision)&&L5(J.cause))&&K1($.operationIds,(J)=>w0(J)&&typeof J.producerId==="string"&&typeof J.operationId==="string"&&H2(J.revision))&&K1($.access,(J)=>w0(J)&&_5(J.account,Z)&&W9(J.eligibilityStateUpdatedAt)&&H2(J.committedRevision))}class P1{namespace;logger;replaced=!1;terminal;constructor($,Z){this.namespace=$,this.logger=Z}assertWritable(){if(this.terminal)throw this.terminal}decode($){if(this.assertWritable(),$===void 0)return{};let Z;if(!w0($))Z="malformed";else if($.schemaVersion!==1)throw this.terminal=new D1,this.terminal;else if(typeof $.namespace==="string"&&$.namespace!==this.namespace)Z="foreign-namespace";else if(!aX($,this.namespace))Z="malformed";if(!Z)return{snapshot:$};if(this.replaced)throw this.terminal=new N1,this.terminal;return{replacement:Z}}didCommit($){if(!$||this.replaced)return!1;this.replaced=!0;try{this.logger?.warn(`limits envelope replaced: ${$}`)}catch{}return!0}}var iX=[/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],rX=new RegExp(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","stream disconnected before completion","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"].join("|"),"i");function m2($){let Z=$.toLowerCase();return Z.includes("too_many_requests")||Z.includes("exhausted")||Z.includes("unavailable")||iX.some((J)=>J.test($))||rX.test($)}class T4 extends Error{messageKey;code="unsafe-wording";constructor($){super(`Unsafe refusal template: ${$}`);this.messageKey=$,this.name="UnsafeWordingError"}}function U9($){let Z=new Map(Object.entries($.refusals??{})),J=new Map(Object.entries($.retryable??{}));for(let[X,z]of Z)for(let G of[void 0,"45s","2m","1h 30m","99d 23h 59m","over 99 days"])for(let Q of[[],["this account"]]){let Y=Object.freeze({labels:Object.freeze(Q),reset:G}),B;try{B=z(Y)}catch{throw new T4(X)}if(typeof B!=="string"||m2(B))throw new T4(X)}return Object.freeze({formatReset:$.formatReset,render:(X,z,G)=>(G?Z:J).get(X)?.(z)})}var oX=/[^\s@]+@[^\s@]+\.[^\s@]+/;function q9($){return oX.test($)}function j9($){return q9($)||m2($)?"this account":$}class F9 extends Error{code="ECONNRESET";syscall="sticky-routing";isRetryable=!0;constructor($){super($,{cause:{code:"ECONNRESET",syscall:"sticky-routing"}});this.name="ClaudeIncompleteError"}}function L4($,Z=0){if($===void 0||!Number.isFinite($)||$<0)return;let J=$-K9(Z);return J>=0?Math.ceil(J/1000):void 0}function K9($){return Number.isFinite($)&&$>=0?$:0}function A5($){return $.resetAt!==void 0&&Number.isFinite($.resetAt)?$.resetAt:void 0}function tX($){return $===void 0?"The reset is unknown.":`Reset at ${$}.`}function E5($,Z,J,X){let z=!X&&J!==void 0?` Retry in ${v2(J*1000)}.`:"";return`${$==="pi-final"?"The request cannot continue.":"No account is available."}${z} ${tX(Z)}`}function R5($,Z,J){let X=A5($),z=X===void 0?void 0:h2({resetAt:X,now:Z}),G=L4($.retryAfterMs,$.noticeDelayMs);return E5($.family,z,G,J)}function eX($,Z){let J=$.now+K9($.noticeDelayMs??0),X=()=>R5($,J,Z);try{let z=A5($),G=z===void 0?void 0:($.messages?.formatReset??h2)({resetAt:z,now:J}),Q=L4($.retryAfterMs,$.noticeDelayMs),Y=Object.freeze({labels:Object.freeze($.labelPolicy==="relogin"?($.parameters?.labels??[]).map(j9):[]),reset:G,retryIn:!Z&&Q!==void 0?v2(Q*1000):void 0}),B=$.messages?.render($.messageKey,Y,Z);return typeof B==="string"?B:E5($.family,G,Q,Z)}catch{return X()}}function S5($,Z){switch($){case"openai-429":return JSON.stringify({error:{message:Z,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}});case"claude-429":return JSON.stringify({type:"error",error:{type:"rate_limit_error",message:Z}});case"json-412":return JSON.stringify({error:{code:412,status:"FAILED_PRECONDITION",message:Z}});case"claustrum-429":return JSON.stringify({error:"claustrum-auth: accounts-rate-limited"});case"claustrum-402":return JSON.stringify({error:"claustrum-auth: insufficient balance"});default:return Z}}function N9($){let Z=$.family==="json-412"||$.family==="pi-final",J={family:$.family,disposition:"refuse",retryable:!Z,hostRetry:Z||$.host==="opencode2"?"veto":"leave"},X=S5($.family,eX($,Z));if(Z&&(m2(X)||q9(X))){let Q=$.now+K9($.noticeDelayMs??0);X=S5($.family,R5($,Q,!0))}if($.family==="claude-econnreset")return{...J,kind:"throw",error:new F9(X)};if($.family==="pi-final")return{...J,kind:"text",body:X};let z=new Headers($.family==="json-412"?$.extraHeaders:void 0);z.set("content-type","application/json"),z.delete("retry-after");let G=L4($.retryAfterMs,$.noticeDelayMs);if(G!==void 0)z.set("retry-after",String(G));return{...J,kind:"http",status:$.family==="json-412"?412:$.family==="claustrum-402"?402:429,headers:z,body:X}}function u0($,Z){return R($.account,Z.account)&&($.identity===void 0||Z.identity===void 0||$.identity===Z.identity)}function D9($,Z){if(!u0($,Z))return Z;return{...Z,identity:Z.identity??$.identity}}function P9($,Z,J){if(!u0($,Z))return"identity-replaced";if(!J($,Z))return"credential-epoch";return}var M9=Object.freeze({kind:"failure-ladder",mergeLaw:"max-until",hintFloorMs:2000,quotaSteps:Object.freeze([60000,300000,1800000,7200000]),byKind:Object.freeze({"rate-limit":30000}),byReason:Object.freeze({"server-error":20000,unknown:60000}),capacity:Object.freeze({baseMs:45000,spreadMs:15000}),defaultMs:60000});function O4($,Z,J,X=0){let z=Z.filter((G)=>G.baseRevision>=X);if($!=="max-until"){let G=z.reduce((Q,Y)=>{if(!Q)return Y;if($==="latest-evidence"&&Y.evidenceAt!==Q.evidenceAt)return Y.evidenceAt>Q.evidenceAt?Y:Q;return Y.committedRevision>Q.committedRevision?Y:Q},void 0);return G&&J<G.until?[G]:[]}return z.filter((G,Q)=>J<G.until&&!z.some((Y,B)=>B!==Q&&Y.until>=G.until&&Y.baseRevision>=G.baseRevision&&(Y.until>G.until||Y.baseRevision>G.baseRevision||Y.committedRevision>G.committedRevision||Y.committedRevision===G.committedRevision&&B<Q))).sort((G,Q)=>G.committedRevision-Q.committedRevision)}function M1($,Z){if($.eligibilityStateUpdatedAt!==Z.eligibilityStateUpdatedAt)return $.eligibilityStateUpdatedAt>Z.eligibilityStateUpdatedAt?$:Z;return $.committedRevision>Z.committedRevision?$:Z}var b5=1024;function C9($){return $==="rate-limit"||$==="payment-balance"?$:void 0}function _4($,Z){return C9($.cause)===void 0||$.cause===Z}function k5($){return JSON.stringify([p($.key),C9($.cause)])}function T0($,Z){return{schemaVersion:1,namespace:$,generation:Z,revision:0,lowWatermark:0,marks:[],tombstones:[],operationIds:[],access:[]}}function Zz($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function p($){let Z=$.scope;return JSON.stringify([Zz($.account),Z.kind,Z.kind==="model"?Z.model:Z.kind==="family"?Z.family:null,$.window])}function I5($){return JSON.stringify([$.producerId,$.operationId])}function U2($,Z){let J=new Map;for(let B of $.tombstones){let W=p(B.key),H=J.get(W);if(H)H.push(B);else J.set(W,[B])}let X=$.marks.flatMap((B)=>{let W=J.get(p(B.key)),H=O4(B.mergeLaw,W?B.entries.filter((V)=>!W.some((U)=>_4(U,V.cause)&&V.baseRevision<U.revision)):B.entries,Z);return H.length?[{...B,entries:H}]:[]}),z=$.lowWatermark,G=(B)=>{let W=[...B].sort((V,U)=>V.revision-U.revision),H=Math.max(0,W.length-b5);for(let V of W.slice(0,H))z=Math.max(z,V.revision+1);return W.slice(H)},Q=G($.tombstones),Y=G($.operationIds);return{...$,revision:Math.max($.revision,z),marks:X,tombstones:Q,operationIds:Y,lowWatermark:z}}function q2($,Z,J){let X=U2($,J.now),z=[];for(let G of Z){let Q=(K)=>{z.push({producerId:G.producerId,operationId:G.operationId,status:"rejected",reason:K})};if(G.binding.account.namespace!==X.namespace){Q("wrong-namespace");continue}if(G.baseRevision<X.lowWatermark){Q("below-watermark");continue}if(G.baseRevision>X.revision){Q("future-revision");continue}let Y=J.bindings.find((K)=>R(K.account,G.binding.account));if(!Y){Q("unknown-account");continue}let B=P9(G.binding,Y,J.authorizeEpoch);if(B){Q(B);continue}let W=X.operationIds.find((K)=>I5(K)===I5(G));if(W){z.push({...W,status:"duplicate"});continue}let H=Y.account,V=X.revision+1,U=[...X.marks],j=[...X.tombstones],q=[...X.access];if(G.type==="mark"){let K={account:H,scope:G.scope,window:G.window},N=p(K),D=U.find((M)=>p(M.key)===N);if(j.some((M)=>G.baseRevision<M.revision&&_4(M,G.cause)&&p(M.key)===N)){Q("cleared");continue}if(D&&D.mergeLaw!==G.mergeLaw){Q("merge-law-conflict");continue}let T=O4(G.mergeLaw,[...D?.entries??[],{until:G.until,evidenceAt:G.evidenceAt,baseRevision:G.baseRevision,committedRevision:V,...G.cause==="rate-limit"||G.cause==="payment-balance"?{cause:G.cause}:{}}],J.now);if(U=U.filter((M)=>p(M.key)!==N),T.length)U.push({key:K,mergeLaw:G.mergeLaw,entries:T})}else if(G.type==="clear"){let K=C9(G.cause),N=G.keys.map((M)=>({...M,account:H})).filter((M)=>G.cause===void 0||!U.some((P)=>p(P.key)===p(M)&&P.entries.some((O)=>O.cause!==G.cause))),D=new Set(N.map(p)),T=G.evidenceAt;if(T!==void 0&&U.some((M)=>D.has(p(M.key))&&M.entries.some((P)=>P.evidenceAt>T))){Q("newer-evidence");continue}U=U.filter((M)=>!D.has(p(M.key))),j=j.filter((M)=>!D.has(p(M.key))||K!==void 0&&M.cause!==K);for(let M of new Map(N.map((P)=>[p(P),P])).values())j.push({key:M,revision:V,...K===void 0?{}:{cause:K}})}else{let K={account:H,state:G.state,eligibilityStateUpdatedAt:G.eligibilityStateUpdatedAt,committedRevision:V},N=q.find((D)=>R(D.account,H));q=q.filter((D)=>!R(D.account,H)),q.push(N?M1(N,K):K)}let F={producerId:G.producerId,operationId:G.operationId,revision:V};X=U2({...X,revision:V,marks:U,tombstones:j,access:q,operationIds:[...X.operationIds,F]},J.now),z.push({...F,status:"committed"})}return{snapshot:X,outcomes:z}}import{realpathSync as Jz}from"node:fs";import{basename as x5,dirname as y5,join as Xz,resolve as zz}from"node:path";function C1($){let Z=zz($),J=[x5(Z)],X=y5(Z);for(;;)try{return Xz(Jz.native(X),...J.reverse())}catch(z){let G=z.code;if(G!=="ENOENT"&&G!=="ENOTDIR")throw z;let Q=y5(X);if(Q===X)return Z;J.push(x5(X)),X=Q}}class L0 extends Error{code;constructor($){super($);this.code=$,this.name="LimitsPersistenceRefusal"}}import{randomUUID as Yz}from"node:crypto";import{isDeepStrictEqual as f5}from"node:util";import{AsyncResource as Gz}from"node:async_hooks";import{randomUUID as g5}from"node:crypto";import{isDeepStrictEqual as Qz}from"node:util";var Bz=new Gz("common-auth-limits-recovery");class T1{logger;running;listeners=new Set;constructor($){this.logger=$}subscribe=($)=>{return this.listeners.add($),()=>this.listeners.delete($)};schedule($){if(this.running)return;this.running=Bz.runInAsyncScope(async()=>{await Promise.resolve();let Z=!1;try{await $(),Z=!0}catch(J){try{this.logger?.warn("limits envelope recovery failed; agreement remains degraded",{error:J instanceof Error?J.message:String(J)})}catch{}}finally{if(this.running=void 0,Z)for(let J of this.listeners)try{J()}catch{}}})}}class j2{seen;missingGeneration;incorporated;remember($,Z){if(this.seen&&this.seen.revision>$.revision)return;if(this.seen=structuredClone($),this.missingGeneration=void 0,Z)this.incorporated=structuredClone(Z)}retained($){let Z=Qz($,this.incorporated)?void 0:$;return[this.seen,Z].filter((J)=>J!==void 0&&(J===this.seen||J.revision>0))}lost($,Z){return this.retained(Z).some((J)=>!$||J.generation!==$.generation||$.revision<J.revision||J.tombstones.some((X)=>X.revision>$.lowWatermark&&!$.tombstones.some((z)=>p(z.key)===p(X.key)&&_4(z,X.cause)&&z.revision>=X.revision)))}recover($,Z,J,X){if(!$)this.missingGeneration??=g5();let z=$??T0(J,this.missingGeneration??g5()),G=[...this.retained(Z),z],Q=new Map,Y=new Map,B=new Map,W=new Map,H=0;for(let U of G){H=Math.max(H,U.revision,U.lowWatermark);for(let j of U.marks){let q=p(j.key),F=Q.get(q);if(F&&F.mergeLaw!==j.mergeLaw)throw Error("limits-recovery-merge-law-conflict");Q.set(q,{...j,entries:[...F?.entries??[],...j.entries]});for(let K of j.entries)H=Math.max(H,K.baseRevision,K.committedRevision)}for(let j of U.tombstones){let q=k5(j),F=Y.get(q);if(!F||F.revision<j.revision)Y.set(q,j);H=Math.max(H,j.revision)}for(let j of U.operationIds){let q=JSON.stringify([j.producerId,j.operationId]),F=B.get(q);if(!F||F.revision<j.revision)B.set(q,j);H=Math.max(H,j.revision)}for(let j of U.access){let{namespace:q,accountId:F,incarnation:K}=j.account,N=JSON.stringify([q,F,K]),D=W.get(N);W.set(N,D?M1(D,j):j),H=Math.max(H,j.committedRevision)}}let V=H+1;if(!Number.isSafeInteger(V))throw Error("limits-revision-exhausted");return U2({...z,revision:V,lowWatermark:V,marks:[...Q.values()],tombstones:[...Y.values()],operationIds:[...B.values()],access:[...W.values()]},X)}}function v5($,Z){return Z.flatMap((J)=>J.credentialEpoch===void 0?[]:[{account:{namespace:$,accountId:J.id,incarnation:String(J.credentialEpoch)},credentialEpoch:String(J.credentialEpoch),...J.identity===void 0?{}:{identity:J.identity}}])}async function T9($){let{store:Z,namespace:J}=$;if(!Z.updateLimitsNamespace)throw new L0("limits-unsupported");let X=Z.updateLimitsNamespace.bind(Z),z=Yz(),G=new j2,Q=new P1(J,$.logger),Y=new T1($.logger),B=$.now??Date.now,W=async()=>{let j=await Z.read();if(j.status!=="ready"){if(j.status==="error"&&j.kind==="snapshot-contended")throw Error(j.reason);throw new L0("pool-not-ready")}return v5(J,j.rows)},H=async()=>{let j=await Z.readSettings();if(j.status!=="ready")throw new L0("pool-not-ready");return Q.decode(j.settings.commonAuthLimits)},V=async(j)=>{Q.assertWritable();let q=await W(),F=await H(),K;for(let N=0;N<3;N++){let D=await W(),T=await H(),M=f5(q,D)&&f5(F,T);if(K={snapshot:F.snapshot??T0(J,z),bindings:q,authoritative:M},M){if(!F.replacement&&G.lost(F.snapshot,j))return Y.schedule(()=>U.commit([],j)),{snapshot:G.recover(F.snapshot,j,J,B()),bindings:q,authoritative:!1,degradedAgreement:!0};if(F.snapshot)G.remember(F.snapshot);return K}q=D,F=T}return K},U={namespace:J,read:V,subscribe:Y.subscribe,async commit(j,q){Q.assertWritable();let F,K,N=()=>{if(Q.didCommit(K)&&F)G=new j2,G.remember(F.snapshot,q)};try{await X((D,T)=>{let M=v5(J,T),P=Q.decode(D),O=P.snapshot;K=P.replacement;let C=!K&&G.lost(O,q),L=q2(C?G.recover(O,q,J,B()):O??T0(J,z),j,{now:B(),bindings:M,authorizeEpoch:(A,x)=>A.credentialEpoch===x.credentialEpoch});return F={...L,bindings:M,authoritative:!0,degradedAgreement:C},L.snapshot},{beforePublish:()=>Q.assertWritable(),onPublished:N})}catch(D){if(Q.assertWritable(),D instanceof b&&(D.kind==="pending-migration"||D.kind==="load-error"))throw new L0("pool-not-ready");throw D}if(!F)throw Error("Pool limits mutator was not called");return N(),G.remember(F.snapshot,q),F}};return await V(),U}function w2($){if($&&typeof $==="object"){for(let Z of Object.values($))w2(Z);Object.freeze($)}return $}function O0($){return{opencode1:$,opencode2:$,pi:$}}var F2={action:"reselect",affinity:"always",hint:"none",defaultMs:60000},h5={...F2,action:"retain",affinity:"sticky"},w5={family:"local-auth",messageKey:"auth.no-account",retryable:!1,hostRetry:"leave"};function A4($,Z){return{auth:O0(w5),quota:O0($),incomplete:O0(Z),"model-unavailable":O0({family:"json-412",messageKey:"model-unavailable",retryable:!1,hostRetry:"veto"})}}var S4={kind:"off"},u5={requestEscape:"off",retryExhaustion:"terminal"},p5={statuses:[],attributedLimitOnly:!0},m5={family:"json-412",messageKey:"quota.pool-exhausted",retryable:!1,hostRetry:"veto"},l5=w2({unconfirmedRetainLimit:2,evidence:"per-field-overlay",markers:O0({kind:"reset",mergeLaw:"latest-evidence",defaultMs:60000}),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"on",unknown:{opencode1:{...F2,action:"retain",hint:"minimum"},opencode2:F2,pi:{...F2,action:"pass"}},shortLimit:{holdBound:"cache-ttl",preference:"same-account-first",jitter:"session-sha256"},retainBound:"none",poolWaiting:S4,execution:"host",requestExclusion:"off",advance:O0(p5),markedPool:u5,terminalMetadata:"setting-capped-fresh",terminalPolicy:"provided",refusals:A4({family:"claude-429",messageKey:"quota.all-accounts",retryable:!0,hostRetry:"leave"},{family:"claude-econnreset",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),d5=w2({evidence:"typed",markers:O0(M9),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"off",unknown:O0(F2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:{kind:"earliest",budgetMs:300000,requestDeadlineMs:600000,hardFallbackMs:60000,singleEligibleSoftExemption:!0},execution:"engine",requestExclusion:"on",advance:O0({statuses:[429,503,529],attributedLimitOnly:!1}),markedPool:u5,terminalMetadata:"baseline",terminalPolicy:"pool",refusals:A4(m5,{...m5,messageKey:"incomplete.timeout"})}),$2=w2({evidence:"named-window",markers:{opencode1:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},opencode2:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},pi:S4},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:{opencode1:h5,opencode2:F2,pi:h5},shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:S4,execution:"host",requestExclusion:"off",advance:O0({statuses:[401,403,429],attributedLimitOnly:!1}),markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"same-host-delay"},terminalMetadata:"baseline",terminalPolicy:"provided",refusals:A4({family:"openai-429",messageKey:"quota.no-route",retryable:!0,hostRetry:"leave"},{family:"openai-429",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),c5=w2({evidence:"hints-only",markers:{opencode1:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"},opencode2:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"marker"},pi:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"}},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:O0(F2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:S4,execution:"host",requestExclusion:"off",advance:{opencode1:{statuses:[401,429],attributedLimitOnly:!1},opencode2:p5,pi:{statuses:[401,429],attributedLimitOnly:!1}},markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"host-delay"},terminalMetadata:"baseline",terminalPolicy:"status-history",terminalStatusHistory:{minRetryMs:1000,defaultRetryMs:60000,paymentBalance:{family:"claustrum-402",messageKey:"payment.insufficient-balance"}},refusals:A4({family:"claustrum-429",messageKey:"quota.accounts-rate-limited",retryable:!0,hostRetry:"leave"},{...w5,messageKey:"incomplete.no-account"})}),Wz=w2({"confirmed-affinity":l5,"earliest-pool-engine":d5,"window-router":$2,"status-vault-order":c5});import{AsyncResource as Vz}from"node:async_hooks";var R4=Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1"),Hz="@cortexkit/common-auth/limits-registry/schema-v",E4=1000,s5=5000,K2=new Vz("common-auth-limits"),Uz={now:()=>Date.now(),setTimeout($,Z){let J=setTimeout($,Z);return J.unref?.(),J},clearTimeout:($)=>clearTimeout($)};function qz(){for(let J of Object.getOwnPropertySymbols(globalThis))if(Symbol.keyFor(J)?.startsWith(Hz)&&J!==R4)throw Error("limits-schema-mismatch");let $=Reflect.get(globalThis,R4);if($){if($.schemaVersion!==1||!($.namespaces instanceof Map))throw Error("limits-schema-mismatch");return $}let Z={schemaVersion:1,namespaces:new Map};return Reflect.set(globalThis,R4,Z),Z}function N2($){return JSON.stringify([$.producerId,$.operationId])}class n5{adapter;clock;restrictive;listeners=new Set;owners=0;activity=D4();journal=new Map;failed=new Set;restrictions=new Map;snapshot;recoveryView;bindings=[];lastReloadAt=Number.NEGATIVE_INFINITY;lastActivity=Number.NEGATIVE_INFINITY;lastReadAttempt=Number.NEGATIVE_INFINITY;generation=0;degradedAgreement=!1;abandoned;lastFailure;dirty=!0;live=!1;publicationTimer;reloadTimer;unsubscribe;reading;writing;handoff=Promise.resolve();resolveAbandonment;abandonment=new Promise(($)=>{this.resolveAbandonment=$});constructor($){this.adapter=$.adapter,this.clock=$.clock??Uz,this.restrictive=$.isAccessRestrictive}fail($){if(this.abandoned)return;let Z=H9($);if(Z){this.abandoned=Z,this.lastFailure=$,this.live=!1,this.generation++,this.cancelTimers(),this.unsubscribe?.(),this.unsubscribe=void 0,this.journal.clear(),this.failed.clear(),this.restrictions.clear(),this.recoveryView=void 0,this.resolveAbandonment();for(let J of this.listeners)try{J.onAbandon?.(Z)}catch{}return}this.degradedAgreement=!0,this.lastFailure=$}reconcile($){if(this.abandoned)return!1;if($.snapshot.schemaVersion!==1||$.snapshot.namespace!==this.adapter.namespace)throw Error("limits-schema-mismatch");if(!$.authoritative){if($.degradedAgreement&&this.snapshot&&$.snapshot.revision>this.snapshot.revision)this.recoveryView=$;return this.fail(Error("limits-unverifiable-snapshot")),!1}if(this.snapshot&&$.snapshot.generation===this.snapshot.generation&&$.snapshot.revision<this.snapshot.revision)return!1;this.snapshot=$.snapshot,this.recoveryView=void 0,this.bindings=$.bindings.map((Z)=>{let J=this.bindings.find((X)=>R(X.account,Z.account));return J?D9(J,Z):Z});for(let[Z,J]of this.restrictions){let X=J.command,z=this.bindings.find((Q)=>R(Q.account,X.binding.account)),G=this.snapshot.access.find((Q)=>R(Q.account,X.binding.account));if(!z||!u0(z,X.binding)||X.type==="access"&&G&&G.committedRevision>J.revision&&G.eligibilityStateUpdatedAt>=X.eligibilityStateUpdatedAt)this.restrictions.delete(Z)}if($.degradedAgreement)this.fail(Error("limits-envelope-recovered"));return!$.degradedAgreement}touch(){this.lastActivity=this.clock.now(),this.armReload()}cancelTimers(){if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);if(this.reloadTimer!==void 0)this.clock.clearTimeout(this.reloadTimer);this.publicationTimer=this.reloadTimer=void 0}schedulePublish($){if(!this.live)return;if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);K2.runInAsyncScope(()=>{this.publicationTimer=this.clock.setTimeout(()=>{this.publicationTimer=void 0,K2.runInAsyncScope(()=>{this.flush()})},$)})}armReload(){if(!this.live||this.reading||this.reloadTimer!==void 0||this.clock.now()-this.lastActivity>=s5)return;K2.runInAsyncScope(()=>{this.reloadTimer=this.clock.setTimeout(()=>{if(this.reloadTimer=void 0,!this.live||this.clock.now()-this.lastActivity>=s5)return;K2.runInAsyncScope(()=>{this.reload()})},Math.max(0,this.lastReadAttempt+E4-this.clock.now()))})}async start($){if(this.abandoned)throw this.lastFailure;this.adapter=$,this.live=!0;let Z=++this.generation;if(await this.reload(),this.abandoned||!this.snapshot)throw this.lastFailure??Error("limits-hydration-failed");if(this.unsubscribe=$.subscribe?.(()=>{if(!this.live||this.generation!==Z)return;this.dirty=!0,K2.runInAsyncScope(()=>{this.reload()})}),this.journal.size)this.schedulePublish(0)}reload(){if(this.abandoned)return Promise.resolve();if(this.reading)return this.reading;let $=this.clock.now();return this.lastReadAttempt=$,this.reading=K2.runInAsyncScope(async()=>{try{if(this.dirty=!1,this.reconcile(await this.adapter.read(this.snapshot))){if(this.lastReloadAt=$,!this.journal.size&&!this.failed.size&&!this.restrictions.size)this.degradedAgreement=!1,this.lastFailure=void 0}}catch(Z){this.dirty=!0,this.fail(Z)}}).finally(()=>{this.reading=void 0,this.armReload()}),this.reading}provisional(){if(this.abandoned)return T0(this.adapter.namespace,this.snapshot?.generation??"");let $=this.recoveryView?.snapshot??this.snapshot,Z=[...this.journal.values()].map((X)=>X.command).filter((X)=>X.type==="mark"),J=q2(U2($,this.clock.now()),Z,{now:this.clock.now(),bindings:this.bindings,authorizeEpoch:(X,z)=>X.credentialEpoch===z.credentialEpoch}).snapshot;return{...this.snapshot,marks:J.marks,tombstones:$.tombstones,access:$.access}}enqueue($,Z){if(this.abandoned)return;if($.binding.account.namespace!==this.adapter.namespace)throw Error("wrong-namespace");let J=N2($);if(this.journal.has(J)||this.snapshot.operationIds.some((z)=>N2(z)===J))return;this.journal.set(J,{command:structuredClone($),event:Z}),this.touch();let X=[...this.journal.values()].some((z)=>z.command.type!=="mark");this.schedulePublish(X?0:E4)}flush(){if(this.abandoned)return this.writing??Promise.resolve();if(this.writing)return this.writing;if(!this.journal.size)return Promise.resolve();return this.writing=K2.runInAsyncScope(async()=>{let $=[...this.journal.values()];while($.length&&!this.abandoned){try{let X=await this.adapter.commit($.map((z)=>z.command),this.snapshot);if(this.abandoned)return;if(this.reconcile(X),!X.authoritative)throw Error("limits-unverifiable-commit");for(let z of $){let G=X.outcomes.find((Q)=>N2(Q)===N2(z.command));if(!G)throw Error("limits-missing-acknowledgement");this.settle(z,G)}}catch(X){if(H9(X)){this.fail(X);return}if(this.abandoned)return;if(X instanceof L0&&X.code==="pool-not-ready")for(let z of $)this.settle(z,{...z.command,status:"rejected",reason:"pool-not-ready"});else{for(let z of $)if(this.journal.has(N2(z.command)))this.failed.add(N2(z.command));this.fail(X);break}}let Z=[...this.journal.values()],J=Z.findLastIndex((X)=>X.command.type!=="mark");$=Z.slice(0,J+1)}}).finally(()=>{if(this.writing=void 0,this.journal.size&&this.live)this.schedulePublish(E4);if(this.degradedAgreement&&this.live)this.armReload()}),this.writing}settle($,Z){let J=$.command,X=N2(J);if(this.journal.delete(X),this.failed.delete(X),Z.status==="rejected"){if(this.fail(Error(Z.reason??"limits-command-rejected")),J.type==="access"&&this.restrictive(J.state)){if(this.restrictions.set(X,{command:J,revision:this.snapshot.revision}),Z.reason==="below-watermark"&&J.baseRevision<this.snapshot.lowWatermark&&($.recoveryRetries??0)<3)this.journal.set(X,{...$,recoveryRetries:($.recoveryRetries??0)+1,command:{...J,baseRevision:this.snapshot.revision}})}for(let z of this.listeners)try{z.onRejected?.(J,Z)}catch{}}else if(Z.revision!==void 0&&(J.type==="mark"||$.event==="success"))for(let z of this.listeners)try{z.onEvent?.({type:J.type==="mark"?"mark":"success",command:J,revision:Z.revision})}catch{}}async beforeDispatch($){if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};this.touch();let Z=()=>[...this.journal.values()].some((z)=>z.command.type!=="mark"&&R(z.command.binding.account,$.account));if(Z())await Promise.race([this.flush(),this.abandonment]);if(this.dirty||this.clock.now()-this.lastReloadAt>=E4)await Promise.race([this.reload(),this.abandonment]);if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};let J=(this.recoveryView?.bindings??this.bindings).find((z)=>R(z.account,$.account)),X=this.provisional();return{snapshot:X,blocked:Z()||!J||!u0(J,$)||[...this.restrictions.values()].some((z)=>R(z.command.binding.account,$.account))||[...this.snapshot.access,...X.access].some((z)=>R(z.account,$.account)&&this.restrictive(z.state))}}async stop(){this.live=!1,this.generation++,this.cancelTimers(),await this.flush(),await this.reading,this.unsubscribe?.(),this.unsubscribe=void 0,this.cancelTimers()}}async function L9($){let Z=qz(),J=Z.namespaces.get($.adapter.namespace);if(!J)J=new n5($),Z.namespaces.set($.adapter.namespace,J);let X=J,z={onAbandon:$.onAbandon,onEvent:$.onEvent,onRejected:$.onRejected},G=X.owners++===0;if(X.listeners.add(z),G)X.handoff=X.handoff.catch(()=>{}).then(()=>X.start($.adapter));try{await X.handoff}catch(B){throw X.listeners.delete(z),X.owners--,X.live=!1,X.cancelTimers(),B}let Q=!1,Y=()=>{if(Q)throw Error("limits-registry-disposed")};return{get abandoned(){return X.abandoned},get snapshot(){return Y(),X.provisional()},get lastReloadAt(){return X.lastReloadAt},get degradedAgreement(){return X.degradedAgreement},get lastFailure(){return X.lastFailure},get pendingCommands(){return X.journal.size},activity:X.activity,observe(B){return Y(),{binding:structuredClone(B),baseRevision:X.snapshot.revision}},enqueue(B,W){Y(),X.enqueue(B,W)},beforeDispatch(B){return Y(),X.beforeDispatch(B)},flush(){return Y(),X.flush()},reload(){return Y(),X.reload()},dispose(){if(Q)return X.handoff;if(Q=!0,X.owners--,!X.owners)X.handoff=X.handoff.then(()=>X.stop()).finally(()=>X.listeners.delete(z));else X.listeners.delete(z);return X.handoff}}}function Z2($){let Z=Reflect.get(globalThis,Symbol.for("cortexkit.routing"));if(typeof Z!=="function")return;let J=Z($);return typeof J==="object"&&J!==null?J:void 0}function O9($){try{let J=Z2($.sessionId);if(!J||typeof J.accountFor!=="function")return}catch{return}let Z=F1($);if(!Z||!Number.isFinite($.now))return 0;return Math.floor(Math.max(0,Math.min(Z.maxWaitMs,Z.cacheExpiresAt-$.now))/1000)}function E($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as Kz}from"node:fs";import{rm as r5}from"node:fs/promises";import{dirname as Nz,join as BZ}from"node:path";import{resolveClaustrumConnectionPath as Dz}from"@cortexkit/claustrum-client";function a5($,Z){if(!$)return;let J=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function _9($){if(!E($)||typeof $.minor!=="number"||!Number.isSafeInteger($.minor)||typeof $.exponent!=="number"||!Number.isInteger($.exponent))return;let Z=$.minor/10**$.exponent;return Number.isFinite(Z)?Z:void 0}function jz($){let Z=_9($.total),J=_9($.remaining);if(Z===void 0||J===void 0||Z<0||J<0)return;let X=Z-J,z=$.spendable===!1,G=Z>0?X/Z*100:z?100:0;return{limit:Z,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...E($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function Fz($,Z){if(!E($))return;let J=_9($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function S9($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&E(Z)&&E(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function i5($,Z){let J=a5($.usage?.primary,Z.fetchedAt);if(!J||!Number.isFinite(Z.fetchedAt))return;let X=a5($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((W)=>E(W)&&W.id==="individual_limit"):void 0,G=E(z)?jz(z):void 0,Q=Array.isArray($.spend)?$.spend.find((W)=>E(W)&&W.id==="credits"):void 0,Y=Fz(Q,Z.fetchedAt),B=E($.savedResets)?$.savedResets.availableCount:void 0;return{primary:J,...Y&&{credits:Y},...Y&&E(Q)&&typeof Q.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof B==="number"&&Number.isFinite(B)&&B>=0&&{resetCreditsAvailable:B},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function I4($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var A9="ck auth reclassify --from-registry";function b4($,Z){if(Z===void 0)return"No ChatGPT login in the vault has the `openai-native` category, or the grant is missing. Check `ck auth status` for categories and `ck auth grant` for the grant.";if(Z.grants===0)return`The vault has no grant letting ${$} read OpenAI accounts. Grant it with \`${I4($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${A9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var Y0=t("vault"),YZ="openai-auth";var Pz={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},WZ={opencode:"OpenCode",pi:"Pi"},Mz=[{selector:{category:"openai-native"},operation:"read"}];function R9($){return e5(YZ,$)}function Cz($){return`ChatGPT for ${WZ[$]}`}function v4($){return BZ(Nz($),"openai-auth-vault")}function D2($,Z){return{...ZZ({stateDir:$,host:Z}),rosterPath:BZ($,`${Z}-roster.json`)}}var VZ=2000,tq=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],Tz={"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 ${A9} 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 eq($,Z){if($!=="vault-no-grant")return Tz[$];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: ${I4(Z)}`}function $j($){let Z=$.snapshot();if(Z===void 0)return"vault-unreachable";if(Z.rows.length===0){let J=$.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function Lz($){let Z=g4($);return Z?f4(Z):void 0}class Oz{host;name;paths;#Z;#$;#B=new Map;#Y=new Map;#q=new Map;#j;#J;#W;#z;#F=!1;#K=!1;#V=Promise.withResolvers();#H="unknown";#U;constructor($){this.#Z=$,this.host=$.host,this.name=R9($.host),this.paths=D2($.stateDir,$.host),this.#$=new GZ({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:Pz,pluginId:YZ,connect:()=>this.#C(),isCustodyActive:()=>this.#L(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:Lz,insula:{provider:"codex",normalize:i5},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onDiscovery:(Z)=>this.#O(Z),onError:(Z)=>this.#X("vault roster refresh failed",Z),logger:{...Y0,warn:(Z,J)=>{if(Z!=="skipped insula provider poll")Y0.warn(Z,J)}}})}#N(){return(this.#Z.connectionFile??Dz)()}#D(){return{connectionFile:this.#N(),storagePath:this.paths.tokenPath,logger:($)=>Y0.debug("vault transport error",{errorClass:$})}}#C(){return(this.#Z.connectScoped?.()??QZ(this.#D())).then(($)=>{return this.#j=$.insula!==void 0,$})}#G($,Z,J){let X=this.#q.get($);if(X?.source===Z&&X.reason===J)return;this.#q.set($,{source:Z,reason:J}),Y0.info("vault background quota source changed",{routeId:$,source:Z,reason:J})}#T(){return this.#Z.connectEnrollment?.()??$Z(this.#D())}#X($,Z){this.#J=x0(Z),Y0.warn($,{host:this.host,error:this.#J,...Z instanceof t5&&Z.reason?{reason:Z.reason}:{}})}#Q(){if(u2())return"host";return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=Kz($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#Q(),Z=await JZ(this.paths,this.name);if($===this.#Q()){if(Z!==this.#H)Y0.info("vault authority",{host:this.host,authority:Z});return this.#H=Z,this.#U=$,Z}return"unreadable"}enrolled(){return u2()||this.#U!==this.#Q()||this.#H!=="local"}async#L(){if(this.#U!==this.#Q())await this.authority();return this.enrolled()}start(){if(this.#F||this.#K)return;this.#F=!0,this.#$.start()}#O($){if(this.#z===$)return;this.#z=$,$.finally(()=>{if(this.#z===$)this.#z=void 0;this.#V.resolve()}).catch(()=>{})}#P(){return this.#$.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(!["vault","host"].includes(await this.authority()))return;let $=this.#z;if($)await $.catch(()=>{return});if(this.snapshot()||!["vault","host"].includes(await this.authority()))return;await(this.#z??this.#P()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let $=this.#z;if($)await $.catch(()=>{return});let Z=await this.#P();return this.#J=void 0,Z}catch($){return this.#X("vault roster refresh failed",$),this.#$.snapshot()}}snapshot(){return this.#$.snapshot()}watchState(){return this.#$.watchState()}keptReceiptState(){return this.#$.keptReceiptState()}grantReach(){return this.#$.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap(($)=>$.accountIdentity!==void 0?[$.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let $=new Map((this.snapshot()?.rows??[]).map((Z)=>[Z.routeId,Z]));return this.#$.routingRows().map((Z)=>{let J=$.get(Z.id)?.accountIdentity;return{id:Z.id,credentialId:$.get(Z.id)?.credentialId,kind:Z.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...Z.quota!==void 0?{quota:Z.quota}:{}}})}owns($){return(this.snapshot()?.rows??[]).some((Z)=>Z.routeId===$)}async send($,Z,J){let X=!1;try{return await this.#$.send($,(z)=>{return X=!0,Z(z.accessToken,z)},{site:J.site,...J.signal?{signal:J.signal}:{}})}catch(z){if(X)throw z;this.#X("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#$.authorize($,Z.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure($,Z){if(Z!==401)return;try{await this.#$.reportFailure($,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot($,Z,J,X){let z=k4(Z,(this.#Z.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#$.recordQuota($,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}reportUsage($,Z,J){try{let X;if("headers"in Z){let z={};if(Z.headers.forEach((G,Q)=>{if(Q.startsWith("x-codex-"))z[Q]=G}),Object.keys(z).length===0)return;X={headers:z}}else X={frame:Z.frame};this.#$.reportUsage({routeId:$,credentialId:J.credentialId,reading:{provider:"codex",observedAtMs:(this.#Z.now??Date.now)(),...X,...J.accountIdentity?{account:J.accountIdentity}:{}}})}catch{}}pollQuota($,Z=!0){let J=this.#Y.get($);if(J)return J;let X=this.#_($,Z).finally(()=>{this.#Y.delete($)});return this.#Y.set($,X),X}async#_($,Z){if(Z){await this.authority(),await this.#$.refreshInsulaQuota();let J=(await y4(this.paths.rosterPath))?.rows.find((Y)=>Y.routeId===$),X,z=await this.#$.pollInsulaQuotaForRoute($,async()=>{this.#G($,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#M($,Z);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let Y=k4(S9(z,this.routes().find((W)=>W.id===$)?.quota),z.primary.checkedAt,!0);if(!Y)return this.#G($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#$.recordAccountQuota($,J.accountIdentity,Y))return this.#G($,"insula",null),{ok:!0};return this.#G($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#$.lookupInsulaQuotaForRoute($),Q=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G($,"insula",Q),{ok:!1,error:`insula ${Q}`}}return this.#M($,Z)}async#M($,Z){let J,X=this.#Z.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,Q)=>{try{let Y=Z?void 0:await this.#$.cachedInsulaQuota(Q);if(Y!==void 0){let W=k4(S9(Y,this.routes().find((H)=>H.id===$)?.quota),Y.primary.checkedAt,!0);if(!W)throw Error("unusable insula reading");return await this.#$.recordQuota($,W,Q),new Response(null,{status:200})}let B=await L1({accessToken:G,fetchImpl:X,now:this.#Z.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:$,logger:Y0});return await this.recordSnapshot($,B,!0,Q),J=void 0,new Response(null,{status:200})}catch(Y){J=x0(Y);let B=Y?.status;if(typeof B==="number")return new Response(null,{status:B});throw Y}},{site:"quota"}).catch((G)=>{J=x0(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading($){let Z=this.#B.get($);if(Z)return Z;let J=this.pollQuota($,!1).catch((X)=>{Y0.warn("vault quota poll failed",{routeId:$,error:x0(X)})}).finally(()=>{this.#B.delete($)});return this.#B.set($,J),J}async pollStale($){let Z=(this.#Z.now??Date.now)(),J=[];for(let X of this.routes()){let z=_z(X.quota);if(z!==void 0&&Z-z<$)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder($){let Z=await this.authority();if(Z!=="vault"&&Z!=="host")throw Error("Vault order can only be changed in vault mode.");return this.#$.reorder($)}async decline($){await this.#$.decline($),Y0.info("vault account declined",{routeId:$})}async accept($){await this.#$.accept($),Y0.info("vault account accepted",{routeId:$})}async status(){let $=await this.authority(),Z;try{Z=$==="host"?{state:"idle"}:await x4(this.paths,this.name)}catch(X){this.#X("vault enrollment state unreadable",X),Z={state:"blocked",proposedName:this.name,code:X instanceof o5?X.kind:"unreadable-state"}}let J=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:J!==void 0,accounts:J?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){if(await this.authority()==="host")throw new u("vault-host",E9);let $=await this.#T().catch((Z)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${x0(Z)}. Is the vault running?`)});try{let Z=new XZ({client:$,paths:this.paths,proposedName:this.name,displayName:Cz(this.host),requestedGrants:Mz,...this.#Z.now?{now:this.#Z.now}:{}}),J=await Z.status();if(J.state==="denied"||J.state==="blocked")await Z.resetTerminal();let X=await Z.reconcile();if(Y0.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{$.close()}}waitForApproval($={}){return this.#W??=(async()=>{let Z=$.sleep??((G)=>new Promise((Q)=>setTimeout(Q,G))),J=$.pollIntervalMs??2000,X=Date.now()+($.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if($.onPending?.(z),Date.now()>=X)return z;await Z(J),z=await this.connectStep()}return z})().finally(()=>{this.#W=void 0}),this.#W}async disconnect(){if(await this.authority()==="host")throw new u("vault-host",E9);await r5(this.paths.tokenPath,{force:!0}),await r5(this.paths.statePath,{force:!0}),await this.#Z.afterDisconnect?.(),await this.authority(),this.#J=void 0,Y0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())zZ({mode:"custody",auth:$,provider:"openai"})}close(){this.#K=!0,this.#V.resolve(),this.#$.close()}async dispose(){this.close(),await this.#$.dispose()}}function _z($){if(!$)return;let Z=b0($).limits.map((J)=>J.checkedAt);return Z.length>0?Math.max(...Z):void 0}function h4($,Z){if(Z.state!=="pending")return[];if(!Z.requestId)return[`The vault did not take the enrollment request yet${Z.retryCode?` (${Z.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${Z.requestId} for ${$} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${Z.requestId}`,...Z.requestedGrantsStatus==="sent"?[]:[`Then grant OpenAI access to the name you approved with --name (defaults to ${$}):`,` ${I4($)}`]]}function HZ($,Z,J){let X=`${WZ[$]} (${J.state==="approved"?J.approvedName??Z:Z})`;switch(J.state){case"approved":return`${X}: connected to the Claustrum vault.`;case"idle":return`${X}: not connected to the Claustrum vault.`;case"pending":return J.requestId?`${X}: waiting for approval of request ${J.requestId}.`:`${X}: enrollment request not taken yet${J.retryCode?` (${J.retryCode})`:""}.`;case"denied":return`${X}: the vault denied the enrollment request.`;case"blocked":return`${X}: enrollment stopped (${J.code}).`;case"unavailable":return`${X}: the vault is unavailable (${J.code}).`;case"busy":return`${X}: another process is enrolling right now.`}}function I9($,Z){if((Z.state==="blocked"||Z.state==="unavailable")&&Z.code==="unknown_method")return{ok:!1,text:'Enrollment stopped (unknown_method). This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), then run Connect again.'};switch(Z.state){case"approved":{let J=Z.approvedName??$.name,X=$.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${J}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?`. ${b4(J,$.grantReach())}`:"."}`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${Z.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...h4($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
2
+ `)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var b9="/backend-api/wham/rate-limit-reset-credits",Sz=`https://chatgpt.com${b9}`,NZ=`${b9}/consume`,Az=`https://chatgpt.com${NZ}`,Ez=300000,Rz=60000,Iz=15000,bz=60000;function p2($){return{configPath:$.configPath,statePath:$.statePath}}class W0 extends Error{kind;cooldownUntil;constructor($,Z,J){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=J}}class P2 extends Error{kind;status;constructor($,Z,J){super(Z);this.name="ResetCreditError",this.kind=$,this.status=J}}function DZ($,Z,J){return{authorization:`Bearer ${$}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function w4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function PZ($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function u4($){if(!w4($)||typeof $.redeemRequestId!=="string"||$.redeemRequestId.length===0||typeof $.creditId!=="string"||$.creditId.length===0||typeof $.startedAt!=="number"||!Number.isFinite($.startedAt)||$.chatgptAccountId!==void 0&&(typeof $.chatgptAccountId!=="string"||$.chatgptAccountId.length===0))return;return{redeemRequestId:$.redeemRequestId,creditId:$.creditId,startedAt:$.startedAt,...typeof $.chatgptAccountId==="string"?{chatgptAccountId:$.chatgptAccountId}:{},...MZ($.rejectedStatus)?{rejectedStatus:$.rejectedStatus}:{},...typeof $.unknownAnswers==="number"&&Number.isSafeInteger($.unknownAnswers)&&$.unknownAnswers>0?{unknownAnswers:$.unknownAnswers}:{}}}function MZ($){return typeof $==="number"&&$>=400&&$<500&&$!==408&&$!==409&&$!==425&&$!==429}function m4($){return $.kind==="http_error"&&MZ($.status)}function CZ($,Z){return $.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z||$.rejectedStatus!==void 0}function kz($,Z){if($.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z)throw new W0("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function TZ($){return Boolean($&&Object.hasOwn($,"inFlight"))}function LZ($,Z){return Z-$.startedAt<Ez}function l2($,Z){if(!p0(Z))return;return $.reset?.[Z]}function OZ($){if(!$.reset)$.reset=Object.create(null);return $.reset}function _Z($,Z,J){if(!p0(Z))return;let X=OZ($),z=X[Z]??{},G=z.lastOutcome;delete z.inFlight,z.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[Z]=z}function SZ($,Z){let J=PZ($),X=u4($?.inFlight);if(TZ($)&&!X)return{kind:"corrupt",beforeState:J};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:J,cooldownUntil:$.cooldownUntil};if(X&&LZ(X,Z))return{kind:"claim",beforeState:J,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:J,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:J}}async function xz($,Z){if(!p0(Z))return{kind:"fresh",beforeState:void 0};let J=await $.loadAccountsFn(p2($));return SZ(J?l2(J,Z):void 0,$.now())}async function yz($,Z){let J;if(await $.mutateAccountsFn((X)=>{let z=$.now(),G=l2(X,Z);if(J=SZ(G,z),J.kind==="corrupt")_Z(X,Z,z);return X},p2($)),!J)throw Error("corrupt reset state mutation did not run");return J}async function gz($,Z,J,X){if(!p0(Z))return{kind:"fresh",beforeState:void 0};let z;if(await $.mutateAccountsFn((G)=>{let Q=$.now(),Y=l2(G,Z),B=PZ(Y),W=u4(Y?.inFlight);if(TZ(Y)&&!W)return _Z(G,Z,Q),z={kind:"corrupt",beforeState:B},G;if(Y?.cooldownUntil!==void 0&&Y.cooldownUntil>Q)return z={kind:"cooldown",beforeState:B,cooldownUntil:Y.cooldownUntil},G;if(W&&LZ(W,Q))return z={kind:"claim",beforeState:B,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;if(W&&!CZ(W,X))return z={kind:"expired_unreconciled",beforeState:B,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;let H=p4(J);if(!H)return z={kind:"fresh",beforeState:B},G;let V={redeemRequestId:$.randomUUID(),creditId:H.id,startedAt:Q,...X===void 0?{}:{chatgptAccountId:X}},U=OZ(G);return U[Z]={...Y,inFlight:V},z={kind:"claim",beforeState:B,claim:{inFlight:V,selectedCredit:H}},G},p2($)),!z)throw Error("reset claim mutation did not run");return z}async function fz($,Z,J,X,z){if(!p0(Z))return;if(!y9(X.kind))return vz($,Z,J,X,z);await $.mutateAccountsFn((G)=>{let Q=l2(G,Z),Y=u4(Q?.inFlight);if(!Q||!Y||Y.redeemRequestId!==J.redeemRequestId||Y.creditId!==J.creditId)return G;let B=$.now();if(delete Q.inFlight,Q.lastOutcome={code:X.kind,at:B},X.kind==="reset"||X.kind==="already_redeemed")Q.cooldownUntil=B+bz;else delete Q.cooldownUntil;return G},p2($));return}function UZ($,Z){let J=u4($?.inFlight);return J&&J.redeemRequestId===Z.redeemRequestId&&J.creditId===Z.creditId?J:void 0}async function vz($,Z,J,X,z){let G=m4(X)?X.status:void 0;if(!(J.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===J.rejectedStatus){let B=await $.loadAccountsFn(p2($));return UZ(B?l2(B,Z):void 0,J)}let Y;return await $.mutateAccountsFn((B)=>{Y=void 0;let W=l2(B,Z),H=UZ(W,J);if(!W||!H)return B;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,Y=V,B},p2($)),Y}function O1($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let J=Date.parse($.resetsAt);return!Number.isFinite(J)||J>Z}function k9($,Z,J){if(!(Z||O1($.primary,J)||O1($.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function qZ($,Z){let J=$[Z];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function hz($){if(!w4($))return;let Z=qZ($,"granted_at"),J=qZ($,"reset_type");if(typeof $.id!=="string"||typeof $.status!=="string"||typeof $.expires_at!=="string"||Number.isNaN(Date.parse($.expires_at))||typeof $.is_supported_by_plan!=="boolean"||Z===null||J===null)return;return{id:$.id,status:$.status,...Z===void 0?{}:{grantedAt:Z},expiresAt:$.expires_at,...J===void 0?{}:{resetType:J},isSupportedByPlan:$.is_supported_by_plan}}async function x9($,Z,J){let X;try{X=await $(Sz,{method:"GET",headers:DZ(Z,b9,J),signal:AbortSignal.timeout(Iz)})}catch{throw new P2("http_error","reset credit list request failed")}if(!X.ok)throw new P2("http_error",`reset credit list request failed: ${X.status}`,X.status);let z;try{z=await X.json()}catch{throw new P2("invalid_response","reset credit list response was not valid JSON",X.status)}if(!w4(z))throw new P2("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((Q)=>{let Y=hz(Q);return Y===void 0?[]:[Y]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function p4($){return[...$].filter(AZ).sort((Z,J)=>Date.parse(Z.expiresAt)-Date.parse(J.expiresAt))[0]}function AZ($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function EZ($){return $.filter(AZ).length}function y9($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function mz($,Z,J,X,z){let G;try{G=await $(Az,{method:"POST",headers:{...DZ(Z,NZ,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:X}),signal:AbortSignal.timeout(Rz)})}catch(W){return{kind:"ambiguous",raw:W}}let Q;try{Q=await G.text()}catch(W){return G.ok?{kind:"ambiguous",raw:W}:{kind:"http_error",raw:W,status:G.status}}let Y=Q,B=!1;try{Y=JSON.parse(Q),B=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Y,status:G.status};if(!B||!w4(Y)||!y9(Y.code))return{kind:"ambiguous",raw:Y};return{kind:Y.code,raw:Y}}function jZ($){if($.kind==="cooldown")throw new W0("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function FZ(){throw new W0("expired_unreconciled","the previous reset attempt outcome is unknown")}function KZ($,Z){return{target:$,selectedCredit:void 0,beforeState:Z,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function wz($){if($.kind==="reset"||$.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if($.kind==="nothing_to_reset"||$.kind==="no_credit")return"The server returned a terminal no-op. No cooldown was set; a new attempt starts fresh and remains gated by fresh preconditions.";if(m4($))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 uz($,Z){if($)return"The server refused the request, but recording the refusal failed, so the saved redemption may still be treated as unknown and block a new attempt. A retry reuses the same request and credit identifiers; this does not prove the server did nothing.";if(Z)return"The server refused the request, but another send of the same request had an unknown outcome, so the saved redemption still blocks a new attempt until a retry settles it. A retry reuses the same request and credit identifiers; this does not prove the server did nothing.";return"The server refused the request, and another attempt has already settled or replaced the saved redemption. A new attempt is gated by the current saved state and fresh preconditions."}async function RZ($,Z){if(!p0(Z.accountKey))throw new W0("invalid_account_key","the reset account key is reserved");let J=await $.resolveTarget(Z.accountKey);if(J.chatgptAccountId!==Z.expectedChatgptAccountId)throw new W0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=J.chatgptAccountId,z=J.accountKey==="main"?void 0:X,G=await xz($,Z.accountKey);if(G.kind==="corrupt"){if(G=await yz($,Z.accountKey),G.kind==="corrupt")return KZ(J,G.beforeState)}if(G.kind==="cooldown")jZ(G);let Q;if(G.kind==="claim")Q=G.claim;else if(G.kind==="expired_unreconciled"&&(Z.retry||!CZ(G.claim.inFlight,X))){if(!Z.retry)FZ();Q=G.claim}else{if(Z.retry)throw new W0("retry_without_inflight","there is no active reset credit redemption to retry");let[U,j]=await Promise.all([$.fetchUsage(J),x9($.fetchImpl,J.accessToken,z)]),q=k9(U,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!q.ok)throw new W0("not_exhausted",q.reason);if(!p4(j.credits))throw new W0("no_eligible_credit","no eligible reset credit was returned");let F=await gz($,Z.accountKey,j.credits,X);if(F.kind==="corrupt")return KZ(J,F.beforeState);if(F.kind==="cooldown")jZ(F);if(F.kind==="expired_unreconciled")FZ();if(F.kind!=="claim")throw new W0("no_eligible_credit","no eligible reset credit was available while claiming");Q=F.claim}kz(Q.inFlight,X);let Y=await mz($.fetchImpl,J.accessToken,z,Q.inFlight.creditId,Q.inFlight.redeemRequestId),B,W=!1;try{B=await fz($,Z.accountKey,Q.inFlight,Y,X)}catch{W=!0}let H=W&&y9(Y.kind),V=m4(Y)&&!W&&B?.rejectedStatus!==void 0;return{target:J,selectedCredit:Q.selectedCredit,beforeState:G.beforeState,outcome:Y,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.":m4(Y)&&!V?uz(W,B):wz(Y),...V?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}async function IZ($){let Z=[];for(let J of $)try{Z.push(...await J.run())}catch(X){Z.push({code:"doctor-check-failed",message:`Check ${J.id} failed: ${X instanceof Error?X.message:String(X)}`})}return{findings:Z}}function bZ($,Z){let J=[$];if(Z.findings.length===0)return J.push("No problems found."),J;for(let X of Z.findings){let z=X.repair?" (repair available)":"";J.push(`- ${X.message}${z}`)}return J}async function kZ($,Z){let J={applied:[],declined:[],failed:[]};for(let X of Z.findings){let z=X.repair;if(!z)continue;if(!await $.confirm(`Apply repair: ${z.label}?`)){J.declined.push(X);continue}try{await z.apply(),J.applied.push(X)}catch(G){J.failed.push({finding:X,error:G}),$.print(`Repair failed: ${z.label}: ${G instanceof Error?G.message:String(G)}`)}}return J}function g9($){let Z=$.title??"Auth doctor";return{id:"doctor",label:$.label??"Auth doctor",hint:"check accounts and offer repairs",async run(J){let X=await IZ($.checks);for(let Q of bZ(Z,X))J.print(Q);let z=X.findings.filter((Q)=>Q.repair);if(z.length===0){if(X.findings.length>0)J.print("No repairs are available.");return}let G=await kZ(J,X);J.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as pz}from"node:child_process";import{win32 as lz}from"node:path";function yZ($,Z=process.platform,J=pz){try{if(Z==="win32"){let z=`Start-Process '${$.replaceAll("'","''")}'`,G=J(lz.resolve(process.env.SystemRoot??process.env.windir??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(z,"utf16le").toString("base64")],{stdio:"ignore",windowsHide:!0});return G.on("error",()=>{}),G.unref(),G.pid!==void 0}let X=J(Z==="darwin"?"open":"xdg-open",[$],{stdio:"ignore"});return X.on("error",()=>{}),X.unref(),X.pid!==void 0}catch{return!1}}function xZ($,Z){if($.print(""),$.print("Open this URL in your browser and complete sign-in:"),$.print(""),$.print(Z.url),$.print(""),Z.instructions)$.print(Z.instructions),$.print("")}async function l4($,Z){let J=new AbortController,X=await $.begin({headless:!1,signal:J.signal});X.completion.catch(()=>{}),xZ(Z,X);let z=!1;try{z=await($.openBrowser??yZ)(X.url)!==!1}catch{z=!1}if(!z)J.abort(),Z.print("Could not open a browser. Switching to device authorization."),Z.print(""),X=await $.begin({headless:!0}),xZ(Z,X);return X.completion}var k={hide:"\x1B[?25l",show:"\x1B[?25h",up:($=1)=>`\x1B[${$}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:($,Z)=>`\x1B[${$};${Z}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function f9($){let Z=$.toString(),J=[];for(let X=0;X<Z.length;){let z=Z[X];if(z==="\x1B"){let G=Z.slice(X,X+3),Q=G[1]==="["||G[1]==="O"?G[2]:void 0;if(Q&&"ABCD".includes(Q)){let B={A:"up",B:"down",C:"right",D:"left"}[Q];if(B)J.push(B);X+=3}else if(X+1===Z.length){if(X===0)J.push("escape-start");X+=1}else if((Z[X+1]==="["||Z[X+1]==="O")&&X+2>=Z.length)break;else X+=1;continue}if(z==="\r"||z===`
3
+ `)J.push("enter");else if(z==="\x03")J.push("escape");else if(z&&z>=" ")J.push("char");X+=1}return J}var gZ=`${String.fromCharCode(27)}\\[[0-9;]*m`,dz=new RegExp(gZ,"g"),cz=new RegExp(`^${gZ}`);function fZ($){return $.replace(dz,"")}function M2($,Z){if(Z<=0)return"";if(fZ($).length<=Z)return $;let J=Z>=3?"...":".".repeat(Z),X=Math.max(0,Z-J.length),z="",G=0,Q=0;while(G<$.length&&Q<X){if($[G]==="\x1B"){let Y=$.slice(G).match(cz);if(Y){z+=Y[0],G+=Y[0].length;continue}}z+=$[G],G+=1,Q+=1}return z.includes("\x1B[")?`${z}${k.reset}${J}`:z+J}function v9(){return{input:process.stdin,output:process.stdout,signals:process}}function C2($){return $.input.isTTY===!0}function h9($,Z=""){$.output.write(`${Z}
4
+ `)}var sz=50;function nz($){if($==="red")return k.red;if($==="cyan")return k.cyan;return""}async function d2($,Z,J){if(!C2($))throw Error("Interactive select requires a TTY terminal");if(Z.length===0)throw Error("No menu items provided");let{input:X,output:z,signals:G}=$,Q=0,Y=null,B=!1,W=0,H=()=>{let V=z.columns??80,U=z.rows??24,j=W;if(J.clearScreen)z.write(k.clearScreen+k.moveTo(1,1));else if(j>0)z.write(k.up(j));let q=0,F=(O)=>{z.write(`${k.clearLine}${O}
5
+ `),q+=1},K=J.lines??[],N=1+(J.subtitle?3:0)+K.length+(K.length?1:0),D=Math.max(1,Math.min(Z.length,U-N-2-1)),T=Math.max(0,Math.min(Q-Math.floor(D/2),Math.max(0,Z.length-D))),M=Z.slice(T,T+D);if(F(`${k.dim}┌ ${k.reset}${M2(J.message,Math.max(1,V-4))}`),J.subtitle)F(`${k.dim}│${k.reset}`),F(`${k.cyan}◆${k.reset} ${M2(J.subtitle,Math.max(1,V-4))}`),F("");for(let O of K)F(`${k.cyan}│${k.reset} ${M2(O,Math.max(1,V-4))}`);if(K.length)F(`${k.cyan}│${k.reset}`);for(let O=0;O<M.length;O++){let C=M[O];if(!C)continue;let L=T+O===Q,A=nz(C.color),x=A?`${L?"":k.dim}${A}${C.label}${k.reset}`:L?C.label:`${k.dim}${C.label}${k.reset}`;if(C.hint)x+=` ${k.dim}${C.hint}${k.reset}`;x=M2(x,Math.max(1,V-8)),F(L?`${k.cyan}│${k.reset} ${k.green}●${k.reset} ${x}`:`${k.cyan}│${k.reset} ${k.dim}○${k.reset} ${x}`)}let P=M.length<Z.length?` (${T+1}-${T+M.length}/${Z.length})`:"";F(`${k.cyan}│${k.reset} ${k.dim}${M2(`Up/Down to select | Enter: confirm | Esc: back${P}`,Math.max(1,V-6))}${k.reset}`),F(`${k.cyan}└${k.reset}`);for(let O=q;O<j;O++)F("");W=q};return new Promise((V)=>{let U=X.isRaw??!1,j=()=>{if(B)return;if(B=!0,Y)clearTimeout(Y);X.removeListener("data",K);try{X.setRawMode(U),X.pause(),z.write(k.show)}catch{}G?.removeListener("SIGINT",F),G?.removeListener("SIGTERM",F)},q=(N)=>{j(),V(N)},F=()=>q(null),K=(N)=>{for(let D of f9(N)){if(B)break;if(Y)clearTimeout(Y),Y=null;switch(D){case"up":Q=(Q-1+Z.length)%Z.length,H();break;case"down":Q=(Q+1)%Z.length,H();break;case"enter":q(Z[Q]?.value??null);break;case"escape":q(null);break;case"escape-start":Y=setTimeout(()=>q(null),sz);break;default:break}}};G?.once("SIGINT",F),G?.once("SIGTERM",F);try{X.setRawMode(!0)}catch{j(),V(null);return}X.resume(),z.write(k.hide),H(),X.on("data",K)})}async function m9($,Z,J=!1){if(!C2($))return!1;return await d2($,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Z})??!1}function vZ($){let Z=C2($);return{terminal:$,interactive:Z,print:(J)=>h9($,J),confirm:(J,X)=>m9($,J,X),select:async(J,X)=>Z&&J.length>0?d2($,J,X):null}}function az($,Z){if($.print(Z.title),Z.subtitle)$.print(Z.subtitle);for(let J of Z.status??[])$.print(` ${J}`);$.print(""),$.print("Actions:");for(let J of Z.actions)$.print(J.hint?` - ${J.label} (${J.hint})`:` - ${J.label}`);return $.print(""),$.print("This menu needs an interactive terminal to choose an action; nothing was changed."),{status:"not-interactive"}}async function _1($){let Z=$.terminal??v9(),J=vZ(Z);if(!J.interactive)return az(J,$);if($.actions.length===0)return J.print("No actions are available."),{status:"cancelled"};let X=await d2(Z,$.actions.map((z)=>({label:z.label,value:z,color:z.destructive?"red":"cyan",...z.hint?{hint:z.hint}:{}})),{message:$.title,subtitle:$.subtitle??"Select an account action",...$.status?{lines:$.status}:{},clearScreen:!0});if(!X)return{status:"cancelled"};if(X.destructive&&!await J.confirm(X.confirm??`${X.label}?`))return J.print("Cancelled; nothing was changed."),{status:"declined",action:X.id};try{return await X.run(J),{status:"ran",action:X.id}}catch(z){return J.print(`${X.label} failed: ${z instanceof Error?z.message:String(z)}`),{status:"failed",action:X.id,error:z}}}var mZ="disabled from the auth menu",hZ=8;async function y0($){let Z=await $.read();if(Z.status==="ready")return{rows:Z.rows};if(Z.status==="pending-migration")return{rows:[],problem:"The account store has not been migrated yet."};return{rows:[],problem:`The account store could not be read (${Z.file}: ${Z.reason}).`}}async function iz($){let{rows:Z}=await y0($);return Z.some((J)=>J.credential!==void 0)}function p9($){let Z=[];if($.label)Z.push($.label);if($.invalid)Z.push(`invalid ${$.invalid}`);else if(!$.enabled)Z.push($.disabledReason?`disabled: ${$.disabledReason}`:"disabled");else Z.push("enabled");if(!$.credential&&!$.invalid)Z.push("no credential");return Z.join(", ")}function rz($){if($.problem)return[$.problem];if($.rows.length===0)return["No accounts yet."];let Z=$.rows.slice(0,hZ).map((X)=>`${X.id}: ${p9(X)}`),J=$.rows.length-hZ;if(J>0)Z.push(`... and ${J} more`);return Z}function oz($){return $ instanceof Error?$.message:String($)}async function l9($,Z,J){if(Z.length===0)return $.print("There are no accounts."),null;return $.select(Z.map((X)=>({label:X.id,value:X,hint:p9(X)})),{message:J})}function tz($,Z){let J=new Set(Z.map((X)=>X.id));if($.id&&!J.has($.id))return $.id;for(let X=1;;X++){let z=`account-${X}`;if(!J.has(z))return z}}function wZ($,Z=Date.now()){let J=e0($.quota)?b0($.quota):void 0,X=d4(J,{now:Z,form:"full"});return(X.length>0?X:[I0(J,{now:Z})]).map((z)=>` ${z}`)}function uZ($){return{id:"add-account",label:"Add account",hint:"sign in to another account",async run(Z){let J=$.login;if(!J)throw Error("No login is configured");let X=await l4(J,Z),{rows:z}=await y0($.store),G=($.newAccountId??tz)(X,z),Q=await $.store.add({id:G,credential:X.credential,...X.identity!==void 0?{identity:X.identity}:{},...X.label!==void 0?{label:X.label}:{}},$.extraLocks?{extraLocks:$.extraLocks}:{});if(Q.outcome==="rotated")Z.print(`That sign-in is already account ${Q.id}; its credential was updated.`);else if(Q.outcome==="added-disabled")Z.print(`Added account ${Q.id}, disabled: another enabled account is the same provider account.`);else if(Q.outcome==="completed")Z.print(`Finished adding account ${Q.id}.`);else Z.print(`Added account ${Q.id}.`)}}}function pZ($){return{id:"reauthenticate",label:"Re-authenticate account",hint:"sign an account in again",async run(Z){let J=$.login;if(!J)throw Error("No login is configured");let{rows:X}=await y0($.store),z=await l9(Z,X,"Re-authenticate which account?");if(!z)return;let G=await l4(J,Z);if(G.identity!==void 0&&z.identity!==void 0&&G.identity!==z.identity){Z.print(`That sign-in is a different account from ${z.id}; nothing was changed. Use Add account to add it.`);return}let Q=G.identity??z.identity;await $.store.replace(z.id,G.credential,Q!==void 0?{identity:Q}:{},$.extraLocks?{extraLocks:$.extraLocks}:{}),Z.print(`Updated the sign-in of account ${z.id}.`)}}}function lZ($){return{...$.protect?{protect:$.protect}:{},...$.extraLocks?{extraLocks:$.extraLocks}:{}}}function dZ($){return $ instanceof b&&$.kind==="row-protected"?$.message:void 0}function cZ($){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run(Z){let{rows:J}=await y0($.store),X=await l9(Z,J,"Remove which account?");if(!X)return;if(!await Z.confirm(`Remove account ${X.id}?`)){Z.print("Cancelled; nothing was changed.");return}try{await $.store.remove(X.id,lZ($))}catch(z){let G=dZ(z);if(G===void 0)throw z;Z.print(`Account ${X.id} was kept: ${G}`);return}Z.print(`Removed account ${X.id}.`)}}}function w9($){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run(Z){let{rows:J}=await y0($.store),X=await l9(Z,J,"Enable or disable which account?");if(!X)return;let z=$.extraLocks?{extraLocks:$.extraLocks}:{};if(X.enabled){await $.store.disable(X.id,$.disableReason??mZ,z),Z.print(`Disabled account ${X.id}.`);return}try{await $.store.enable(X.id,z)}catch(G){if(G instanceof b&&G.kind==="duplicate-identity"){Z.print(`Account ${X.id} stays disabled: another enabled account is the same provider account.`);return}throw G}Z.print(`Enabled account ${X.id}.`)}}}function sZ($){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}if(J.rows.length===0)Z.print("No accounts yet.");for(let X of J.rows)Z.print(`${X.id}: ${p9(X)}`)}}}function u9($){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}let X=new Map,z=$.pollQuota;if(z)for(let Q of J.rows){if(Q.invalid||!Q.credential||Q.credentialEpoch===void 0){X.set(Q.id,"no usable credential");continue}try{let Y=await z(Q);await $.store.recordQuota(Q.id,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},Y)}catch(Y){X.set(Q.id,oz(Y))}}let G=await y0($.store);if(G.rows.length===0)Z.print("No accounts yet.");for(let Q of G.rows){Z.print(`${Q.id}:`);let Y=X.get(Q.id);if(Y)Z.print(` quota check failed: ${Y}`);for(let B of wZ(Q,($.now??Date.now)()))Z.print(B)}}}}function nZ($){return{id:"delete-all",label:"Delete all accounts",destructive:!0,confirm:"Delete every account? Accounts the plugin keeps are not deleted.",async run(Z){let J=await y0($.store);if(J.problem){Z.print(J.problem);return}let X=[],z=[];for(let G of J.rows)try{await $.store.remove(G.id,lZ($)),X.push(G.id)}catch(Q){let Y=dZ(Q);if(Y===void 0)throw Q;z.push(`${G.id} (${Y})`)}if(Z.print(`Deleted ${X.length} account(s).`),z.length>0)Z.print(`Kept: ${z.join(", ")}.`)}}}async function d9($){return aZ($,u2()||await $.custody?.()===!0)}function aZ($,Z){let J=$.doctor?.length?[g9({checks:$.doctor})]:[],X=[...$.extraActions??[]];if(Z)return[sZ($),w9($),u9($),...J,...X];return[...$.login?[uZ($),pZ($)]:[],cZ($),w9($),u9($),...J,...X,nZ($)]}async function ez($){let Z=u2(),J=Z||await $.custody?.()===!0,X=aZ($,J),[z,G]=await Promise.all([y0($.store),$.status?.()??[]]);return _1({title:$.title,subtitle:J?"Accounts come from the vault; select an action":"Select an account action",status:[...G,...Z?[c4]:[],...rz(z)],actions:X,...$.terminal?{terminal:$.terminal}:{}})}function iZ(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function rZ($){return $!==void 0}function $G($){return async(Z)=>{if(!rZ(Z))return $.login();if(!await $.hasCredential())return $.login(Z);return await $.openMenu(Z),iZ()}}function V0($){return $.authority!=="local"}async function $0($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function s4($){let Z;try{return await Promise.race([Promise.resolve().then(()=>$.refresh()).then(()=>{return},(J)=>J instanceof Error?J.message:String(J)),new Promise((J)=>{Z=setTimeout(()=>J("Vault roster refresh did not finish within the roster wait budget."),VZ)})])}finally{clearTimeout(Z)}}function H0($){if($.email)return $.email;if($.credentialId==="chatgpt:openai"&&(!$.label||$.label===$.credentialId))return"main";return $.label||$.routeId}function oZ($,Z){let J=b0(e0($.quota)?$.quota:void 0),X=d4(J,{now:Z});return(X.length>0?X:[I0(J,{now:Z})]).map((z)=>` ${z}`)}var S1="Accounts are managed in the vault with ck. Disconnect to use local accounts.",T2="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function tZ($){let Z=[...$.label?[$.label]:[],$.invalid?`invalid ${$.invalid}`:$.enabled?"enabled":`disabled${$.disabledReason?`: ${$.disabledReason}`:""}`];return`${$.id}: ${Z.join(", ")}`}async function ZG($,Z){let J=await s4(Z),X=await $0(Z),{status:z}=X,G=V0(X)?void 0:await $.store.read(),Q=await d9($),Y=new Set(["check-quotas",...($.extraActions??[]).map((H)=>H.id)]),B=Q.filter((H)=>!V0(X)||Y.has(H.id)).map((H)=>({...H,run:async(V)=>{if(!Y.has(H.id)&&V0(await $0(Z))){V.print(T2);return}await Z.authority(),await H.run(V)}})),W=B.find((H)=>H.id==="check-quotas");if(W)W.run=async(H)=>{await s4(Z);let V=await $0(Z),U=V0(V)?void 0:await $.store.read();if(!U)H.print(S1);else if(U.status!=="ready")H.print("The local account store could not be read.");else for(let F of U.rows){H.print(tZ(F));try{if($.pollQuota&&F.credentialEpoch!==void 0){let D=await $.pollQuota(F);await $.store.recordQuota(F.id,{credentialEpoch:F.credentialEpoch,...F.identity!==void 0?{identity:F.identity}:{}},D)}}catch(D){H.print(` quota check failed: ${D instanceof Error?D.message:String(D)}`)}let K=await $.store.read(),N=K.status==="ready"?K.rows.find((D)=>D.id===F.id):void 0;for(let D of oZ(N??F,($.now??Date.now)()))H.print(D)}let j=V.routes;for(let F of Z.snapshot()?.rows??[]){if(H.print(`Vault ${H0(F)}: ${F.enabled?F.state:"declined"}`),!j.has(F.routeId)){H.print(" quota check skipped: account is not enabled and active");continue}let K=await Z.pollQuota(F.routeId);if(!K.ok)H.print(` quota check failed: ${K.error??"vault unavailable"}`);let N=Z.snapshot()?.rows.find((D)=>D.routeId===F.routeId);for(let D of oZ({quota:N?.quota},($.now??Date.now)()))H.print(D)}let q=await Z.status();if(q.lastError)H.print(`Claustrum vault unreachable: ${q.lastError}`)};return _1({title:$.title,subtitle:"Select an account action",status:[...await $.status?.()??[],...J?[`Last error: ${J}`]:[],...z.lastError?[`Claustrum vault unreachable: ${z.lastError}`]:[],...z.accounts.map((H)=>`Vault ${H0(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!G?[S1]:G.status==="ready"?G.rows.map((H)=>tZ(H)):["The local account store could not be read."]],actions:B,...$.terminal?{terminal:$.terminal}:{}})}function eZ($){return E($)?{...$}:{}}function c9($,Z){let J=e0(Z)?$7(Z.credits):void 0;return J?`${$} · prepaid ${J}`:$}function J7($,Z){return{...$,sections:$.sections.map((J)=>J.id!=="quota"?J:{...J,items:J.items.map((X)=>X.detail===void 0?X:{...X,detail:c9(X.detail,Z.get(X.id))})})}}function n4($,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:Q})=>{let Y=await $.apply({command:$.command,sectionId:Z,...X?{itemId:X}:{},actionId:J.id,values:G,confirmed:!0},Q);return{ok:Y.ok,text:Y.text,...Y.code?{code:Y.code}:{}}}}}function s9($,Z){return new Proxy($,{get(J,X){if(X==="read")return async()=>{let G=await J.read();if(G.status!=="ready")return G;let Q={...G,rows:G.rows.map((W)=>({...W,label:W.label??W.id}))};if(!Z)return Q;let Y=await $0(Z);if(!V0(Y))return Q;let B=[...Y.status.accounts.map((W)=>({id:W.routeId,label:H0(W),type:"oauth",enabled:W.enabled,identity:W.accountIdentity,quota:W.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:B}};if(X==="readSettings")return async()=>{let G=await J.readSettings();if(G.status==="error"||!Z)return G;let Q=await $0(Z),Y=eZ(G.settings.killswitch);if(!V0(Q)||!G.settings.killswitch)return G;let B=eZ(Y.accounts);for(let W of Q.status.accounts)B[W.routeId]=A1({version:1,accounts:[],...G.settings},W.routeId);return{...G,settings:{...G.settings,killswitch:{...Y,accounts:B}}}};let z=Reflect.get(J,X);return typeof z==="function"?z.bind(J):z}})}function n9($,Z,J={}){let X=W2($),z=(W)=>W2({command:$.command,title:$.title,store:s9($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,...$.settings?{settings:$.settings}:{},routing:{...$.routing,formerMainId:W??"",vaultOrder:async()=>{let H=await $0(Z);if(!V0(H))return;return{rows:H.status.accounts.map((V)=>({id:V.routeId,label:H0(V)})),reorder:async(V)=>{if(!V0(await $0(Z)))throw new u("vault-local-action",T2);return Z.reorder(V)}}}},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),G=async(W,H)=>{let V=await $0(Z),U=V0(V),j=Z7(V.status.accounts.map((L)=>({id:L.routeId,credentialId:L.credentialId}))),q=U?z(j):X,K=(await q.open(H)).menu.sections.find((L)=>L.id===W);if(!K)throw new u("unavailable","The account menu is unavailable.");if(!U)return{lines:K.lines,items:K.items.map((L)=>({...L,actions:L.actions.map((A)=>n4(q,W,A,L.id))})),actions:K.actions.map((L)=>n4(q,W,L))};let N=new Map(V.status.accounts.map((L)=>[L.routeId,L])),D=($.now??Date.now)(),T=(L)=>({id:"check",label:L?"Check this account":"Check now",group:"Actions",run:async()=>{let x=[...(await $0(Z)).routes].filter((I)=>!L||I===L);if(L&&x.length===0)throw new u("unavailable","This vault account cannot be checked right now.");for(let I of x){let f=await Z.pollQuota(I);if(!f.ok)throw new u("quota-check-failed",`${I}: ${f.error??"vault unavailable"}`)}return`Checked quota for ${x.length} account${x.length===1?"":"s"}.`}});if(W==="quota"){let L=(A,x)=>I0(b0(A.quota,$.quota?.scope),{now:D,form:x});return{lines:V.status.accounts.filter((A)=>!V.routes.has(A.routeId)).map((A)=>`${H0(A)} (${A.enabled?A.state:"disabled"}): ${c9(L(A,"compact"),A.quota)}`),items:V.status.accounts.filter((A)=>V.routes.has(A.routeId)).map((A)=>({id:A.routeId,label:H0(A),group:"Accounts",status:L(A,"compact"),detail:c9(L(A,"full"),A.quota),actions:[T(A.routeId)]})),actions:V.routes.size>0?[T()]:[]}}let M=K.items.map((L)=>{let A=N.get(L.id),x=A&&W==="accounts"?`Vault · ${A.credentialType==="oauth"?"login":"API key"} · ${A.state} · ${A.enabled?"enabled":"declined"}`:L.detail;return{id:L.id,label:L.label,detail:x,group:L.group,status:A&&W==="accounts"?A.enabled?A.state:"disabled":L.status,...L.facts?{facts:L.facts}:{},actions:A&&W!=="limits"?[]:L.actions.map((I)=>n4(q,W,I,L.id))}}),P=K.actions.filter((L)=>V.status.accounts.length>0&&(W==="limits"||W==="routing"&&(L.id==="mode"||L.id==="order"||L.id==="maxSameAccountWait"))).map((L)=>n4(q,W,L)),O=K.actions.find((L)=>L.id==="mode")?.knobs.find((L)=>L.id==="mode"),C=W==="routing"&&j===null&&O?.kind==="choice"&&(O.value==="main-first"||O.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"],S1]:[...K.lines,...C?["No default vault account, so this mode orders like Ordered"]:[]],items:M,actions:P}},Q=W2({...$,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:$.extras?.map((W)=>W.id!=="reset"?W:{...W,build:async(H)=>{let V=await $0(Z);if(V0(V))return{lines:[S1]};return W.build(H)}})}),Y=async()=>{if(!V0(await $0(Z)))return{menu:X,error:void 0};let W=J.refresh===!1?void 0:await s4(Z);return{menu:Q,error:W}},B=async(W,H)=>{let V=await W.menu.open(H);if(W.error)V.menu.sections.find((j)=>j.id==="vault")?.lines.push(`Last error: ${W.error}`);return V};return{command:$.command,open:async(W)=>B(await Y(),W),apply:async(W,H)=>{let V=await Y(),{menu:U}=V;if(U===Q&&(W.sectionId==="accounts"||W.sectionId==="reset"||W.sectionId==="quota"&&(await $0(Z)).routes.size===0||W.sectionId==="limits"&&W.itemId!==void 0&&!(await $0(Z)).status.accounts.some((j)=>j.routeId===W.itemId)))return{...await B(V,H),ok:!1,code:"vault-local-action",text:T2};if(J.refuseApply)return{...await B(V,H),ok:!1,...J.refuseApply};return U.apply(W,H)}}}var R1="openai",B7="OpenAI accounts",J2="main",Y7="that account is already your main account, so it was not added again",q0=t("commands"),W7=new Set(["__proto__","constructor","prototype"]);function JG($,Z){let J={version:1,accounts:[],killswitch:$},X=E($.accounts)?Object.keys($.accounts):[],z={};for(let Y of new Set([J2,...Z,...X])){if(W7.has(Y))continue;let B=A1(J,Y===J2?void 0:Y);z[Y]={primary:B.primary,secondary:B.secondary}}let G=A1(J,void 0),Q={...$};return delete Q.main,Q.accounts=z,Q.defaults={primary:G.primary,secondary:G.secondary},Q.schema=I1,Q}function XG($,Z){let J=E($.accounts)?{...$.accounts}:{};for(let z of new Set([J2,...Z])){if(W7.has(z)||Object.hasOwn(J,z))continue;J[z]={primary:E1.primary,secondary:E1.secondary}}let X=E($.defaults)?$.defaults:{primary:E1.primary,secondary:E1.secondary};return{...$,accounts:J,defaults:X,schema:I1}}function X7($,Z){let J=!1;if(E($.cachekeep))$.cacheKeep={...$.cachekeep,...E($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,J=!0;let X=$.killswitch;if(E(X)&&X.schema!==I1)$.killswitch=JG(X,Z),J=!0;return J}async function z7($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((J)=>J.id):[]}function r9($,Z){if(Z&&a4(Z)==="shared")return $;let J=async()=>{let z=await $.readSettings();if(z.status==="error")return z;let G=structuredClone(z.settings);return X7(G,await z7($)),{...z,settings:G}},X=async(z,G)=>{let Q=await z7($);return $.updateSettings(async(Y)=>{X7(Y,Q);let B=await z(Y)??Y;if(E(B.killswitch)&&B.killswitch.schema!==I1)B.killswitch=XG(B.killswitch,Q);return B},G)};return new Proxy($,{get(z,G){if(G==="readSettings")return J;if(G==="updateSettings")return X;let Q=Reflect.get(z,G,z);return typeof Q==="function"?Q.bind(z):Q}})}function zG($,Z){let J=(B,W)=>Z.rowLocks?Z.rowLocks(B):W,X=(B,W)=>{let H=J(B,W?.extraLocks);return{...W??{},...H?{extraLocks:H}:{}}},z=(B,W,H,V)=>$.replace(B,W,H,X(B,V)),Y={add:async(B,W)=>{let H=await $.read(),U=(H.status==="ready"?H.rows:[]).filter((K)=>K.type==="oauth"&&!K.invalid),j=B.identity?U.find((K)=>K.identity===B.identity):void 0;if(j?.id===J2)throw new u("main-account",Y7);let q=j??U.find((K)=>K.id===B.id&&K.id!==J2);if(!q||B.credential.type!=="oauth")return $.add(B,W);let F=await z(q.id,B.credential,B.identity!==void 0?{identity:B.identity}:{},W?.extraLocks?{extraLocks:W.extraLocks}:void 0);return q0.info("account signed in again",{id:q.id}),{id:F.id,outcome:"rotated",credential:F.credential,credentialEpoch:F.credentialEpoch}},replace:z,enable:(B,W)=>$.enable(B,X(B,W)),disable:(B,W,H)=>$.disable(B,W,X(B,H)),remove:(B,W)=>$.remove(B,X(B,W))};return new Proxy($,{get(B,W){if(Object.hasOwn(Y,W))return Y[W];let H=Reflect.get(B,W,B);return typeof H==="function"?H.bind(B):H}})}async function WF($,Z,J){await r9($).updateSettings((X)=>{J(X);return},Z?{extraLocks:Z}:{})}var GG=["version","accounts","commonAuthPool"];function VF($,Z,J){return async(X)=>{let z;if(await r9($,J).updateSettings((G)=>{let Q={...G,version:1,accounts:[]},Y=X(Q)??Q;z=Y;let B={...Y};for(let W of GG)delete B[W];return B},Z?{extraLocks:Z}:{}),!z)throw Error("the settings write did not run");return z}}var QG="migration";function G7($){let Z=["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. This menu works on that layout, so it opens after the move.",$.length>0?"These processes still hold the move back:":"No running process holds the move back."],J={command:R1,title:B7,sections:[{id:QG,slot:"extra",title:"Accounts are moving",lines:Z,items:$.map((X,z)=>({id:`blocker-${z}`,label:X.pid==="unknown"?"processes that could not be read":`pid ${X.pid}`,detail:`version ${X.version}`,actions:[]})),actions:[]}]};return i9(J)}var BG=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function YG($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(BG.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function a9($,Z,J){if(Array.isArray($))return $.map((z,G)=>a9(z,`${Z}[${G}]`,J));if(!E($))return $;let X={};for(let[z,G]of Object.entries($)){if(YG(z)){J.push(`${Z}.${z}`);continue}X[z]=a9(G,`${Z}.${z}`,J)}return X}function i9($){let Z=[],J=a9($,"menu",Z);if(Z.length>0)q0.warn("credential-shaped field stripped before RPC",{fields:Z});return J}function WG($){return{id:$.id,credential:{type:"oauth",refresh:$.refresh,...$.access!==void 0?{access:$.access}:{},...$.expires!==void 0?{expires:$.expires}:{}},...$.accountId!==void 0?{identity:$.accountId}:{},...$.label!==void 0?{label:$.label}:{}}}function VG($,Z){return{label:"Add account",knobs:[{kind:"text",id:"label",label:"Label (optional)"},{kind:"toggle",id:"headless",label:"Sign in with a device code (no browser on this machine)",value:!1}],run:async(J)=>{let X=typeof J.label==="string"&&J.label.trim().length>0?J.label.trim():void 0,z=J.headless===!0,G=await $.begin({...X!==void 0?{label:X}:{},headless:z}),Q=z?`Open this verification URL:
6
+
7
+ ${G.url}
8
+
9
+ Then enter the code: ${G.instructions.match(/Enter code: (.+)/)?.[1]??G.instructions}
10
+
11
+ The account is added when you finish.`:`Open this URL and complete sign-in:
12
+
13
+ ${G.url}
14
+
15
+ ${G.instructions}
16
+
17
+ The account is added when you finish.`,Y=G.completion.then(async(B)=>{if(Z&&await Z.authority()!=="local")throw new u("vault-local-action",T2);let W=await $.mainIdentity?.();if(B.id===J2||B.accountId&&W&&B.accountId===W)throw q0.warn("account add rejected (main identity)",{id:B.id}),new u("main-account",Y7);return q0.info("account added",{id:B.id}),WG(B)});return{status:"pending",message:Q,completion:Y}}}}function HF($){return{id:"session",title:"This session",build:async(Z)=>{let J=Z.sessionId;if(!J)return{lines:["No current session"]};let X=await $.getPin?.(J);return{lines:[X?`Pinned to ${X}`:"No sticky pin"],actions:$.clearPin?[{id:"clear-pin",label:"Clear this session's pin",description:"The next request may still choose the same account.",run:async({invocation:z})=>{if(!z.sessionId)return"No current session.";return await $.clearPin?.(z.sessionId),q0.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 UF($){let{vault:Z}=$;return{id:"vault",title:"Vault",build:async()=>{let J=await Z.status(),X=J.enrollment.state==="approved"?J.enrollment.approvedName??J.name:J.name,z=await Z.authority(),G=z==="host",Q=z!=="local",Y=Z.routes().length;return{lines:[G?c4:Q?J.discovered?`Connected · ${J.accounts.length} account${J.accounts.length===1?"":"s"}`:"Connected · waiting for the vault's first answer":J.enrollment.state==="idle"?"Not connected":`Enrollment ${J.enrollment.state}`,...!G?[HZ(J.host,J.name,J.enrollment),...h4(J.name,J.enrollment)]:[],...Q&&J.discovered?[J.accounts.length===0?b4(X,Z.grantReach()):`The vault serves ${J.accounts.length} OpenAI account${J.accounts.length===1?"":"s"}; ${Y} can route now.`]:[],...Q&&Z.snapshot()?.complete===!1?["The vault's last list had records this host could not read; accounts it did not list are kept as they were until a complete list arrives."]:[],...J.lastError?[`Last error: ${J.lastError}`]:[]],items:J.accounts.map((B)=>({id:B.routeId,label:H0(B),group:"Accounts",status:B.enabled?B.state:"disabled",detail:[B.credentialType==="api_key"?"API key":"login",B.state==="active"?"active":`vault state ${B.state}`,B.enabled?"enabled":"disabled here"].join(", "),actions:[B.enabled?{id:"disable",label:"Disable on this host",description:"It stays in the vault and in this list, and is never sent from this host until enabled again.",run:async()=>{return await Z.decline(B.routeId),await $.changed?.(),`${H0(B)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await Z.accept(B.routeId),await $.changed?.(),`${H0(B)} is enabled on this host.`}}]})),actions:G?[]:Q?[{id:"disconnect",label:"Disconnect",description:"Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",confirm:"Disconnect from the vault? Connecting again needs a new approval with `ck`.",run:async()=>{let B=(await Z.status().catch(()=>{return}))?.enrollment,W=B?.state==="approved"?B.approvedName??Z.name:Z.name,H=B&&B.state!=="blocked"?`Run \`ck auth enroll revoke --name ${W}\` to revoke it in the vault too.`:"Run ck auth enroll list to find this host's enrollment name, then ck auth enroll revoke --name <name>.";return await Z.disconnect(),await $.changed?.(),`Disconnected: ${W} no longer reads from the vault. ${H}`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:B})=>{let W=await Z.connectStep();if(W.state!=="pending"&&W.state!=="busy")return await $.changed?.(),I9(Z,W);return Z.waitForApproval($.wait).then(async(H)=>{await $.changed?.();let V=I9(Z,H);B.notify(V.text,V.ok?"info":"warning")}).catch((H)=>{B.notify(`Connecting to the vault failed: ${H instanceof Error?H.message:String(H)}`,"error")}),{ok:!0,text:[...h4(Z.name,W),"Waiting for the approval; you are told here when it lands."].join(`
18
+ `)}}}]}}}}async function Q7($,Z,J){if(!p0(Z))return U0(Z,"invalid_account_key","That account cannot take a reset credit.");let X;try{let z=(await $.loadAccounts({configPath:$.configPath,statePath:$.statePath}))?.reset?.[Z];if(J||z&&Object.hasOwn(z,"inFlight"))X=(await $.resolveResetTarget(Z)).chatgptAccountId;else{let Q=await H7(Z,$);if(!Q.eligible)return U0(Z,"not_eligible",U7(Q));X=Q.chatgptAccountId}if(!X)return U0(Z,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");q0.info("reset redemption decision",{accountKey:Z,retry:J});let G=await RZ({configPath:$.configPath,statePath:$.statePath,mutateAccountsFn:$.mutateAccounts,loadAccountsFn:$.loadAccounts,now:$.now,randomUUID:$.randomUUID,fetchImpl:$.fetchImpl,resolveTarget:$.resolveResetTarget,fetchUsage:(Q)=>L1({accessToken:Q.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:Q.chatgptAccountId}),hasActiveRateLimitMark:(Q)=>$.quotaManager.isRateLimited(Q)},{accountKey:Z,expectedChatgptAccountId:X,retry:J});return q0.info("reset redemption outcome",{accountKey:Z,code:G.outcome.kind}),q7(G,$,X)}catch(z){let G=KG(Z,z,X);return q0.info("reset redemption outcome",{accountKey:Z,code:G.code}),G}}function qF($){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await $.accountKeys()).map((Z)=>({id:Z,group:"Accounts",label:Z===J2?"Main account":Z,actions:[{id:"preview",label:"Preview",description:"Fetch the account's current quota and reset credits before spending a credit.",run:async()=>{let J=await H7(Z,$);return{ok:J.eligible,text:`${FG(J)}
19
+
20
+ ${U7(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 Q7($,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 Q7($,Z,!0);return{ok:J,text:X}}}]}))})}}var HG=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],UG=["primary","secondary"];function jF($){let Z=new Set($.unavailableSections),J=(W)=>({title:W,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),X=[...$.extras??[]];if(Z.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:R1,title:B7,store:s9(r9(zG($.store,{...$.rowLocks?{rowLocks:$.rowLocks}:{}}),$.configPath)),...$.settings?{settings:$.settings}:{},...$.extraLocks?{extraLocks:$.extraLocks}:{},accounts:{...$.login?{login:VG($.login,$.vault)}:{},...$.protect?{protect:$.protect}:{},...$.describeIdentity?{describeIdentity:$.describeIdentity}:{}},quota:$.quotaCheck?{check:$.quotaCheck}:{},routing:{orderedVariants:HG,formerMainId:J2,sameAccountWait:!0},limits:{labels:UG},...Z.has("cache")?{cache:J("Cache")}:$.cache?{cache:$.cache}:{},...Z.has("diagnostics")?{diagnostics:J("Diagnostics")}:$.diagnostics?{diagnostics:$.diagnostics}:{},extras:X,...$.logger?{logger:$.logger}:{},...$.now?{now:$.now}:{}},G=$.vault?n9(z,$.vault,{refresh:!$.readOnly,...$.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):W2(z),Q=$.vault?n9(z,$.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,Y=(W)=>{let{sessionId:H}=W,V=W.notify.bind(W);return{...H!==void 0?{sessionId:H}:{},notify:V}},B=async(W)=>{if($.vault&&await $.vault.authority()!=="local")return W;let H=await $.store.read().catch(()=>{return});if(H?.status!=="ready")return W;return{...W,menu:J7(W.menu,new Map(H.rows.map((V)=>[V.id,V.quota])))}};return{command:R1,async open(W){let H=Y(W),V=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(V&&!V.migrated)return{command:R1,menu:G7(V.blockers)};let U=await G.open(H);return B({...U,menu:i9(U.menu)})},async apply(W,H){let V=Y(H),U=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(U&&!U.migrated)return{command:R1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:G7(U.blockers)};if($.readOnly&&$.vault)return G.apply(W,V);if($.readOnly||$.allowAction&&!$.allowAction(W)||Z.has(W.sectionId)){if(Q)return Q.apply(W,V);return{...await G.open(V),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let j=await G.apply(W,V);if(j.ok)await $.afterApply?.();return B({...j,menu:i9(j.menu)})}}}function V7($){let Z=[$.primary?.usedPercent,$.secondary?.usedPercent].filter((J)=>J!==void 0);return Z.length>0?Math.max(...Z):void 0}function qG($,Z){let J=[$.primary,$.secondary].filter((z)=>z!==void 0),X=J.filter((z)=>O1(z,Z));return(X.length>0?X:J).sort((z,G)=>G.usedPercent-z.usedPercent)[0]?.resetsAt}function jG($,Z){if(!$)return!1;let J=[$.primary,$.secondary].filter((X)=>X!==void 0);if(J.length===0)return!1;return J.every((X)=>!O1(X,Z))}async function H7($,Z){let J;try{J=await Z.resolveResetTarget($);let X=J.accountKey==="main"?void 0:J.chatgptAccountId,[z,G]=await Promise.all([L1({accessToken:J.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:J.chatgptAccountId}),x9(Z.fetchImpl,J.accessToken,X)]),Q=p4(G.credits),Y=EZ(G.credits),B=G.availableCount??z.resetCreditsAvailable??(Y>0?Y:void 0),W=z.resetCreditsApplicable,H=k9(z,Z.quotaManager.isRateLimited($),Z.now()),V;if(!J.chatgptAccountId)V="stable ChatGPT account identity unavailable";else if(!H.ok)V=H.reason;else if(!Q)V="no eligible credit";return{accountKey:J.accountKey,label:J.label,chatgptAccountId:J.chatgptAccountId,usedPercent:V7(z),resetTime:qG(z,Z.now()),availableCount:B,applicableAvailableCount:W,eligible:V===void 0,reason:V,selectedCreditId:Q?.id,selectedCreditExpiresAt:Q?.expiresAt}}catch(X){if(X?.status===401)await J?.onAuthFailure?.(401);return q0.warn("reset preview row failed",{accountKey:$,error:X?.message??String(X)}),{accountKey:$,label:$==="main"?"Main account":$,eligible:!1,reason:X?.message??String(X)}}}function FG($){let Z=$.usedPercent===void 0?"quota unavailable":`${$.usedPercent}% used`,J=$.availableCount===void 0?"credits unavailable":`${$.applicableAvailableCount===void 0?"?":$.applicableAvailableCount}/${$.availableCount} applicable/available`,X=$.eligible?`eligible · credit ${$.selectedCreditId} expires ${$.selectedCreditExpiresAt}`:$.reason;return`${Z}; ${J}; ${X}`}function U7($){let Z=["## Confirm reset credit","",`Account: **${$.label}** (\`${$.accountKey}\`)`,`Current quota: **${$.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${$.availableCount??"unknown"}**`,`Credit expires: **${$.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${$.resetTime??"unavailable"}**`,""];if(($.availableCount??0)>0&&$.applicableAvailableCount===0)Z.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),Z.push("");if($.eligible&&$.chatgptAccountId)Z.push('Eligible: choose "Spend a reset credit" to redeem one.');else Z.push(`Cannot reset: **${$.reason??"not eligible"}**`);return Z.join(`
21
+ `)}function U0($,Z,J,X={}){if(Object.keys(X).length>0)q0.debug("reset step details",{accountKey:$,code:Z,...X});return{ok:Z==="reset"||Z==="already_redeemed",code:Z,text:J}}function KG($,Z,J){if(Z instanceof W0){let z={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",pair_identity_mismatch:"Nothing was sent: the saved redemption was started while this account was signed in as a different ChatGPT account. Sign this account back in as that ChatGPT account and retry, or wait until five minutes after the saved redemption started and spend a new credit.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return U0($,Z.kind,`## Reset credit
22
+
23
+ ${z[Z.kind]}
24
+
25
+ Code: \`${Z.kind}\``,{cooldownUntil:Z.cooldownUntil,...Z.kind==="expired_unreconciled"?{chatgptAccountId:J,retryGuidance:"Retry replays the same request and credit identifiers from the previous attempt."}:{}})}let X=Z?.code;if(X==="unknown_account"||X==="disabled_account"||X==="non_oauth_account"||X==="token_unavailable")return U0($,X,`## Reset credit
26
+
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
+
29
+ Code: \`${X}\``);if(Z instanceof P2)return U0($,Z.kind,`## Reset credit
30
+
31
+ No redemption was attempted: reset credit availability could not be loaded.
32
+
33
+ Code: \`${Z.kind}\``);return q0.warn("reset command failed before a known result",{accountKey:$,error:Z?.message??String(Z)}),U0($,"error",`## Reset credit
34
+
35
+ The reset request failed before a known result: internal command failure — see plugin log.`)}async function q7($,Z,J){let{accountKey:X}=$.target,z=$.outcome.kind;if($.finalizeStateWriteFailed)return U0(X,z,`## Reset credit result
36
+
37
+ Account: **${$.target.label}** (\`${X}\`)
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:$.retrySafety,chatgptAccountId:J});if(z==="reset"||z==="already_redeemed"){let Q={account:X,ok:!1,error:"targeted quota refresh did not complete"};try{Q=await Z.refreshResetTargetQuota(X)}catch(j){Q.error=j?.message??String(j)}let Y=!Q.ok&&Q.error!==void 0;if(Y)q0.warn("reset quota re-check failed",{accountKey:X,error:Q.error});let B=X==="main"?Z.quotaManager.getMain():Z.quotaManager.getFallback(X),W=Q.ok&&jG(B?.quota,Z.now()),H=B?.quota.resetCreditsApplicable,V=W?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${z}\`).`,U=Y?`
40
+
41
+ quota re-check failed — see log.`:"";return U0(X,z,`## Reset credit result
42
+
43
+ Account: **${$.target.label}** (\`${X}\`)
44
+
45
+ Code: \`${z}\`
46
+
47
+ ${V}${U}${H===void 0?"":`
48
+
49
+ Remaining applicable credits: **${H}**`}`,{verifiedFresh:W,afterUsedPercent:V7(B?.quota??{}),remainingCredits:H})}if(z==="ambiguous_local")return U0(X,z,`## Reset credit result
50
+
51
+ Account: **${$.target.label}** (\`${X}\`)
52
+
53
+ Code: \`${z}\`
54
+
55
+ ${$.retrySafety}`,{retryGuidance:$.retrySafety});if(z==="ambiguous"||z==="http_error"){let Q=$.refused?' The server refused the request; five minutes after the redemption started, "Spend a reset credit" starts a new one instead.':"";return U0(X,z,`## Reset credit result
56
+
57
+ Account: **${$.target.label}** (\`${X}\`)
58
+
59
+ The redemption outcome is unknown (\`${z}\`).
60
+
61
+ Retry with "Retry the last redemption" on this account. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.${Q}`,{retryGuidance:$.retrySafety,chatgptAccountId:J})}let G={nothing_to_reset:"The server found no exhausted quota window to reset. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions.",no_credit:"The server found no usable reset credit. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions."};return U0(X,z,`## Reset credit result
62
+
63
+ Account: **${$.target.label}** (\`${X}\`)
64
+
65
+ Code: \`${z}\`
66
+
67
+ ${G[z]??"The server returned a no-op result. No reset was confirmed."}`)}function j7($,Z){return JSON.stringify(["openai","pool",C1($),C1(Z)])}function F7($){return JSON.stringify(["openai","vault",C1($)])}function NG($,Z){let J=Z.kind==="vault"?Z.routeId:Z.id,X=Z.kind==="pool"?Z.credentialEpoch:Z.kind==="vault"?Z.addedAt:Z.verifiedIdentity;if(X===void 0||X==="")return;return{namespace:$,accountId:J,incarnation:String(X)}}function NF($,Z){let J=NG($,{kind:"pool",...Z});return J?{account:J,credentialEpoch:J.incarnation,identity:Z.identity}:void 0}function DF($,Z){return{account:{namespace:$,accountId:Z.routeId,incarnation:String(Z.addedAt)},credentialEpoch:String(Z.addedAt),identity:Z.accountIdentity}}function y($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function o9($){return JSON.stringify($.map((Z)=>[y(Z.account),Z.credentialEpoch,Z.identity??null]).sort((Z,J)=>JSON.stringify(Z).localeCompare(JSON.stringify(J))))}var t9=900000;function DG($){return{...$2,shortLimit:{...$2.shortLimit,holdBound:"cache-ttl",preference:"same-account-first",jitter:"none"},advance:{...$2.advance,opencode1:{...$2.advance.opencode1,statuses:$?.length?[...$]:[401,403,429]},pi:{...$2.advance.pi,statuses:$?.length?[...$]:[401,403,429]}},terminalMetadata:"setting-capped-fresh"}}function X2($,Z){return Number.isFinite($)&&$<=Z&&Z-$<=t9}function i4($){if(!$)return;let Z=Date.parse($);return Number.isFinite(Z)?Z:void 0}function PG($,Z){return["primary","secondary"].flatMap((J)=>{let X=$?.[J];if(!X||!X2(X.checkedAt,Z)||!Number.isFinite(X.usedPercent)||!(X.usedPercent>=100))return[];return[{window:J,confirmed:!0,confirmedByReading:!0,resetAt:i4(X.resetsAt),observedAt:X.checkedAt,provenance:"reading"}]})}function MG($,Z,J,X){let z=$.window==="primary"||$.window==="secondary",G=z?J?.[$.window]:void 0,Q=G&&X2(G.checkedAt,X),Y=$.window==="usage_limit_reached",B=Y&&$.resetAt!==void 0&&Number.isFinite($.resetAt)&&$.resetAt>0;return[{window:z?$.window:Y?"usage":$.window,confirmed:z||Y,confirmedByReading:!1,resetAt:z?Q?i4(G.resetsAt):void 0:B?$.resetAt:void 0,observedAt:z&&Q?G.checkedAt:Z,provenance:z&&Q?"reading":B?"provider":"unproven"}]}function LF($){let Z=$.body;if(typeof Z==="string")try{Z=JSON.parse(Z)}catch{Z=void 0}let J=E(Z)?Z:{},X=J.type==="response.failed"&&E(J.response)?J.response:void 0,z=E(X?.error)?X.error:E(J.error)?J.error:J,G=E(X?.failed)?X.failed.rate_limit_reached_type:void 0,Q=typeof z.type==="string"?z.type:void 0,Y=typeof z.code==="string"?z.code:void 0,B=typeof G==="string"?G:X?Y??Q:Q??Y,W=$.status??(typeof J.status==="number"?J.status:typeof J.status_code==="number"?J.status_code:void 0);if(B!=="usage_limit_reached"&&!X&&W!==429)return;if(X&&!B)return;if(X&&B!=="primary"&&B!=="secondary"&&B!=="usage_limit_reached"&&B!=="rate_limit_exceeded")return;let{resets_at:H,resets_in_seconds:V}=z,U=typeof H==="number"&&Number.isFinite(H)&&H>0?H*1000:typeof V==="number"&&Number.isFinite(V)&&V>0?$.now+V*1000:void 0,q=X||Q==="usage_limit_reached"?MG({window:B??"rate_limit",resetAt:X?void 0:U},$.now,$.reading,$.now):[{window:B??"rate_limit",confirmed:!1,confirmedByReading:!1,observedAt:$.now,provenance:"unproven"}],F=$.headers?.get("retry-after"),K=F?.trim()?Number(F):NaN;return{account:$.account,kind:q.some((N)=>N.confirmed)?"quota-exhausted":"rate-limit",reason:B??"rate_limit",status:W,scope:{kind:"pool"},windows:q,observedAt:$.now,...Number.isFinite(K)&&K>=0?{retryAfterMs:K*1000,retryAfterSource:"retry-after"}:{}}}function OF($,Z,J){let X=new Map(PG(Z,J).map((z)=>[z.window,z]));for(let z of $?.windows??[]){if(!z.confirmed)continue;let G=X.get(z.window);if(!G||(z.resetAt??1/0)>=(G.resetAt??1/0))X.set(z.window,z)}return[...X.values()]}function N7($,Z,J){if(Z===401||Z===403||!$.admitted)return!0;let X=$.confirmedBlockers?.filter((G)=>G.confirmed)??[],z=Math.max(...X.map((G)=>G.resetAt??NaN));return!Number.isFinite(z)||$.blockers.some((G)=>G.kind==="hard"&&(G.until??0)>J&&(G.until??0)>z)}function _F($){if(N7($.candidate,$.status,$.now))return;let Z=F1({activity:$.activity,accountKey:$.candidate.account,maxSameAccountWait:$.maxSameAccountWait});return Z?{...Z,...$.maxDelayMs===void 0?{}:{maxDelayMs:$.maxDelayMs}}:void 0}function CG($){return!($.host!=="opencode2"&&$.mode==="ordered"&&$.status!==void 0&&!K7({version:1,accounts:[],fallbackOn:$.fallbackOn}).includes($.status))}function D7($,Z){if($.phase==="after-limit"&&!CG({...Z,host:$.host,status:$.status}))return;let J=$.candidates.find((z)=>$.attempted&&R(z.account,$.attempted)),X=!J||N7(J,$.status,$.now);return(Z.decide??Y9)({...$,hold:X?void 0:$.hold},DG(Z.fallbackOn))}function RF($){let Z=P7($.reading,$.parsed.window,$.now,60000,$.parsed.resetAt),J=$.parsed.resetAt!==void 0&&Number.isFinite($.parsed.resetAt)&&$.parsed.resetAt>$.now,X=$.parsed.window==="primary"||$.parsed.window==="secondary"?$.reading?.[$.parsed.window]:void 0,z=!J&&X&&X.resetsAt&&Date.parse(X.resetsAt)===Z&&X2(X.checkedAt,$.now),G=J?$.resetSource==="retry-after"?"unproven":"provider":z?"reading":"unproven";return{command:{type:"mark",binding:$.binding,baseRevision:$.baseRevision,producerId:$.producerId,operationId:$.operationId,scope:{kind:"pool"},window:"account",cause:"rate-limit",until:Z,evidenceAt:$.evidenceAt,mergeLaw:"max-until"},provenance:{accountKey:$.binding.account,expiry:Z,branch:G,observedAt:z?X.checkedAt:$.observedAt,evidenceAt:$.evidenceAt}}}var e9=t("quota"),M7="the account holds a tombstone from the removed vault custody, not a credential";function TG($){return $?.status===401}async function fF($,Z={}){let J=$.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let X=[],z=$.logger??e9,G=(q)=>{X.push(q);let F={pid:process.pid,accountId:q.account,status:q.ok?"ok":"error",...q.error?{error:q.error}:{}};if(q.ok)z.debug("quota refresh succeeded",F);else z.warn("quota refresh failed",F)},Q=$.skipFresherThanMs,Y=!1,B;if(Q!==void 0)try{B=await $.readSidebarState()}catch{}let W=new Map(B?.fallbacks.map((q)=>[q.id,q])??[]),H=(...q)=>Q!==void 0&&q.some((F)=>typeof F==="number"&&Number.isFinite(F)&&F<=$.now()&&$.now()-F<Q),V=await $.loadAccounts($.paths).catch(()=>{return}),U=V?.mainAccountId??$.storageMainAccountId,j;if(!Z.accountKey||Z.accountKey==="main")try{let q=await $.getAuth();if(O7(q)){if(j=_7(V),!j)G({account:"main",ok:!1,error:b1(q)?M7:"main account row is missing from the account pool"})}else if(q.type==="oauth"){let F=B&&U!==void 0&&B.main.mainAccountId===U?B.main.quota:void 0;if(H($.quotaManager.peekMainForPolicy(U)?.checkedAt,F?.primary?.checkedAt,F?.secondary?.checkedAt,F?.checkedAt))G({account:"main",ok:!0});else{if(!q.access||(q.expires??0)<$.now()){let N=await $.refreshMainWithLease();q={...q,access:N.access,expires:N.expires}}if(q.access)if($.respectBackoff&&$.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let N=await J({accessToken:q.access,fetchImpl:$.fetchImpl,now:$.now,accountId:U,accountKey:"main"});$.quotaManager.setMain(q.access,{quota:N,refreshAfter:$.now()+300000,checkedAt:$.now()},U,!0),Y=!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(q){G({account:"main",ok:!1,error:x0(q)})}if(V)for(let q of V.accounts){let F=j!==void 0&&q===j;if(!F&&Z.accountKey&&(Z.accountKey==="main"||q.id!==Z.accountKey))continue;if(!F&&$.isOAuthAccountFn(q)&&L7(V,q)){if(Z.accountKey)G({account:q.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let K=F?q.accountId??U:void 0,N=(D,T,M)=>{if(F)$.quotaManager.setMain(T,D,K,!0);else $.quotaManager.setFallback(q.id,D,T,!0,M)};if(q.enabled===!1||!$.isOAuthAccountFn(q)){if(Z.accountKey)G({account:q.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let D=W.get(q.id),T=q.accountId,M=F?B&&K!==void 0&&B.main.mainAccountId===K?B.main.quota:void 0:D&&T!==void 0&&D.accountId===T?D.quota:void 0;if(H(F?$.quotaManager.peekMainForPolicy(K)?.checkedAt:$.quotaManager.peekFallbackForPolicy(q.id,T)?.checkedAt,M?.primary?.checkedAt,M?.secondary?.checkedAt,M?.checkedAt)){G({account:q.id,ok:!0});continue}if($.respectBackoff&&(F?$.quotaManager.isBackedOff():$.quotaManager.isFallbackBackedOff(q.id,q.access))){G({account:q.id,ok:!0});continue}let P=q.lastRefreshError;if(C7(P,q.refresh,$.now())){G({account:q.id,ok:!1,error:T7(P,$.now()),permanent:!0});continue}if(b1(q)){G({account:q.id,ok:!1,error:M7});continue}let O;try{O=F?await $.fallbackManager.refreshAccount(q,V,{asPoolMain:!0}):await $.fallbackManager.refreshAccount(q,V)}catch(L){e9.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:q.id,error:x0(L)}),O=q}if(!O.access||(O.expires??0)<$.now()){G({account:q.id,ok:!1,error:"no usable access token"});continue}let C;try{C=await J({accessToken:O.access,fetchImpl:$.fetchImpl,now:$.now,accountId:O.accountId,accountKey:q.id})}catch(L){if(!TG(L))throw L;if(e9.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:q.id}),O=await $.fallbackManager.refreshAccount(q,V,F?{force:!0,asPoolMain:!0}:{force:!0}),!O.access){G({account:q.id,ok:!1,error:"no usable access token after forced refresh"});continue}C=await J({accessToken:O.access,fetchImpl:$.fetchImpl,now:$.now,accountId:O.accountId,accountKey:q.id})}N({quota:C,refreshAfter:$.now()+300000,checkedAt:$.now()},O.access,O.accountId),Y=!0,G({account:q.id,ok:!0})}catch(D){G({account:q.id,ok:!1,error:x0(D)})}}if(Z.accountKey&&Z.accountKey!=="main"&&!X.some((q)=>q.account===Z.accountKey))X.push({account:Z.accountKey,ok:!1,error:"account not found"});if(Q===void 0||Y){let q=await $.loadAccounts($.paths);await $.writeSidebarState($.quotaManager,q)}return X}function LG($){try{let Z=JSON.parse($)?.model;if(typeof Z!=="string")return!1;let J=/^gpt-(\d+)(?:\.(\d+))?(?:-|$)/.exec(Z);if(!J)return!1;let X=Number(J[1]),z=Number(J[2]??0);return X>5||X===5&&z>=6}catch{return!1}}function mF($,Z=300000){return LG($)?1800000:Z}function wF($,Z,J,X){if(!J||X.kind==="synthetic")return!1;if(X.aborted)return!1;return(X.kind==="http"?X.completed&&!X.failed:X.kind==="ws"?X.event==="response.completed":X.kind==="pi"?X.stop==="stop":X.status>=200&&X.status<300)&&$.recordAccepted({sessionId:Z.sessionId,accountKey:Z.accountKey,currentAccountKey:J,lastAcceptedAt:Z.dispatchedAt,ttlMs:Z.ttlMs})}import{createHash as _G,randomUUID as SG}from"node:crypto";var E7=["cost-cap","count-cap","deadline-missed","outside-hours","session-ended","unsupported"];function x1($){return E7.some((Z)=>Z===$)}var S7=new Set;function R7($,Z=new Set){if(typeof $!=="object"||$===null)return`${typeof $}:${String($)}`;if(Z.has($))return"cycle";return Z.add($),`${Array.isArray($)?"array":"object"}:{${Object.entries(Object.getOwnPropertyDescriptors($)).sort(([J],[X])=>J.localeCompare(X)).map(([J,X])=>`${J}:${"value"in X?R7(X.value,Z):"accessor"}`).join(",")}}`}function k1($,Z){let J="unreadable";try{J=R7(Z)}catch{}try{let X=`${$}:${J}`;if(!S7.has(X))S7.add(X),console.warn(`[common-auth] Ignoring invalid session ${$} policy`)}catch{}return null}function $$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function OG($){if(typeof $.then!=="function")return!1;return Promise.resolve($).catch(()=>{}),!0}function A7($,Z){return Reflect.ownKeys($).every((J)=>typeof J==="string"&&Z.includes(J))}function Z$($){let Z;try{let J=Z2($);if(!J)return null;let X=J.cache;if(typeof X!=="function")return null;if(Z=X.call(J),Z===null)return null;if(!$$(Z)||OG(Z))return k1("cache",Z);let{ttl:z,keep_warm:G,hours:Q}=Z;if(!A7(Z,["ttl","keep_warm","hours"])||z!==void 0&&z!=="none"&&z!=="short"&&z!=="long"||G!==void 0&&G!=="off"&&G!=="hours"&&G!=="always"&&G!=="auto"||z==="none"&&G!==void 0&&G!=="off"||G!=="hours"&&"hours"in Z)return k1("cache",Z);let Y={...z!==void 0?{ttl:z}:{},...G!==void 0?{keep_warm:G}:{}};if(G==="hours"){if(!$$(Q)||!A7(Q,["from","to","tz"]))return k1("cache",Z);let{from:B,to:W,tz:H}=Q,V=/^(?:[01]\d|2[0-3]):[0-5]\d$/;if(typeof B!=="string"||!V.test(B)||typeof W!=="string"||!V.test(W)||B===W||typeof H!=="string"||H.length===0)return k1("cache",Z);new Intl.DateTimeFormat("en",{timeZone:H}),Y.hours={from:B,to:W,tz:H}}return Y}catch{return k1("cache",Z)}}function I7($,Z){let J=Z2($);if(!J)return;let X=J.report;if(typeof X!=="function")return;let z=X.call(J,Z);if($$(z)&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}function r4($,Z){try{let{at:J,ttlMs:X,source:z}=Z;if(!Number.isSafeInteger(J)||J<0||X!=="implicit"&&(typeof X!=="number"||!Number.isFinite(X)||X<0)||z!=="response"&&z!=="warm")return;I7($,{kind:"cache_touch",at:J,ttl_ms:X,source:z})}catch{}}function J$($,Z){try{let{at:J,reason:X}=Z;if(!Number.isSafeInteger(J)||J<0||typeof X!=="string")return;I7($,{kind:"cache_warm_stopped",at:J,reason:X})}catch{}}var X$=128,AG=["account_limit","account_free","rate_limited","server_busy","quota_reading","routing_hold"];function _0($){return typeof $==="object"&&$!==null}function i($){return typeof $==="string"&&$.length>0}function l0($,Z){return i($)&&$.length<=Z&&!/\p{Cc}/u.test($)}function o4($){return typeof $==="string"&&/^[a-z0-9._-]{1,64}$/.test($)}function EG($){if(!_0($)||Array.isArray($))return;let{accountId:Z,credentialId:J,limitWindow:X,observedAtMs:z}=$;if(!l0(Z,256)||!l0(J,256)||typeof z!=="number"||!Number.isSafeInteger(z)||z<=0||X!=="five_hour"&&X!=="seven_day"&&X!=="signed_out")return;let G={account:Z,credential_id:J,limit_window:X,observed_at_ms:z};if(X==="signed_out"){if("pool"in $||"resetsAtMs"in $||"retryAfterS"in $)return;return G}let{pool:Q,resetsAtMs:Y,retryAfterS:B}=$;if(Q!==void 0&&!o4(Q)||Y!==void 0&&(typeof Y!=="number"||!Number.isSafeInteger(Y)||Y<=0)||B!==void 0&&(typeof B!=="number"||!Number.isFinite(B)||B<0))return;return{...G,...Q!==void 0?{pool:Q}:{},...Y!==void 0?{resets_at_ms:Y}:{},...B!==void 0?{retry_after_s:Math.floor(B)}:{}}}function RG($){if(!_0($)||Array.isArray($))return;let{ttlMs:Z,implicit:J,warming:X}=$,z={};if(!(Z!==void 0&&J!==void 0)){if(typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>0)z.ttl_ms=Z;else if(J===!0)z.implicit=!0}if(_0(X)&&!Array.isArray(X)){let{on:G,stopReason:Q}=X;if(typeof G==="boolean")z.warming={on:G,...!G&&x1(Q)?{stop_reason:Q}:{}}}return Object.keys(z).length>0?z:void 0}function b7($){if(!_0($)||Array.isArray($))return;let Z={};for(let[X,z]of[["input","input"],["output","output"],["cacheRead","cache_read"],["cacheWrite","cache_write"],["cacheWrite5m","cache_write_5m"],["cacheWrite1h","cache_write_1h"],["reasoning","reasoning"]]){let G=$[X];if(typeof G==="number"&&Number.isSafeInteger(G)&&G>=0)Z[z]=G}let J=$.reasoningIncludedInOutput;if(typeof J==="boolean")Z.reasoning_included_in_output=J;return Object.keys(Z).length>0?Z:void 0}function IG($){let Z=[];for(let{accountId:z,credentialId:G}of $)if(i(z)&&l0(G,256))Z.push({account_id:z,credential_id:G});let J=Z.map(({account_id:z,credential_id:G})=>Buffer.from(`${z} ${G}
68
+ `,"utf8")).sort(Buffer.compare),X=_G("sha256");for(let z of J)X.update(z);return{view_digest:X.digest("hex"),accounts:Z}}function bG($,Z){if(!_0($))return;let{account_id:J,credential_id:X}=$;if(typeof J!=="string")return;if(X!==void 0&&typeof X!=="string")return;let z=Z.find((Y)=>Y.accountId===J&&(X===void 0||Y.credentialId===X));if(!z)return;let G=$.hold,Q=_0(G)?G.retry_after_ms:void 0;if(typeof Q==="number"&&Number.isFinite(Q)&&Q>=0)return{candidate:z,hold:{retry_after_ms:Q}};return{candidate:z}}function kG($){if(!_0($))return;let Z=$.code;if(Z!=="account_limit_exhausted"&&Z!=="account_selection_refused"&&Z!=="account_selection_final"&&Z!=="concurrency_full")return;let J={code:Z},{routing_code:X,reason:z}=$;if(o4(X))J.routingCode=X;if(o4(z))J.reason=z;let G=$.retry_after_secs;if(typeof G==="number"&&Number.isFinite(G)&&G>=0)J.retryAfterSecs=G;let Q=$.resets_at_ms;if(typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>0)J.resetsAtMs=Q;else if(Z==="concurrency_full")return;return{refused:J}}function z$($){return k7($,!1)}async function k7($,Z){let J;try{let X={provider:$.provider,modelId:$.modelId},{requestId:z}=$;if($.mode==="continue"){if(!l0(z,X$))return;let F=EG($.exhausted);if(!F)return;X.mode="continue",X.request_id=z,X.exhausted=F}else if($.mode===void 0&&l0(z,X$))X.request_id=z;let G=Z2($.sessionId);if(!G)return;let Q=G.accountFor;if(typeof Q!=="function")return;let Y=$.deadlineMs??1500,B=Number.isNaN(Y)?1500:Math.min(2000,Math.max(1,Y)),W=new Promise((F)=>{J=setTimeout(()=>F(void 0),B),J.unref()}),H=$.holdWaitMaxS;if(typeof H==="number"&&Number.isFinite(H))X.hold_wait_max_s=Math.max(0,Math.floor(H));if($.refusals===!0)X.refusals=!0;if(Z)X.waits_for_capacity=!0;let V=$.warmCredentialId;if(l0(V,256)&&$.candidates.some((F)=>F.credentialId===V))X.warm_credential=V;let U=IG($.candidates);if(U.accounts.length>0||X.mode==="continue")X.candidates=U;let j=Q.call(G,X,{deadlineMs:B});if(!_0(j)||typeof j.then!=="function")return;let q=await Promise.race([j,W]);if($.refusals===!0&&_0(q)&&"refused"in q)return kG(q.refused);return bG(q,$.candidates)}catch{return}finally{clearTimeout(J)}}async function xG($,Z){do{Z?.throwIfAborted();let J=Math.min($,2147483647);await new Promise((X,z)=>{function G(){clearTimeout(Q),z(Z?.reason)}let Q=setTimeout(()=>{Z?.removeEventListener("abort",G),X()},J);Q.unref(),Z?.addEventListener("abort",G,{once:!0})}),$-=J}while($>0)}async function x7($,Z){let{signal:J,now:X=Date.now,sleep:z=xG}=Z;J?.throwIfAborted();let G=$.mode==="continue"?{...$,refusals:!0}:{...$,refusals:!0,requestId:l0($.requestId,X$)?$.requestId:SG()};async function Q(){while(!0){J?.throwIfAborted();let Y=await k7(G,!0);if(J?.throwIfAborted(),Y&&"refused"in Y){let{code:B,resetsAtMs:W}=Y.refused;if(B==="concurrency_full"&&W!==void 0){let H=W-X();J?.throwIfAborted(),await z(H<0?1000:H,J);continue}}return Y}}if(!J)return Q();return new Promise((Y,B)=>{let W=()=>B(J.reason);J.addEventListener("abort",W,{once:!0}),Q().finally(()=>J.removeEventListener("abort",W)).then(Y,B)})}function z2($){try{let Z=$.sessionId,J=Z2(Z);if(!J)return;let X=J.report;if(typeof X!=="function")return;let z;if("kind"in $)switch($.kind){case"transient_backoff":{let{accountId:Q,credentialId:Y,retryAtMs:B,providerCode:W}=$;if(!i(Z)||!i(Q)||!Number.isSafeInteger(B)||B<=0||Y!==void 0&&!l0(Y,256)||W!==void 0&&!l0(W,128))return;z={kind:"transient_backoff",account_id:Q,...Y!==void 0?{credential_id:Y}:{},retry_at_ms:B,...W!==void 0?{provider_code:W}:{}};break}case"wait":{let{phase:Q,waitId:Y,reason:B,nextMs:W,attempt:H,message:V,outcome:U}=$;if(!i(Z)||Q!=="start"&&Q!=="end"||!i(Y)||Y.length>64||/[^A-Za-z0-9._:-]/.test(Y)||!AG.includes(B))return;z={kind:"wait",phase:Q,wait_id:Y,reason:B,...typeof W==="number"&&Number.isSafeInteger(W)&&W>0?{next_ms:W}:{},...typeof H==="number"&&Number.isInteger(H)&&H>=1?{attempt:H}:{},...typeof V==="string"&&V.length>=1&&V.length<=160&&!/\p{Cc}/u.test(V)?{message:V}:{},...Q==="end"&&(U==="resumed"||U==="cancelled"||U==="abandoned")?{outcome:U}:{}};break}case"billing":{let{attemptId:Q,requestKind:Y,credentialId:B,provider:W,model:H,outcome:V,accountId:U,providerRequestId:j,providerResponseId:q,userMessageId:F,status:K,attempt:N,chargeBasis:D,usage:T,usageByModel:M,cache:P}=$;if(!i(Q)||!i(B)||!i(W)||!i(H)||Y!=="primary"&&Y!=="title"&&Y!=="compaction"&&Y!=="generate"&&Y!=="keep_warm"&&Y!=="prime"||V!=="completed"&&V!=="cut"&&V!=="failed")return;let O=b7(T),C=RG(P),L=[];if(Array.isArray(M))for(let A of M){if(!_0(A)||Array.isArray(A))continue;let x=A.modelUsed;if(!i(x))continue;let I=b7(A.usage);if(!I)continue;L.push({model_used:x,usage:I})}z={kind:"billing",attempt_id:Q,request_kind:Y,credential_id:B,provider:W,model:H,outcome:V,...i(U)?{account_id:U}:{},...i(j)?{provider_request_id:j}:{},...i(q)?{provider_response_id:q}:{},...i(F)?{user_message_id:F}:{},...typeof K==="number"&&Number.isInteger(K)&&K>=0?{status:K}:{},...typeof N==="number"&&Number.isInteger(N)&&N>=1?{attempt:N}:{},...D==="subscription_included"||D==="metered_api"?{charge_basis:D}:{},...O?{usage:O}:{},...L.length>0?{usage_by_model:L}:{},...C?{cache:C}:{}};break}case"turn_notes_supported":{let{model:Q,supported:Y}=$;if(typeof Q!=="string"||Q.length===0||typeof Y!=="boolean")return;z={kind:"turn_notes_supported",model:Q,supported:Y};break}case"turn_note_skipped":{let{after_tool_use_id:Q,reason:Y}=$;if(typeof Q!=="string"||Q.length===0||Y!=="anchor_missing"&&Y!=="before_user_message"&&Y!=="unsupported_model"&&Y!=="not_oauth")return;z={kind:"turn_note_skipped",after_tool_use_id:Q,reason:Y};break}default:return}else{let Q={account_id:$.accountId,...$.credentialId!==void 0?{credential_id:$.credentialId}:{}};switch($.outcome){case"served":z={...Q,outcome:"served",headers:$.headers};break;case"exhausted":{let{window:Y,pool:B}=$;if(Y!=="5h"&&Y!=="7d")return;if(B!==void 0&&!o4(B))return;z={...Q,outcome:"exhausted",window:Y,...B?{pool:B}:{},...$.resetsAt!==void 0?{resets_at:$.resetsAt}:{}};break}case"credential_refused":{let{credentialId:Y,providerCode:B}=$;if(!i(Y)||typeof B!=="string"||!/^[a-z0-9._-]{1,64}$/.test(B))return;z={...Q,outcome:"credential_refused",provider_code:B};break}default:return}}let G=X.call(J,z);if(_0(G)&&typeof G.then==="function")Promise.resolve(G).catch(()=>{})}catch{}}function y7($){if($.accountKey)return O9({...$,accountKey:$.accountKey});try{let Z=Reflect.get(globalThis,Symbol.for("cortexkit.routing"));return typeof(typeof Z==="function"?Z($.sessionId):void 0)?.accountFor==="function"?0:void 0}catch{return}}var XK="Thalamus routing declined this request, so it was not sent.";function zK($){if(!("refused"in $))return;let{code:Z,retryAfterSecs:J}=$.refused;if(Z==="account_selection_refused"&&typeof J==="number"&&J>0&&J<=5)return J*1000;return}function G2(){try{return typeof Reflect.get(globalThis,Symbol.for("cortexkit.routing"))==="function"}catch{return!1}}var yG={account_limit:"Waiting for the account limit to reset",account_free:"Waiting for an account to come free",quota_reading:"Checking account quota"};function GK($){let Z=$.nextMs===void 0?$.boundMs??0:$.nextMs-$.now;if(!$.sessionId||!G2()||Z<2000)return;let J={sessionId:$.sessionId,kind:"wait",waitId:crypto.randomUUID(),reason:$.reason,...$.nextMs===void 0?{}:{nextMs:$.nextMs},...$.attempt===void 0?{}:{attempt:$.attempt},message:yG[$.reason]};z2({...J,phase:"start"});let X=!1;return(z)=>{if(X)return;X=!0,z2({...J,phase:"end",outcome:z})}}async function QK($){let{request:Z,sessionId:J,continuation:X}=$;if(!$.vaultMode||!G2()||!J||!Z?.modelId||!X&&(!$.fresh||Z.retry))return;let z=$.eligibleIds&&new Set($.eligibleIds),G=$.routing.rows.filter((j)=>!z||z.has(j.id)),Q=X&&f7({...$.routing,rows:G,placement:"roster",mainId:null}),Y=new Set(!Q?G.filter((j)=>$.routing.killswitch.get(j.id)!==!1).map((j)=>j.id):Q.kind==="send"?Q.order.filter((j)=>Q.tiers[j]!=="last-path"):[]),B=$.routes.flatMap((j)=>j.id!==X?.previousId&&Y.has(j.id)&&j.identity&&j.credentialId?[{accountId:j.identity,credentialId:j.credentialId,id:j.id}]:[]);if(X){let{accountId:j,credentialId:q}=X.exhausted;B.push({accountId:j,credentialId:q,id:X.previousId})}if(B.length===0)return;let W=y7({...$.wait,sessionId:J,now:$.routing.now}),H={sessionId:J,provider:"openai",modelId:Z.modelId,candidates:B,warmCredentialId:$.routes.find((j)=>j.id===$.warmAccountId)?.credentialId,refusals:!0,holdWaitMaxS:W},V=X?await z$({...H,mode:"continue",exhausted:X.exhausted,requestId:crypto.randomUUID()}):$.capacityWait?await x7({...H,requestId:crypto.randomUUID()},$.capacityWait):await z$(H);if(!V||"refused"in V)return V;if(V.candidate.id!==X?.previousId)return V.candidate.id;if(!V.hold)return{holdMs:0};let U=V.hold.retry_after_ms;if(!W||U>W*1000)return{refused:{code:"account_selection_refused"}};return{holdMs:U}}var gG=["x-codex-primary-used-percent","x-codex-primary-window-minutes","x-codex-primary-reset-at","x-codex-secondary-used-percent","x-codex-secondary-window-minutes","x-codex-secondary-reset-at","retry-after","retry-after-ms"],v7=new Set(["usage_limit_reached","insufficient_quota","quota_exceeded"]);function h7($,Z){let J=$.get("retry-after-ms");if(J?.trim()&&Number.isFinite(Number(J))&&Number(J)>=0)return Z+Number(J);let X=$.get("retry-after");if(!X?.trim())return;let z=Number(X);if(Number.isFinite(z)&&z>=0)return Z+z*1000;let G=Date.parse(X);return Number.isFinite(G)?G:void 0}function m7($,Z,J){return typeof $==="number"&&Number.isFinite($)&&$>0?$*1000:typeof Z==="number"&&Number.isFinite(Z)&&Z>0?J+Z*1000:void 0}function fG($,Z,J,X={}){if(!G2()||!$||!Z?.accountIdentity)return;if(!v7.has(J.window)&&!["primary","secondary","5h","7d"].includes(J.window))return;let z=E(X.body)?X.body:void 0,G=E(z?.response)?z.response:z,Q=E(G?.error)?G.error:G,Y=E(G?.failed)?G.failed:void 0,B=typeof Y?.rate_limit_reached_type==="string"?Y.rate_limit_reached_type:typeof Q?.rate_limit_reached_type==="string"?Q.rate_limit_reached_type:typeof Q?.window==="string"?Q.window:J.window,W=g7(X.quota),H=B==="primary"||B==="secondary"?B:void 0,V=H?Number(X.headers?.get(`x-codex-${H}-window-minutes`)??W?.[H]?.windowMinutes):void 0,U=V===300?"5h":V===10080?"7d":B;if(U!=="5h"&&U!=="7d")return;let j=H?Number(X.headers?.get(`x-codex-${H}-reset-at`))*1000:NaN,q=Q?.resets_at??Y?.resets_at,F=Q?.resets_in_seconds??Y?.resets_in_seconds,K=X.now??Date.now(),N=m7(q,F,K),D=J.resetAt??N,T=D!==void 0&&Number.isFinite(D)&&D>0?D:Number.isFinite(j)&&j>0?j:X.headers?h7(X.headers,K):void 0;return z2({sessionId:$,accountId:Z.accountIdentity,credentialId:Z.credentialId,outcome:"exhausted",window:U,...T!==void 0?{resetsAt:T}:{}}),{accountId:Z.accountIdentity,credentialId:Z.credentialId,limitWindow:U==="5h"?"five_hour":"seven_day",observedAtMs:K,...T!==void 0?{resetsAtMs:T}:{}}}function BK($,Z,J){if(!$||!Z||J.failed||!G2())return;let{status:X,headers:z}=J,G=Z.accountIdentity?{sessionId:$,accountId:Z.accountIdentity,credentialId:Z.credentialId}:void 0;if(X===429||X===403){let Y=E(J.body)?J.body:void 0,B=E(Y?.response)?Y.response:Y,W=E(B?.error)?B.error:B,H=J.limit?.window,V=typeof W?.code==="string"?W.code:void 0,U=typeof W?.type==="string"&&!["error","response.failed"].includes(W.type)?W.type:void 0,j=[H,V,U].find((K)=>K!==void 0&&v7.has(K)),q=Y?.type==="response.failed"&&E(B?.failed)&&typeof B.failed.rate_limit_reached_type==="string"?B.failed.rate_limit_reached_type:void 0,F=q??j;if(X===429&&F){let K=q??(typeof W?.rate_limit_reached_type==="string"?W.rate_limit_reached_type:typeof W?.window==="string"?W.window:F),N=fG($,Z,{window:K,resetAt:J.limit?.resetAt},{headers:z,quota:J.quota,now:J.now,body:Y});if(N)return{kind:"exhausted",exhausted:N}}if(J.backoff){let K=J.now??Date.now(),N=Math.ceil(h7(z,K)??J.limit?.resetAt??m7(W?.resets_at,W?.resets_in_seconds,K)??K+5000);if(G)z2({...G,kind:"transient_backoff",retryAtMs:N,providerCode:V||U||`http_${X}`});return{kind:"backoff",retryAtMs:N,credentialId:Z.credentialId,...Z.accountIdentity!==void 0?{accountIdentity:Z.accountIdentity}:{}}}return}if(!G||X<200||X>=300)return;let Q={};for(let Y of gG){let B=z.get(Y);if(B!==null)Q[Y]=B}z2({...G,outcome:"served",headers:Q})}function YK($){return E($)&&($.type==="error"||$.type==="response.failed"||E($.response)&&$.response.status==="failed")}function WK($){return $.includes('"response.failed"')||$.includes('"type":"error"')||$.includes('"error"')&&/"type"\s*:\s*"error"/.test($)||$.includes('"failed"')&&/"status"\s*:\s*"failed"/.test($)}function vG($){let Z=Z$($);if(!Z?.keep_warm)return;return{mode:Z.keep_warm,hours:Z.hours}}function qK($,Z){let J=vG($);return J?J.mode!=="off":Z}function jK($,Z){r4($,{...Z,ttlMs:"implicit",source:"warm"})}function FK($,Z){J$($,Z)}function hG($,Z){setTimeout(()=>{r4($,{at:Z,ttlMs:"implicit",source:"response"})},0)}function KK($,Z,J=Date.now){if(!Z||!$.ok||!G2())return $;let X=()=>{hG(Z,J())};if(!$.body)return X(),$;let z=$.body.getReader();return new Response(new ReadableStream({async pull(G){try{let Q=await z.read();if(Q.done)G.close(),X();else G.enqueue(Q.value)}catch(Q){G.error(Q)}},cancel(G){return z.cancel(G)}},{highWaterMark:0}),{status:$.status,statusText:$.statusText,headers:$.headers})}import{types as mG}from"node:util";var wG=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,uG=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function d7($){return $.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,(Z,J,X)=>{if(J)return String.fromCharCode(Number.parseInt(J,16));return{b:"\b",f:"\f",n:`
69
+ `,r:"\r",t:"\t"}[X]??X??Z})}function pG($,Z){if(!Z)return $;let J=$.split(Z).join("[credential]"),X=Z.replace(/\s/g,"");if(!X)return J;let z=J.replace(/\s/g,"");if(!z.includes(X))return J;let G=[];for(let B=0;B<J.length;B++){let W=J[B]??"";if(!/\s/.test(W))G.push(B)}let Q=[],Y=0;for(let B=z.indexOf(X);B>=0;B=z.indexOf(X,B+X.length)){let W=G[B]??Y,H=(G[B+X.length-1]??W)+1;Q.push(J.slice(Y,W),"[credential]"),Y=H}return Q.length?Q.join("")+J.slice(Y):J}function w7($,Z){let J=pG($,Z);return l7(J).replaceAll("***REDACTED***","[credential]")}function c2($,Z){let J=w7($,Z),X=d7(J),z=w7(X,Z);return z===X?J:z}function u7($){let Z=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec($);if(!Z)return;let J=Z[3]??"",X=(Z[2]??"")+J,z=0;while(X[z]==="0")z++;if(z===X.length)return"0";let G=X.length;while(X[G-1]==="0")G--;let Q=Z[4]??"0",Y=Q.startsWith("-")||Q.startsWith("+")?1:0;while(Q[Y]==="0")Y++;let B=Q.slice(Y)||"0";if(B.length>16)return;let W=BigInt((Q.startsWith("-")?"-":"")+B)-BigInt(J.length)+BigInt(X.length-G);return`${Z[1]}${X.slice(z,G)}e${W}`}function c7($,Z){let J=Z?u7(Z):void 0;return $.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(X)=>{if(!X.startsWith('"'))return Z&&(X===Z||J!==void 0&&u7(X)===J||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(X)&&String(Number(X))===Z)?'"[credential]"':X;let z=d7(X.slice(1,-1)),G=c2(z,Z);return G===z?X:JSON.stringify(G)})}function t4($,Z){let J=c7($,Z);try{return JSON.parse($),J}catch{return c2(J,Z)}}var lG=16384,s7=65536,dG="No diagnostic was received.";async function cG($){if(!$)return"";let Z=$.getReader(),J=new Uint8Array(s7),X=new TextDecoder,z=performance.now()+2000,G=0,Q;try{let Y=async()=>{while(performance.now()<z){let{done:B,value:W}=await Z.read();if(B)return X.decode(J.subarray(0,G));if(G+W.byteLength>J.byteLength)return;J.set(W,G),G+=W.byteLength}return};return await Promise.race([Y(),new Promise((B)=>{Q=setTimeout(B,2000,void 0)})])}catch{return}finally{clearTimeout(Q),Z.cancel().catch(()=>{})}}var sG=[/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 nG($){try{let Z=d(JSON.parse($),"request_id");if(typeof Z==="string")return Z;if(typeof Z!=="number")return;let J=0,X,z=!0,G=!1,Q;for(let Y of $.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let B=Y[0];if(B==="{"||B==="["){J++;continue}if(B==="}"||B==="]"){J--;continue}if(J!==1)continue;if(B===","){z=!0,G=!1,X=void 0;continue}if(B===":"){G=!0;continue}if(z&&B.startsWith('"')){X=JSON.parse(B),z=!1;continue}if(G&&X==="request_id"&&!B.startsWith('"'))Q=B;G=!1}return Q}catch{return}}function aG($,Z){let J=t4($,Z);if(Buffer.byteLength(J,"utf8")<=s7)return J;let X=sG.flatMap((G)=>G.exec(J)?.[0]??[]);for(let G of["FreeUsageLimitError","GoUsageLimitError"])if(J.includes(G))X.push(G);let z={retry:X};try{let G=JSON.parse(J);if(d(G,"type")==="error")z.type="error";let Q=d(G,"error"),Y={};for(let W of["code","type"]){let H=d(Q,W);if(typeof H==="string")Y[W]=H.slice(0,256)}if(Object.keys(Y).length)z.error=Y;let B={};for(let W of["workspace","limitName"]){let H=d(d(G,"metadata"),W);if(typeof H==="string")B[W]=H.slice(0,256)}if(Object.keys(B).length)z.metadata=B}catch{}return JSON.stringify(z)}function e4($){if(!$||typeof $!=="object")return!1;let Z=$;for(let J=0;Z&&J<16;J++){if(mG.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function d($,Z){if(!e4($))return;let J=Object.getOwnPropertyDescriptor($,Z);return J&&"value"in J?J.value:void 0}function y1($,Z){return c2($,Z).slice(0,lG)}function s2($,Z){let J=Object.getOwnPropertyDescriptor($,Z)?.get;if(!J)throw Error(`Missing native ${Z} accessor`);return J}var iG=s2(DOMException.prototype,"message"),rG=s2(DOMException.prototype,"name");function G$($,Z){let J=d($,"message"),X=d($,"name");if(e4($)&&$ instanceof DOMException)try{J=iG.call($),X=rG.call($)}catch{}let z=Error(y1(typeof J==="string"?J:typeof $==="string"?$:"Provider request failed",Z));for(let V of Object.getOwnPropertyNames(z))if(V!=="message")Reflect.deleteProperty(z,V);Object.defineProperty(z,"name",{value:typeof X==="string"?y1(X,Z):"Error",configurable:!0,writable:!0});let G=(V,U,j)=>{let q=d(V,j);if(typeof q==="string"||typeof q==="number"&&Number.isFinite(q)||typeof q==="boolean")Object.defineProperty(U,j,{value:typeof q==="string"?y1(q,Z):q,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let U=d($,V);if(typeof U==="number"&&Number.isFinite(U))G($,z,V)}for(let V of["code","type","isRetryable"])G($,z,V);for(let V of["error","data"]){let U=d($,V),j=Object.create(null);for(let F of["type","code","message","resets_at","resets_in_seconds"])G(U,j,F);let q=d(U,"error");if(e4(q)){let F=Object.create(null);for(let K of["type","code","message","resets_at","resets_in_seconds"])G(q,F,K);j.error=F}if(Object.keys(j).length)Object.defineProperty(z,V,{value:j,enumerable:!0})}let Q=d($,"responseHeaders");if(Q&&typeof Q==="object"){let V={};for(let U of["retry-after-ms","retry-after"]){let j=d(Q,U);if(typeof j==="string")V[U]=y1(j,Z)}Object.defineProperty(z,"responseHeaders",{value:V,enumerable:!0})}let Y=d($,"responseBody");if(typeof Y==="string")Object.defineProperty(z,"responseBody",{value:aG(Y,Z),enumerable:!0});let B=d($,"request_id"),W=d(Q,"x-request-id"),H=typeof B==="string"?B:typeof W==="string"?W:typeof Y==="string"?nG(t4(Y,Z)):void 0;if(typeof H==="string")Object.defineProperty(z,"request_id",{value:y1(H,Z),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let U=Symbol.for(V);if(d($,U)===!0)Object.defineProperty(z,U,{value:!0})}return z}function oG($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!wG.test($)&&!uG.test($)))return $;let J;try{J=JSON.parse($)}catch{return $}if(J?.type==="error"||J?.error||J?.response?.error)return c7($,Z);return $}var tG=s2(Response.prototype,"status"),eG=s2(Response.prototype,"statusText"),$Q=s2(Response.prototype,"headers"),ZQ=s2(Response.prototype,"body"),JQ=Response.prototype.text,p7=Headers.prototype.entries;async function MK($,Z,J="http",X){try{let q=function(F){let K=j&&F.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,K+F.slice(K.length).replace(/^data: ?([^\r\n]*)/gm,(N,D)=>N.slice(0,N.length-D.length)+oG(D,Z))};if(!e4($))throw Error("Invalid provider response");let z=tG.call($),G=$Q.call($),Q=ZQ.call($),Y=new Headers;for(let[F,K]of p7.call(G))Y.append(F,K);let B={status:z,statusText:c2(eG.call($),Z),headers:Y};if(z<200||z>299){for(let[K,N]of p7.call(G)){if(c2(K,Z?.toLowerCase())!==K){B.headers.delete(K);continue}try{B.headers.set(K,c2(N,Z))}catch{B.headers.delete(K)}}if(B.headers.delete("content-length"),X?.boundRefusal&&(z===403||z===429)){let K=await cG(Q);return new Response(K===void 0?dG:t4(K,Z),B)}let F=await JQ.call($);return new Response(t4(F,Z),B)}if(!Q||J==="http")return $;B.headers.delete("content-length");let W=ReadableStream.prototype.getReader.call(Q),H=new TextDecoder("utf-8",{ignoreBOM:!0}),V=new TextEncoder,U="",j=!0;return new Response(new ReadableStream({async pull(F){try{for(;;){let K=await W.read();U+=H.decode(K.value,{stream:!K.done});let N=!1;for(;;){let D=/\r?\n\r?\n/.exec(U);if(!D)break;let T=D.index+D[0].length;F.enqueue(V.encode(q(U.slice(0,T)))),U=U.slice(T),N=!0}if(K.done){if(U)F.enqueue(V.encode(q(U)));F.close();return}if(N)return}}catch(K){F.error(G$(K,Z))}},async cancel(F){try{await W.cancel(F)}catch(K){throw G$(K,Z)}finally{W.releaseLock()}}}),B)}catch(z){throw G$(z,Z)}}function $6($){return $.match(/^gpt-(\d+(?:\.\d+)?)/)?.[1]}function _K($,Z){if(!Array.isArray($)||typeof Z!=="string")return $;let J=$6(Z);if(!J)return $;let[X,z="0"]=J.split(".");if(Number(X)<6||Number(X)===6&&Number(z)<2)return $;let G;for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(!E(Y)||Y.type!=="function_call"||Object.hasOwn(Y,"status"))continue;G??=$.slice(),G[Q]={...Y,status:"completed"}}return G??$}import{createHash as XQ}from"node:crypto";function n7($){return JSON.stringify(Q$($))??"undefined"}function Q$($){if(Array.isArray($))return $.map(Q$);if(!E($))return $;return Object.fromEntries(Object.keys($).sort().map((Z)=>[Z,Q$($[Z])]))}function zQ($){let Z=$6($);return Z!==void 0&&Number(Z.split(".")[0])>=6}function a7($,Z){return E($)&&($.type==="message"||("role"in $))&&$.role===Z}function xK($,Z){let J=typeof $.model==="string"?$.model:"";if(!zQ(J))return;let X=E($.reasoning)?$.reasoning:void 0,z=typeof X?.effort==="string"?X.effort:void 0;if(!z)return;let G=Array.isArray($.input)?$.input:void 0;Z.effortUpdates??=[];let Q=Z.effortUpdates,Y=(U)=>XQ("sha256").update(n7(U)).digest("hex").slice(0,16);if(Z.pinnedEffort===void 0||Q.some((U)=>!G||!a7(G[U.anchor],"user")||Y(G[U.anchor])!==U.fingerprint)){Z.pinnedEffort=z,Z.effortUpdates=[];return}if(!G||G.length===0)return;let B=G.findLastIndex((U)=>a7(U,"user")),W=Q.at(-1),H=W?.effort??Z.pinnedEffort;if(B>=0&&z!==H)if(W?.anchor===B){let U=Q.at(-2)?.effort??Z.pinnedEffort;if(z===U)Q.pop();else W.effort=z}else Q.push({anchor:B,fingerprint:Y(G[B]),effort:z});else if(B<0&&z!==H)return;if(Q.some((U,j)=>j>0&&U.anchor<=(Q[j-1]?.anchor??-1))){Z.pinnedEffort=z,Z.effortUpdates=[];return}if($.reasoning={...X,effort:Z.pinnedEffort},Q.length===0)return;let V=G.slice();for(let U=Q.length-1;U>=0;U--){let j=Q[U];if(!j)continue;V.splice(j.anchor,0,{type:"configuration_update",reasoning:{effort:j.effort}})}$.input=V}import{createHash as GQ}from"node:crypto";var QQ=Buffer.from("6ba7b8129dad11d180b400c04fd430c8","hex");function i7($,Z){let J=GQ("sha1").update($).update(Z,"utf8").digest().subarray(0,16);return J[6]=J.readUInt8(6)&15|80,J[8]=J.readUInt8(8)&63|128,J}function BQ($,Z){let J=i7(i7(QQ,$),Z).toString("hex");return`msg_${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}function vK($,Z){let J=$.instructions;if(typeof J!=="string"||J.length===0)return;let X=Array.isArray($.input)?$.input:typeof $.input==="string"?[{type:"message",role:"user",content:[{type:"input_text",text:$.input}]}]:[],z=X[0],G=E(z)&&z.type==="additional_tools"?1:0,Q=$.prompt_cache_key;$.input=[...X.slice(0,G),{type:"message",...typeof Q==="string"&&{id:BQ(Q,J)},role:"developer",content:[{type:"input_text",text:J}],internal_chat_message_metadata_passthrough:{content_item_kinds:["model.base_instructions"],...Z?.responsesLite&&{content_item_metadata:[{provenance:{type:"harness",hook:!1}}]}}},...X.slice(G)],delete $.instructions}var r7={unproven:0,reading:1,provider:2};class B${namespace;entries=new Map;constructor($){this.namespace=$}record($,Z){if($.accountKey.namespace!==this.namespace)return;if(![$.expiry,$.observedAt,$.evidenceAt,Z].every(Number.isFinite))return;if(this.prune(Z),$.expiry<=Z)return;let J=y($.accountKey),X=this.entries.get(J);if(X?.expiry===$.expiry){if(r7[X.branch]<=r7[$.branch])return}if(this.entries.set(J,$),this.entries.size<=256)return;let z,G=1/0;for(let[Q,Y]of this.entries)if(Y.observedAt<G)z=Q,G=Y.observedAt;if(z!==void 0)this.entries.delete(z)}read($,Z,J,X){this.prune(X);let z=this.entries.get(y($));return z?.expiry===Z&&z.evidenceAt===J?z:void 0}retire($){this.entries.delete(y($))}clear(){this.entries.clear()}reconcile($,Z){this.prune(Z);for(let[J,X]of this.entries)if(!$.marks.some((z)=>R(z.key.account,X.accountKey)&&z.key.window==="account"&&z.key.scope.kind==="pool"&&z.entries.some((G)=>G.cause==="rate-limit"&&G.until===X.expiry&&G.evidenceAt===X.evidenceAt)))this.entries.delete(J)}prune($){for(let[Z,J]of this.entries)if(J.expiry<=$)this.entries.delete(Z)}}import{randomUUID as t7}from"node:crypto";import{randomUUID as YQ}from"node:crypto";function Y$($,Z){return(Z?.rows??[]).map((J)=>({account:{namespace:$,accountId:J.routeId,incarnation:String(J.addedAt)},credentialEpoch:String(J.addedAt),...J.accountIdentity===void 0?{}:{identity:J.accountIdentity}}))}async function W$($){let{namespace:Z,path:J}=$,X=YQ(),z=new j2,G=new P1(Z,$.logger),Q=new T1($.logger),Y=$.now??Date.now,B=async(H)=>{G.assertWritable();let V=await y4(J),{snapshot:U,replacement:j}=G.decode(V?.limits);if(!j&&z.lost(U,H))return Q.schedule(()=>W.commit([],H)),{snapshot:z.recover(U,H,Z,Y()),bindings:Y$(Z,V),authoritative:!1,degradedAgreement:!0};if(U)z.remember(U);return{snapshot:U??T0(Z,X),bindings:Y$(Z,V),authoritative:!0}},W={namespace:Z,read:B,subscribe:Q.subscribe,commit:async(H,V)=>{G.assertWritable();let U,j,q=()=>{if(G.didCommit(U)&&j)z=new j2,z.remember(j,V)},F=await o7(J,(K)=>{let N=Y$(Z,K),D=G.decode(K?.limits),T=D.snapshot;U=D.replacement;let M=!U&&z.lost(T,V),P=q2(M?z.recover(T,V,Z,Y()):T??T0(Z,X),H,{now:Y(),bindings:N,authorizeEpoch:(O,C)=>O.credentialEpoch===C.credentialEpoch});return j=P.snapshot,{next:{...K??{version:1,complete:!0,rows:[],declined:[]},limits:P.snapshot},result:{...P,bindings:N,authoritative:!0,degradedAgreement:M}}},{beforePublish:async()=>G.assertWritable(),onPublished:q});return q(),z.remember(F.snapshot,V),F}};return await B(),W}var WQ=256,VQ=256,HQ=1024;function V$($){return JSON.stringify([y($.account),$.until,$.evidenceAt])}class H${log;generation;issued=0;adopted=0;remembered=new Map;staged=new Map;consumed=new Map;exhausted=!1;constructor($=()=>{}){this.log=$}capture($,Z){return{token:++this.issued,view:$,at:Z}}adopt($,Z){let{view:J,token:X,at:z}=$,G=J.snapshot;if(X<=this.adopted||!J.authoritative||J.degradedAgreement||G.namespace!==Z.namespace||G.generation!==Z.generation||G.revision!==Z.revision)return!1;if(this.adopted=X,this.generation!==G.generation)this.generation=G.generation,this.remembered.clear(),this.staged.clear(),this.consumed.clear();let Q=new Set(J.bindings.map((B)=>y(B.account))),Y=new Map;for(let B of G.marks){if(B.key.window!=="account"||B.key.scope.kind!=="pool")continue;if(!Q.has(y(B.key.account)))continue;for(let W of B.entries){if(W.cause!=="rate-limit")continue;let H={account:B.key.account,until:W.until,evidenceAt:W.evidenceAt,committedRevision:W.committedRevision};Y.set(V$(H),H)}}for(let B of[this.remembered,this.staged])for(let[W,H]of B){if(!Q.has(y(H.account))){B.delete(W);continue}if(Y.has(W))continue;let V=G.tombstones.some((U)=>y(U.key.account)===y(H.account)&&U.key.window==="account"&&U.key.scope.kind==="pool"&&U.revision>=H.committedRevision&&(U.cause===void 0||U.cause==="rate-limit"));if(B===this.staged&&!V)continue;if(B.delete(W),!V&&B===this.remembered&&H.until<=z)this.stage(H)}for(let[B,W]of Y){if(this.consumed.has(B))continue;if(W.until<=z)this.remembered.delete(B),this.stage(W);else if(this.remembered.has(B)||this.remembered.size<WQ)this.remembered.set(B,W)}return!0}stage($){let Z=V$($);if(this.consumed.has(Z)||this.exhausted)return;let{NEGATIVE_INFINITY:J,NEGATIVE_INFINITY:X}=Number;for(let z of this.consumed.values()){if(y(z.account)!==y($.account))continue;J=Math.max(J,z.until),X=Math.max(X,z.evidenceAt)}if($.until<=J&&$.evidenceAt<=X)return;if(this.staged.has(Z)||this.staged.size<VQ)this.staged.set(Z,$)}candidate($,Z){if(this.exhausted||this.generation===void 0)return;let J=y($.account),X;for(let z of this.staged.values()){if(y(z.account)!==J||z.until>Z)continue;if(!X||z.until>X.until||z.until===X.until&&z.evidenceAt>X.evidenceAt)X=z}return X&&{...X,generation:this.generation}}consume($){let Z=V$($);if(this.exhausted||$.generation!==this.generation||!this.staged.has(Z)||this.consumed.has(Z))return!1;let J=[...this.staged].filter(([,X])=>y(X.account)===y($.account));if(this.consumed.size+J.length>HQ)return this.exhausted=!0,this.staged.clear(),this.log("OpenAI limits recovery evidence is full; skipping further recovery clears."),!1;for(let[X,z]of J)this.consumed.set(X,z),this.staged.delete(X);return!0}}var j$=5000,U$=1000,q$=60000,UQ={now:()=>Date.now(),setTimeout:($,Z)=>setTimeout($,Z),clearTimeout:($)=>clearTimeout($)};class e7{options;clock;dropped;owners=0;registry;recovery;provenance;provenanceGeneration;adapter;acquiring;releasing;deadline;fallback=!1;fallbackResolve;fallbackSignal=new Promise(($)=>{this.fallbackResolve=$});failureAt;retryAt=0;retryDelay=U$;failureTimer;latestRead;adoptedBindings=[];controls=new Map;projection;producerId=t7();constructor($,Z,J){this.options=$;this.clock=Z;this.dropped=J;this.recovery=new H$($.log),this.provenance=new B$($.namespace)}stopTracking(){if(this.fallback)return;this.fallback=!0,this.clock.clearTimeout(this.failureTimer),this.fallbackResolve(),this.options.log("OpenAI limits tracking is unavailable; serving without timed marks for this process.");let $=this.registry;if(this.registry=void 0,this.adapter=void 0,this.latestRead=void 0,this.provenance.clear(),$)this.releasing=$.dispose().catch(()=>{})}wait($){return new Promise((Z)=>this.clock.setTimeout(Z,Math.max(0,$)))}async bounded($,Z){let J;try{return await Promise.race([$,this.fallbackSignal.then(()=>{return}),new Promise((X)=>{J=this.clock.setTimeout(()=>X(void 0),Math.max(0,Z-this.clock.now()))})])}finally{this.clock.clearTimeout(J)}}recordFailure(){if(!this.registry||this.fallback)return;let $=this.clock.now();if(this.failureAt===void 0)this.failureAt=$,this.failureTimer=this.clock.setTimeout(()=>this.stopTracking(),q$);if(this.retryAt=$+this.retryDelay,this.retryDelay=Math.min(q$,this.retryDelay*2),$-this.failureAt>=q$)this.stopTracking()}recordSuccess(){this.failureAt=void 0,this.retryAt=0,this.retryDelay=U$,this.clock.clearTimeout(this.failureTimer),this.failureTimer=void 0}async makeAdapter(){let $=await this.options.adapter();return{namespace:$.namespace,read:async(Z)=>{if(this.adoptRead(),this.registry&&this.clock.now()<this.retryAt)throw this.registry.lastFailure??Error("limits-reload-backoff");try{let J=await $.read(Z);this.latestRead=this.recovery.capture(J,this.clock.now());let X=!Z||J.snapshot.generation!==Z.generation||J.snapshot.revision>=Z.revision;if(J.authoritative&&!J.degradedAgreement&&X)this.recordSuccess();else if(!J.authoritative||J.degradedAgreement)this.recordFailure();return J}catch(J){throw this.recordFailure(),J}},commit:async(Z,J)=>{this.adoptRead();let X=await $.commit(Z,J);return this.latestRead=this.recovery.capture(X,this.clock.now()),X},subscribe:$.subscribe?.bind($)}}async ready($){if(!$||this.fallback||this.registry)return;if(!this.acquiring)this.acquiring=this.acquire().finally(()=>{this.acquiring=void 0});await this.acquiring}async acquire(){await this.releasing,this.deadline??=this.clock.now()+j$;while(!this.fallback&&!this.registry){if(this.clock.now()>=this.deadline){this.stopTracking();return}let $=(async()=>{return this.adapter??=await this.makeAdapter(),L9({adapter:this.adapter,clock:this.clock,isAccessRestrictive:this.options.isAccessRestrictive,onAbandon:()=>this.stopTracking(),onRejected:(Z)=>{this.controls.delete(JSON.stringify([Z.producerId,Z.operationId]))}})})();try{let Z=await this.bounded($,this.deadline);if(!Z||this.fallback){this.stopTracking(),$.then((J)=>J.dispose()).catch(()=>{});return}if(this.registry=Z,Z.abandoned){this.stopTracking();return}this.adoptRead()}catch(Z){if(Z instanceof N1||Z instanceof D1){this.stopTracking();return}if(Z instanceof L0&&Z.code==="pool-not-ready"){this.deadline=void 0,this.adapter=void 0;return}await this.wait(Math.min(U$,Math.max(0,this.deadline-this.clock.now())))}}}adoptRead(){let $=this.current();if($&&this.latestRead&&this.recovery.adopt(this.latestRead,$.snapshot)){if(this.provenanceGeneration!==void 0&&this.provenanceGeneration!==$.snapshot.generation)this.provenance.clear();this.provenanceGeneration=$.snapshot.generation,this.provenance.reconcile($.snapshot,this.clock.now()),this.projection=o9(this.latestRead.view.bindings),this.adoptedBindings=this.latestRead.view.bindings;for(let Z of $.snapshot.operationIds)this.controls.delete(JSON.stringify([Z.producerId,Z.operationId]))}}current(){if(this.registry?.abandoned)this.stopTracking();return this.registry}snapshot(){return this.adoptRead(),this.current()?.snapshot}enqueue($,Z){let J=this.current();if(J){if($.type!=="mark")this.controls.set(JSON.stringify([$.producerId,$.operationId]),$);if(J.enqueue($),$.type!=="mark")this.provenance.retire($.binding.account);else if(Z&&Z.expiry===$.until&&Z.evidenceAt===$.evidenceAt&&y(Z.accountKey)===y($.binding.account))this.provenance.record(Z,this.clock.now());else this.provenance.retire($.binding.account)}else if($.type==="mark")this.dropped()}dropSignal(){this.dropped()}observe($){this.adoptRead();let Z=this.current();if(!Z||!$)return;return{...Z.observe($),registry:Z,evidence:this.recovery.candidate($,this.clock.now())}}afterProbe($,Z,J){if(!$?.evidence||!Z||J||this.current()!==$.registry)return;if(this.adoptRead(),$.registry.snapshot.marks.some((z)=>y(z.key.account)===y($.binding.account)&&z.entries.some((G)=>G.until>this.clock.now()))||!this.recovery.consume($.evidence))return;this.enqueue({type:"clear",producerId:this.producerId,operationId:t7(),binding:$.binding,baseRevision:$.baseRevision,keys:[{scope:{kind:"pool"},window:"account"}],cause:"rate-limit",evidenceAt:$.evidence.evidenceAt})}dispatchAtBound($){this.adoptRead();let Z=this.current()?.snapshot;if(!Z)return{status:"ready"};let J=this.adoptedBindings.find((G)=>y(G.account)===y($.account)),X=[...this.controls.values()].some((G)=>y(G.binding.account)===y($.account)),z=Z.access.some((G)=>y(G.account)===y($.account)&&this.options.isAccessRestrictive(G.state));return{status:!J||!u0(J,$)||X||z?"blocked":"ready",snapshot:Z}}async release(){if(--this.owners!==0)return;if(await this.acquiring,this.owners!==0)return;let $=this.current();if(this.registry=void 0,this.clock.clearTimeout(this.failureTimer),$)this.releasing=$.dispose(),await this.releasing;this.adapter=void 0,this.projection=void 0,this.deadline=void 0,this.provenance.clear()}}class $8{lease;projectionDeadline;constructor($){this.lease=$}snapshot(){return this.lease.snapshot()}async reloadForBindings($){for(;;){this.lease.adoptRead();let Z=this.lease.current();if(!Z)return;if(o9($())===this.lease.projection)return;if(this.projectionDeadline??=this.lease.clock.now()+j$,this.lease.clock.now()>=this.projectionDeadline)return;if(await this.lease.bounded(Z.reload(),this.projectionDeadline),this.lease.adoptRead(),this.lease.clock.now()>=this.projectionDeadline)return;if(Z.degradedAgreement)return}}async beforeDispatch($,Z,J=$?.account.accountId){await this.reloadForBindings(Z);let X=()=>{if(!J)return"ready";let B=Z().find((W)=>W.account.accountId===J);if(!B)return $?"absent":"ready";if($&&(y(B.account)!==y($.account)||!u0(B,$)))return"changed";return"ready"},z=X();if(z!=="ready")return{status:z};let G=this.lease.current();if(!G||!$)return{status:"ready"};if(this.projectionDeadline!==void 0&&this.lease.clock.now()>=this.projectionDeadline)return this.lease.dispatchAtBound($);let Q=this.projectionDeadline??this.lease.clock.now()+j$,Y=await this.lease.bounded(G.beforeDispatch($),Q);if(Y?.blocked&&this.lease.current())await this.lease.bounded(G.reload(),Q),Y=await this.lease.bounded(G.beforeDispatch($),Q);if(z=X(),z!=="ready")return{status:z};if(!this.lease.current())return{status:"ready"};return this.lease.adoptRead(),{status:!Y||Y.blocked?"blocked":"ready",snapshot:Y?.snapshot}}}class Z8{lease;disposed=!1;constructor($){this.lease=$;$.owners++}get namespace(){return this.lease.options.namespace}get registry(){return this.lease.current()}get provenance(){return this.lease.adoptRead(),this.lease.provenance}async forRequest($){if(this.disposed)throw Error("limits-owner-disposed");return await this.lease.ready($),new $8(this.lease)}snapshot(){return this.lease.snapshot()}observe($){return this.lease.observe($)}enqueue($,Z){this.lease.enqueue($,Z)}dropSignal(){this.lease.dropSignal()}afterProbe($,Z,J=!1){this.lease.afterProbe($,Z,J)}async reload(){let $=this.lease.current();if($)await $.reload();this.lease.adoptRead()}async flush(){await this.lease.current()?.flush()}async dispose(){if(this.disposed)return;this.disposed=!0,await this.lease.release()}}function qQ($=UQ,Z={}){let J=new Map,X=Z.droppedSignalLog??{logged:!1};return{acquire(z){let G=J.get(z.namespace);if(!G)G=new e7(z,$,()=>{if(X.logged)return;X.logged=!0,z.log("OpenAI limit signal dropped because timed-mark tracking is unavailable.")}),J.set(z.namespace,G);return new Z8(G)}}}var J8=Symbol.for("@cortexkit/openai-auth/limits-leases/v1"),X8=globalThis,z8=X8[J8]??qQ();X8[J8]=z8;function jQ($){let{source:Z}=$,J=Z.kind==="pool"?j7(Z.configPath,Z.statePath):F7(Z.rosterPath),X=$.log??(()=>{});return z8.acquire({namespace:J,log:X,isAccessRestrictive:$.isAccessRestrictive??(()=>!1),adapter:()=>Z.kind==="pool"?T9({namespace:J,store:Z.store,logger:{warn:X}}):W$({namespace:J,path:Z.rosterPath,logger:{warn:X}})})}function QN($,Z,J){let X=$.get(Z.sessionId),z=new Set(Z.validPinnedAccountIds);if(X&&!Z.excludeAccountIds.includes(X.accountId)&&G8(X,z,Z.wireAccountIdByAccount[X.accountId])){if(Z.persist){let B=Z.quotaCheckedAtByAccount[X.accountId];J(Z.sessionId,{accountId:X.accountId,inputBytes:Z.requestBytes,...X.wireIdentity!==void 0?{wireIdentity:X.wireIdentity}:{},...B!==void 0?{quotaCheckedAt:B}:{}})}return{accountId:X.accountId}}let G=new Map(Object.entries(Z.quotaCheckedAtByAccount)),Q=Q8($,G,Z.sessionId),Y=Z.select(Q);if(!Y)return;if(Z.persist){let B=Z.wireAccountIdByAccount[Y.accountId];J(Z.sessionId,{accountId:Y.accountId,inputBytes:Z.requestBytes,...B!==void 0?{wireIdentity:B}:{},...Y.quotaCheckedAt!==void 0?{quotaCheckedAt:Y.quotaCheckedAt}:{}})}return{accountId:Y.accountId}}import{statSync as FQ}from"node:fs";var V8=30000,KQ=8,NQ=1800000;function H8($){return JSON.stringify([$.id,$.credentialEpoch??null])}function HN($){try{let Z=FQ($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function UN($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}function DQ($,Z){try{return B8($,Z)}catch{return $}}function qN($,Z,J){let X=H8(Z);$.set(X,[...$.get(X)??[],{credentialEpoch:Z.credentialEpoch,identity:Z.identity,observation:J}].slice(-KQ))}function jN($,Z,J){let X=$;for(let z of Z.get(H8($))??[]){if(!(J-z.observation.checkedAt<=NQ)||z.credentialEpoch!==$.credentialEpoch||z.identity!==$.identity)continue;X={...X,quota:DQ(X.quota,z.observation)}}return X}function FN($,Z,J,X){let z=g1($);if(typeof Z?.status==="number"||Y8(Z)){let Q=W8({error:Z,now:J,refreshToken:$,...X?{previous:{message:"",checkedAt:J,nextRetryAt:X.nextRetryAt,retryCount:X.retryCount,tokenHash:X.tokenHash}}:{}});return{nextRetryAt:Q.nextRetryAt,tokenHash:z,retryCount:Q.retryCount}}return{nextRetryAt:J+V8,tokenHash:z,retryCount:X?.tokenHash===z?X.retryCount:0}}function KN($,Z,J,X){let z=new Map;for(let G of $){if(X(G,J))continue;let Q=Z.get(G.id);z.set(G.id,Q&&Q.nextRetryAt>J?Q.nextRetryAt:J+V8)}return z}import{createHash as PQ}from"node:crypto";var MQ={quota:"Every OpenAI account has used up its quota.",killswitch:"Every OpenAI account is below its killswitch quota floor (see the Limits section of `/openai`).","timed-mark":"Every OpenAI account is paused by OpenAI for now."},CQ={quota:"OpenAI quota exhausted — retrying on another account.",killswitch:"Killswitch: all OpenAI accounts are below their configured quota threshold.","timed-mark":"OpenAI rate limit reached — retrying on another account.",hold:"OpenAI usage limit reached on this account. Waiting for it keeps the conversation's prompt cache."};function U8($){return({retryIn:Z,reset:J})=>`${$}${Z?` Retry in ${Z}.`:""}${J?` Resets in ${J}.`:""}`}var TQ=U9({refusals:Object.fromEntries(Object.entries(MQ).map(([$,Z])=>[$,U8(Z)])),retryable:Object.fromEntries(Object.entries(CQ).map(([$,Z])=>[$,U8(Z)])),formatReset:h2});function TN($,Z,J){if(!$||!Z||G2())return;return{jitterMs:PQ("sha256").update(J??"").digest().readUInt32BE(0)%21*1000}}function LN($){let Z=[],J=!1,X=!1,z=$.familyOf??(()=>{return}),G=$.accounts.flatMap((W)=>{if(W.usable===!1)return[];let H=R(W.account,W.readingAccount??W.account)&&!(W.identity&&W.readingIdentity&&W.identity!==W.readingIdentity),V=[];if(H){for(let U of["primary","secondary"]){let j=W.reading?.[U];if(!j)continue;let q=X2(j.checkedAt,$.now),F=W.floors?.[U],K=F!==void 0&&j.remainingPercent<F?"killswitch-floor":q&&j.usedPercent>=100?"exhausted":void 0;if(!K)continue;if(K==="killswitch-floor")X=!0;else J=!0;let N=q?i4(j.resetsAt):void 0;V.push({window:U,scope:{kind:"pool"},blockedBy:K,...N===void 0?{}:{reset:{at:N,checkedAt:j.checkedAt}}})}for(let U of W.confirmedBlockers??[]){if(!U.confirmed||!X2(U.observedAt,$.now))continue;J=!0,V.push({window:U.window,scope:{kind:"pool"},blockedBy:"exhausted",...U.resetAt===void 0?{}:{reset:{at:U.resetAt,observedAt:U.observedAt}}})}}for(let U of W.marks??[]){if(!Number.isFinite(U.until)||U.until<=$.now)continue;let j=$.provenance?.read(W.account,U.until,U.evidenceAt,$.now),q=j&&j.branch!=="unproven"&&X2(j.observedAt,$.now);if(!q)Z.push(U.until);V.push({window:"account",scope:{kind:"pool"},blockedBy:"exhausted",...q?{reset:{at:U.until,observedAt:j.observedAt}}:{}})}return[{account:W.account,readingAccount:W.account,windows:V}]}),Q=$.activity&&$.currentAccountKey&&R($.activity.accountKey,$.currentAccountKey)?$.activity:void 0,Y={candidates:G,effectiveModel:$.effectiveModel,familyOf:z,maxAgeMs:t9,maxSameAccountWait:m0($.maxSameAccountWait),...$.waitForReset&&{waitForReset:$.waitForReset},activity:Q,accountKey:Q?.accountKey},B=M4(Y,$.now);if(B&&Z.some((W)=>W<B.resetAt))Y={...Y,candidates:[]};return{source:"pool",reason:"quota",messageKey:X?"killswitch":J?"quota":"timed-mark",scan:Y}}function ON($,Z){let J=$.phase==="pre-send"?{...$,attempted:void 0,selection:void 0,hold:void 0}:$,X=D7({...J,terminal:Z},{mode:"sticky"});if(!X)throw Error("Missing OpenAI terminal decision");return X}function _N($){let Z=$.decision,J=$.host!=="pi"&&Z.action==="hold"&&Z.waitKind!=="terminal",X=$.host!=="pi"&&!$.requestThrow&&(J||m0($.maxSameAccountWait)!==0&&Z.retryable),z=J?"hold":$.cause??(Z.action==="refuse"?Z.messageKey:"quota");return N9({family:$.host==="pi"?"pi-final":$.requestThrow?"json-412":J?"openai-429":Z.action==="refuse"?Z.family==="pi-final"?"pi-final":X?"openai-429":"json-412":X?"openai-429":"pi-final",messageKey:z,messages:TQ,now:$.now,...X&&"retryAfterMs"in Z?{retryAfterMs:Z.retryAfterMs}:{},..."resetAt"in Z&&Z.resetAt!==void 0?{resetAt:Z.resetAt}:{}})}import{randomUUID as LQ}from"node:crypto";function OQ($){if(!E($))return;let Z=E($.input_tokens_details)?$.input_tokens_details:void 0,J=Z?.cached_tokens,X=Z?.cache_write_tokens,z=E($.output_tokens_details)?$.output_tokens_details.reasoning_tokens:void 0;return{...typeof $.input_tokens==="number"?{input:Math.max(0,$.input_tokens-(typeof J==="number"?J:0)-(typeof X==="number"&&X>0?X:0))}:{},...typeof J==="number"?{cacheRead:J}:{},...typeof X==="number"&&X>0?{cacheWrite:X}:{},...typeof $.output_tokens==="number"?{output:$.output_tokens}:{},...typeof z==="number"?{reasoning:z}:{},reasoningIncludedInOutput:!0}}class _Q{sessionId;receipt;requestKind;model;attempt;warming;freeQuota;attemptId=LQ();reported=!1;completed=!1;failed=!1;responseId;usage;constructor($,Z,J,X,z,G,Q=!1){this.sessionId=$;this.receipt=Z;this.requestKind=J;this.model=X;this.attempt=z;this.warming=G;this.freeQuota=Q}event($){if(!E($))return;if($.type==="error"||$.type==="response.failed")this.failed=!0;if($.type!=="response.completed"&&$.type!=="response.incomplete"&&$.type!=="response.failed")return;if(this.completed=$.type!=="response.failed",E($.response)){if(typeof $.response.id==="string")this.responseId=$.response.id;this.usage=OQ($.response.usage)}}piCompleted($,Z){if(this.completed=!0,this.piResponseId($),!E(Z))return;let J={reasoningIncludedInOutput:!0};for(let X of["input","output","cacheRead","reasoning"])if(typeof Z[X]==="number")J[X]=Z[X];if(typeof Z.cacheWrite==="number"&&Z.cacheWrite>0)J.cacheWrite=Z.cacheWrite;this.usage=J}piResponseId($){this.responseId=$}end($,Z,J,X=!1){if(this.reported)return;this.reported=!0;let z;try{z=this.warming?.(this.sessionId)}catch{}z2({sessionId:this.sessionId,kind:"billing",attemptId:this.attemptId,requestKind:this.requestKind,credentialId:this.receipt.credentialId,...this.receipt.accountIdentity?{accountId:this.receipt.accountIdentity}:{},provider:"openai",model:this.model,...this.freeQuota?{chargeBasis:"subscription_included"}:{},attempt:this.attempt,cache:{implicit:!0,warming:z?.on?{on:!0}:{on:!1,...x1(z?.stopReason)?{stopReason:z.stopReason}:{}}},outcome:this.failed||J!==void 0&&(J<200||J>=300)?"failed":this.completed&&(Z||X)?"completed":$?"cut":"failed",...J!==void 0?{status:J}:{},...this.responseId?{providerResponseId:this.responseId}:{},...this.usage?{usage:this.usage}:{}})}}import{readdir as AQ,readFile as EQ,rm as RQ,stat as IQ}from"node:fs/promises";import{homedir as bQ,uptime as kQ}from"node:os";import{join as a2}from"node:path";var K$=Symbol.for("@cortexkit/openai-auth/runtime-layout-runs"),N$=globalThis,F$=globalThis,SQ=N$[K$];N$[K$]??={};var n2=N$[K$];n2.legacyGeneration??=SQ===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));n2.runs??=new Map;n2.logged??=new Set;var c0=Object.assign(n2,{runs:n2.runs,logged:n2.logged});function X0(){return c0.legacyGeneration===!0}function Z6(){return process.env.XDG_STATE_HOME||a2(bQ(),".local","state")}function xQ($=Z6()){return a2($,"cortexkit","openai-auth","processes")}function yQ($=Z6()){return a2($,"cortexkit","openai-auth","rpc")}function gQ($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}function q8($){let Z=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec($.trim());if(!Z)return;return{core:[Number(Z[1]),Number(Z[2]),Number(Z[3])],pre:Z[4]?Z[4].split("."):[]}}function j8($,Z){let J=q8($),X=q8(Z);if(!J||!X)return;for(let z=0;z<3;z++){let G=J.core[z]-X.core[z];if(G!==0)return Math.sign(G)}if(J.pre.length===0||X.pre.length===0)return Math.sign(X.pre.length-J.pre.length);for(let z=0;z<Math.max(J.pre.length,X.pre.length);z++){let G=J.pre[z],Q=X.pre[z];if(G===void 0)return-1;if(Q===void 0)return 1;let Y=/^\d+$/.test(G),B=/^\d+$/.test(Q);if(Y&&B){let W=Number(G)-Number(Q);if(W!==0)return Math.sign(W)}else if(Y!==B)return Y?-1:1;else if(G!==Q)return G<Q?-1:1}return 0}async function D$($){try{return{ok:!0,names:await AQ($)}}catch(Z){let J=Z.code;if(J==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:J,error:`${$}: ${String(Z)}`}}}async function F8($,Z){let J;try{J=await EQ($,"utf8")}catch(X){if(X.code==="ENOENT")return{kind:"gone"};return{kind:"unreadable"}}try{let X=JSON.parse(J);if(X!==null&&typeof X==="object"&&X.pid===Z){let z=X.layouts;return{kind:"ok",version:typeof X.version==="string"?X.version:"unknown",startedAt:X.startedAt,...z!==null&&typeof z==="object"&&!Array.isArray(z)?{layouts:z}:{}}}}catch{}return{kind:"unreadable"}}async function N8($){let Z=$.isAlive??gQ,J=$.selfPid??process.pid,z=($.now??Date.now)()-($.uptime??kQ)()*1000-300000,G=(F)=>typeof F==="number"&&Number.isFinite(F)&&F<z,Q=new Map,Y=(F)=>{let K=F.pid==="unknown"?`dir:${F.detail}`:F.pid;if(!Q.has(K))Q.set(K,F)};if($.layoutMove&&J===process.pid&&X0())Y({pid:J,version:"unknown",detail:"an older plugin generation ran in this process"});let B=(F)=>{try{return Z(F)}catch{return!0}},W=(F,K)=>{let N=K.exec(F),D=N?Number(N[1]):Number.NaN;return Number.isSafeInteger(D)&&D>=1?D:void 0},H=xQ($.stateHome),V=await D$(H);if(!V.ok)Y({pid:"unknown",version:"unknown",detail:V.error});for(let F of V.ok?V.names:[]){let K=W(F,/^(\d+)\.json$/);if(K===void 0||K===J)continue;let N=a2(H,F),D=await F8(N,K);if(D.kind==="gone")continue;if(D.kind==="ok"&&G(D.startedAt)){await RQ(N,{force:!0}).catch(()=>{});continue}if(!B(K))continue;if(D.kind==="unreadable"){Y({pid:K,version:"unknown",detail:N});continue}let T=j8(D.version,$.currentVersion);if(T===void 0||T<0){Y({pid:K,version:D.version,detail:N});continue}if($.layoutMove===!0&&(D.layouts===void 0||Object.values(D.layouts).includes("legacy")))Y({pid:K,version:D.version,detail:N})}let U=$.rpcDir??yQ($.stateHome),j=await D$(U);if(!j.ok)Y({pid:"unknown",version:"unknown",detail:j.error});for(let F of j.ok?j.names:[]){if(!K8(F))continue;let K=a2(U,F),N=await D$(K);if(!N.ok){if(N.code==="ENOTDIR")continue;Y({pid:"unknown",version:"unknown",detail:N.error});continue}for(let D of N.names){let T=W(D,/^port-(\d+)\.json$/);if(T===void 0||T===J||!B(T))continue;let M=a2(K,D),P=await F8(M,T);if(P.kind==="gone")continue;if(P.kind==="ok"){let L=P.startedAt===void 0?await IQ(M).then((A)=>A.mtimeMs).catch(()=>{return}):P.startedAt;if(G(L))continue}let O=P.kind==="ok"?P.version:"unknown",C=j8(O,$.currentVersion);if(C===void 0||C<0)Y({pid:T,version:O,detail:M})}}let q=(F)=>F.pid==="unknown"?Number.POSITIVE_INFINITY:F.pid;return Q.size===0?{open:!0}:{open:!1,blockers:[...Q.values()].sort((F,K)=>q(F)-q(K))}}import{createHash as fQ}from"node:crypto";import{existsSync as vQ,realpathSync as P$}from"node:fs";import{homedir as C8}from"node:os";import{basename as hQ,dirname as mQ,join as j0,resolve as T$}from"node:path";var L$="openai-auth-sessions.json",O$="openai-auth-sessions-opencode2.json",J6="layout.json",_$="config-dir.json";function X6(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return wQ()}function wQ(){return j0(process.env.XDG_CONFIG_HOME||j0(C8(),".config"),"opencode")}function z6(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||j0(X6(),M$)}function i2($,Z){let J=T$($);return Z==="win32"||Z==="darwin"?J.toLowerCase():J}function D8($){try{return P$.native($)}catch{try{return j0(P$.native(mQ($)),hQ($))}catch{return}}}function G6($,Z,J=process.platform){if(i2($,J)===i2(Z,J))return!0;let X=D8($),z=D8(Z);return X!==void 0&&z!==void 0&&i2(X,J)===i2(z,J)}function P8($){try{return P$.native($)}catch{return T$($)}}var M8=new Map;function Q6($=X6()){let Z=Z6(),J=j0(C8(),".config","opencode"),X=`${$}\x00${J}\x00${Z}`,z=M8.get(X);if(z&&Y6(z))return z;let G=P8($);if(z&&z.key===G)return z;let Q=G===P8(J),Y=j0(Z,"cortexkit","openai-auth"),B={key:G,configDir:$,stateHomeDir:Q?j0(Y,"opencode"):j0(Y,`opencode-${fQ("sha256").update(G).digest("hex").slice(0,16)}`),isDefaultConfigDir:Q};return M8.set(X,B),B}var T8=Symbol.for("@cortexkit/openai-auth/runtime-layouts"),L8=globalThis,S$=L8[T8]??new Map;L8[T8]=S$;function O8($){return`${$.stateHomeDir}\x00${$.key}`}function B6($,Z){S$.set(O8($),X0()?"legacy":Z)}function Y6($){return S$.get(O8($))}function _8($=X6()){if(X0())return $;let Z=Q6($);return(Y6(Z)??(vQ(j0(Z.stateHomeDir,J6))?"state-home":"legacy"))==="state-home"?Z.stateHomeDir:$}function bD($){return j0(_8(),$==="opencode1"?L$:O$)}function A$($){let Z=j0(X6(),M$);return $===Z||i2($,process.platform)===i2(Z,process.platform)}function S8($=z6()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return A$($)?void 0:C$($)}function A8($=z6()){return A$($)?void 0:$}function uQ($=z6()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z){if(G6($,Z))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${T$($)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return Z}if(!A$($))return C$($);return j0(_8(),f1)}function kD($=z6()){return{configPath:$,statePath:uQ($)}}import{createHash as iQ}from"node:crypto";import{existsSync as rQ,readFileSync as oQ}from"node:fs";import{readFile as tQ}from"node:fs/promises";import{resolve as eQ}from"node:path";import{createHash as pQ}from"node:crypto";import{readFile as lQ}from"node:fs/promises";import{homedir as dQ}from"node:os";import{join as E8,resolve as cQ}from"node:path";var sQ="openai",R8=250,h1="main-refresh";function R$($){if(typeof $.access!=="string"||typeof $.refresh!=="string")return;let Z=Buffer.from($.access),J=Buffer.from($.refresh),X=(z)=>{let G=Buffer.alloc(4);return G.writeUInt32BE(z.length),G};return pQ("sha256").update(X(Z)).update(Z).update(X(J)).update(J).digest("hex")}function g8($){if(!$||typeof $!=="object")return;let Z=$;if(Z.type!=="oauth")return;return{type:"oauth",...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.refresh==="string"?{refresh:Z.refresh}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.accountId==="string"?{accountId:Z.accountId}:{}}}function f8($){let Z=g8($);if(typeof Z?.access!=="string"||typeof Z.refresh!=="string")return;return{access:Z.access,refresh:Z.refresh,...typeof Z.expires==="number"?{expires:Z.expires}:{}}}function I8($){if(L2($)&&$.type==="api"&&typeof $.key==="string")return{kind:"api"};let Z=g8($);if(!Z)return{kind:"indeterminate"};return b1(Z)?{kind:"tombstone",oauth:Z}:{kind:"real",oauth:Z}}async function b8($){return $.auth.get({path:{id:sQ}})}async function k8($){return Object.keys(await $.auth.all()).length>0}async function v8($){let Z=await b8($.client);if(Z!==void 0)return I8(Z);let J=await k8($.client),X=$.now();if(await $.sleep(R8),$.now()-X<R8)return{kind:"indeterminate"};let z=await b8($.client);if(z!==void 0)return I8(z);let G=await k8($.client);return J&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function W6($=process.env,Z=dQ()){let J=$.XDG_DATA_HOME||E8(Z,".local","share");return E8(J,"opencode","auth.json")}function L2($){return!!$&&typeof $==="object"&&!Array.isArray($)}var x8=($)=>$===void 0||typeof $==="string";function nQ($){if(!L2($))return!1;switch($.type){case"oauth":return typeof $.refresh==="string"&&typeof $.access==="string"&&typeof $.expires==="number"&&Number.isSafeInteger($.expires)&&$.expires>=0&&x8($.accountId)&&x8($.enterpriseUrl);case"api":return typeof $.key==="string"&&($.metadata===void 0||L2($.metadata)&&Object.values($.metadata).every((Z)=>typeof Z==="string"));case"wellknown":return typeof $.key==="string"&&typeof $.token==="string";default:return!1}}async function E$($,Z=process.env){let J=Z.OPENCODE_AUTH_CONTENT;if(J)try{let z=JSON.parse(J);return L2(z)?z:{}}catch{}let X;try{X=JSON.parse(await lQ($,"utf8"))}catch{return{}}if(!L2(X))return{};return Object.fromEntries(Object.entries(X).filter(([,z])=>nQ(z)))}function y8($){if(!$.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse($.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class V6 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function aQ($){let Z=$.env??process.env,J=$.path??W6(Z),X=new Map;return{path:cQ(J),migrationDisabledReason:()=>y8(Z)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(z){let G=(await E$(J,Z))[z.path.id];return X.set(z.path.id,JSON.stringify(G)),G},async all(){return E$(J,Z)},async set(z){if(y8(Z))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let G=(await E$(J,Z))[z.path.id];if(v1(z.body)&&(!X.has(z.path.id)||X.get(z.path.id)!==JSON.stringify(G)))throw new V6;let Q=await $.set(z);if(L2(Q)&&"error"in Q&&Q.error!==void 0)throw Error(`OpenCode refused the write of its ${z.path.id} login: ${JSON.stringify(Q.error)}`);return Q}}}function wD($,Z={}){let J=L2($)?$.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:aQ({...Z,set:(z)=>X.call(J,z)})}}var r2="openai",$B="common-auth-placeholder:v1:openai",m1=Object.freeze({type:"oauth",access:"",refresh:$B,expires:0});function v1($){if(!F0($))return!1;return $.type===m1.type&&$.access===m1.access&&$.refresh===m1.refresh&&$.expires===m1.expires}var H6="openaiAuthPool",ZB=120000,n8="pool-migration",JB="slot-transfer-origin-unknown",XB="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.",K6=Object.freeze({mainRefreshTtlMs:ZB,fallbackTtlMs:c8,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function U6($,Z,J){return $.kind==="placeholder"&&!Z&&!J.pending}class O2 extends Error{constructor($){super(`timed out waiting for the legacy ${$} lock`);this.name="LegacyLockContention"}}function F0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function zB($){let Z=$.now??Date.now;return{paths:$.paths,slot:$.slot,now:Z,sleep:$.sleep??((J)=>new Promise((X)=>setTimeout(X,J))),newId:$.newId??(()=>crypto.randomUUID()),log:$.log??t("pool-migration"),...$.vaultServes?{vaultServes:$.vaultServes}:{},locks:{...K6,...$.legacyLocks},leaseWait:$.leaseWait??{timeoutMs:4000,pollMs:50},store:U1({provider:r2,configPath:$.paths.configPath,statePath:$.paths.statePath,quota:j6,now:Z,...$.store}),onStep:async(J)=>{await $.onStep?.(J)}}}async function t2($){let Z;try{Z=await tQ($,"utf8")}catch(X){if(X.code==="ENOENT")return{};throw X}let J=JSON.parse(Z);if(!F0(J))throw Error("config root is not an object");return J}async function w1($,Z,J,X,z){let G=performance.now();for(;;){if(z?.aborted)throw new O2(Z);let Q=await d0({name:Z,path:J,ttlMs:X,renew:$.locks.renew,...$.locks.renewIntervalMs!==void 0?{renewIntervalMs:$.locks.renewIntervalMs}:{}});if(Q){if(!z?.aborted)return Q;throw await Q.release(),new O2(Z)}if(performance.now()-G>=$.locks.timeoutMs)throw new O2(Z);await $.sleep($.locks.retryMs)}}async function $P($,Z,J={}){let X={...K6,...J},z=performance.now();for(;;){let G=await d0({name:h1,path:$,ttlMs:X.mainRefreshTtlMs,renew:X.renew,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}});if(G)try{return await Z()}finally{await G.release().catch(()=>{})}if(performance.now()-z>=X.timeoutMs)throw new O2(h1);await new Promise((Q)=>setTimeout(Q,X.retryMs))}}async function u1($,Z){let J=$.locks.saveTtlMs,X=await w1($,"save",$.paths.configPath,J);try{let z=await w1($,"save",$.paths.statePath,J);try{let G=await t2($.paths.configPath);if(!Z(G))return;await P0($.paths.configPath,G,{beforeRename:async()=>{await X.assertOwned(),await z.assertOwned()}})}finally{await z.release().catch(()=>{})}}finally{await X.release().catch(()=>{})}}function GB($){if(!F0($))return;let{rowId:Z,operation:J,rowFingerprint:X,slotFingerprint:z}=$,{credentialFingerprint:G,carryLegacyMain:Q,recordedAt:Y,identity:B}=$;if(typeof Z!=="string"||!Z)return;if(J!=="add"&&J!=="rotate"&&J!=="replace")return;if(X!==null&&typeof X!=="string")return;if(typeof z!=="string")return;if(typeof G!=="string")return;return{rowId:Z,operation:J,rowFingerprint:X,slotFingerprint:z,credentialFingerprint:G,...typeof B==="string"&&B?{identity:B}:{},carryLegacyMain:Q===!0,recordedAt:typeof Y==="number"?Y:0}}function a8($,Z){if(!F0($)||!Z)return!1;return S0($).pending?.credentialFingerprint===D0({type:"oauth",refresh:Z})}function ZP($,Z){let J;try{J=JSON.parse(oQ($,"utf8"))}catch{return!1}return a8(J,Z)}class QB extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var BB=600000;async function JP($,Z,J={}){let X=J.now??Date.now,z=(B)=>{let W=S0(B).pending;return W&&a8(B,Z)&&X()-W.recordedAt>=BB?W:void 0},G=z(await t2($.configPath));if(!G)return!1;let Q={...K6,...J.legacyLocks},Y=await d0({name:n8,path:$.configPath,ttlMs:Q.mainRefreshTtlMs});if(!Y)return!1;try{let B=await t2($.configPath),W=S0(B).migratedAt!==void 0,H=await U1({provider:r2,configPath:$.configPath,statePath:$.statePath,quota:j6,now:X}).read();if(W&&H.status!=="ready")return!1;let V;if(H.status==="ready"){let j=H.rows.find((F)=>F.id===G.rowId&&!F.invalid),q=j?.fingerprint??null;if(W&&j&&q===G.credentialFingerprint)return!1;if(j&&q!==G.credentialFingerprint&&q!==G.rowFingerprint)V=J.slotAccess!==void 0?R$({type:"oauth",access:J.slotAccess,refresh:Z}):G.slotFingerprint}let U=!1;if(await u1({paths:$,locks:Q,sleep:(j)=>new Promise((q)=>setTimeout(q,j))},(j)=>{let q=S0(j),F=z(j);if(!F||F.recordedAt!==G.recordedAt)return!1;let{pending:K,...N}=q;return N6(j,V!==void 0?{...N,declinedSlotFingerprint:V}:N),U=!0,!0}),U)(J.log??t("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 U}finally{await Y.release().catch(()=>{})}}function S0($){let Z=$[H6];if(!F0(Z))return{};let J=GB(Z.pending);return{...typeof Z.migratedAt==="number"?{migratedAt:Z.migratedAt}:{},...J?{pending:J}:{},...typeof Z.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:Z.declinedSlotFingerprint}:{}}}function N6($,Z){let X={...F0($[H6])?$[H6]:{}};for(let z of["migratedAt","pending","declinedSlotFingerprint"])delete X[z];Object.assign(X,Z),$[H6]=X}function YB($){let Z=$?g4($):void 0;return Z?f4(Z):void 0}function WB($){let Z=R$({type:"oauth",...$}),J=YB($.access);return{kind:"real",credential:$,fingerprint:Z,credentialFingerprint:D0({type:"oauth",refresh:$.refresh}),...J?{identity:J}:{}}}function i8($){if(v1($))return{kind:"placeholder",...F0($)&&typeof $.accountId==="string"?{origin:$.accountId}:{}};let Z=f8($);if(!Z?.refresh.trim())return{kind:"empty"};return WB(Z)}async function p1($){let Z=await v8({client:{auth:{get:(J)=>$.slot.get(J),all:()=>$.slot.all()}},now:$.now,sleep:$.sleep});if(Z.kind==="real")return i8(Z.oauth);return Z.kind==="slot-absent"||Z.kind==="indeterminate"?{kind:Z.kind}:{kind:Z.kind}}async function XP($,Z){if(!v1(Z))return!1;let J=await t2($.configPath),X=await U1({provider:r2,configPath:$.configPath,statePath:$.statePath,quota:j6}).read();if(X.status==="error")return!1;let z=X.status==="ready"?X.rows.some((G)=>G.id==="main"):X.roster.some((G)=>F0(G)&&G.id==="main");return U6({kind:"placeholder"},z,S0(J))}async function VB($){let Z=$.now()+$.leaseWait.timeoutMs;for(;;){let J=await p1($);if(J.kind!=="real")return J;if(!await r8($,J.credential.refresh))return J;if($.now()>=Z)return{kind:"retry"};await $.sleep($.leaseWait.pollMs)}}async function r8($,Z){let J=await F6($.paths),X=J?.refresh?.mainRefreshLeaseUntil;return Boolean(X&&X>$.now()&&J?.refresh?.mainRefreshLeaseTokenHash===g1(Z))}function HB($){return $.length>0&&$.trim()===$&&!["__proto__","constructor","prototype","main"].includes($)}function UB($,Z,J,X,z){let G=J.identity?{identity:J.identity}:{},Q=Z.find((H)=>!H.invalid&&H.fingerprint===J.credentialFingerprint);if(Q)return{rowId:Q.id,operation:"rotate",rowFingerprint:Q.fingerprint??null,...G,carryLegacyMain:$==="migrate"&&Q.id==="main"};let Y=Z.find((H)=>H.id==="main");if(!Y||!Y.invalid&&!Y.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...G,carryLegacyMain:$==="migrate"};if(J.identity){let H=Z.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:$==="migrate"&&H.id==="main"}}let B=new Set(Z.map((H)=>H.id));return{rowId:X??(J.identity&&HB(J.identity)&&!B.has(J.identity)?J.identity:z()),operation:"add",rowFingerprint:null,...G,carryLegacyMain:!1}}function qB($,Z,J,X,z,G,Q){let Y=Z.pending;if(Y){let B=J.find((V)=>V.id===Y.rowId&&!V.invalid),W=B?.fingerprint??null,H=X.kind==="real"&&X.fingerprint===Y.slotFingerprint;if(B&&W===Y.credentialFingerprint)return{kind:"finish",record:Y};if((B||Y.rowFingerprint===null)&&W===Y.rowFingerprint)return H&&X.kind==="real"?{kind:"transfer",record:Y,credential:X.credential,fresh:!1}:{kind:"drop-record"};if(!B)return{kind:"drop-record"};return H?{kind:"ambiguous",record:Y}:{kind:"drop-record"}}if(X.kind==="indeterminate")return{kind:"drop-record"};if(X.kind!=="real")return{kind:"nothing",slot:X.kind};if(Z.declinedSlotFingerprint===X.fingerprint)return{kind:"nothing",slot:"declined"};return{kind:"transfer",record:{...UB($,J,X,z,Q),slotFingerprint:X.fingerprint,credentialFingerprint:X.credentialFingerprint,recordedAt:G},credential:X.credential,fresh:!0}}async function jB($,Z,J){let X={type:"oauth",access:J.access,refresh:J.refresh,...J.expires!==void 0?{expires:J.expires}:{}},z=Z.identity?{identity:Z.identity}:{},G={extraLocks:q6($.paths,Z.rowId,$.locks)};if(Z.operation==="add")await $.store.add({id:Z.rowId,credential:X,...z},G);else if(Z.operation==="replace")await $.store.replace(Z.rowId,X,z,G);else{let Q=await $.store.read(),Y=Q.status==="ready"?Q.rows.find((B)=>B.id===Z.rowId):void 0;await $.store.rotate(Z.rowId,X,Y?.identity===void 0?z:{},G)}}async function FB($,Z){let J=await $.store.read();if(J.status!=="ready")return;let X=J.rows.find((z)=>z.id===Z.rowId&&!z.invalid);return X?.fingerprint===Z.credentialFingerprint?X:void 0}function KB($,Z){let J=[],X=[["primary",$.primary],["secondary",$.secondary]],z=0;for(let[Y,B]of X){if(!B||!Number.isFinite(B.checkedAt)||!Number.isFinite(B.usedPercent))continue;z=Math.max(z,B.checkedAt),J.push({checkedAt:B.checkedAt,readings:[{label:Y,usedPercent:B.usedPercent,...typeof B.resetsAt==="string"?{resetsAt:B.resetsAt}:{},...Number.isFinite(B.windowMinutes)?{windowMinutes:B.windowMinutes}:{}}]})}let G=Z??(z||void 0),Q=$.spendControl;if(G!==void 0&&Q)J.push({checkedAt:G,budget:{kind:"reading",reached:Q.reached,remainingPercent:Q.remainingPercent,usedPercent:Q.usedPercent,limit:Q.limit,used:Q.used,remaining:Q.remaining,...Q.resetsAt!==void 0?{resetsAt:Q.resetsAt}:{},...Q.unit!==void 0?{unit:Q.unit}:{}}});else if(G!==void 0&&$.spendControlCleared)J.push({checkedAt:G,budget:{kind:"cleared"}});return J.sort((Y,B)=>Y.checkedAt-B.checkedAt)}async function NB($,Z){let J=await F6($.paths);if(!J)return;let X=J.quota?.mainQuotaToken,z=Z.credential?.type==="oauth"?Z.credential.access:void 0,Q=!X||z!==void 0&&X===u8(z)?J.quota?.mainQuota:void 0;if(Q&&Z.credentialEpoch!==void 0){let H={credentialEpoch:Z.credentialEpoch,...Z.identity!==void 0?{identity:Z.identity}:{}};for(let V of KB(Q,J.quota?.mainQuotaCheckedAt))try{await $.store.recordQuota(Z.id,H,V)}catch(U){$.log.warn("legacy main quota not carried to the pool row",{rowId:Z.id,error:U instanceof Error?U.message:String(U)})}}let Y=J.refresh?.mainLastRefreshError,B=J.accounts.find((H)=>H.id===Z.id);if(!B||!l8(B)||B.corrupt)return;if(!Y&&!Q)return;let W={...J,accounts:[{...B,...B.lastRefreshError||!Y?{}:{lastRefreshError:Y},...B.quota||!Q?{}:{quota:Q}}]};try{await d8(W,$.paths,{accounts:[Z.id]})}catch(H){$.log.warn("legacy main backoff not carried to the pool row",{rowId:Z.id,error:H instanceof Error?H.message:String(H)})}}async function o2($,Z,J={}){await u1($,(X)=>{let z=S0(X);if(delete X.mainAccountId,Z==="migrate"&&z.migratedAt===void 0&&DB($))PB(X);return N6(X,{...z.migratedAt!==void 0||Z==="migrate"?{migratedAt:z.migratedAt??$.now()}:{},...J.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:J.declinedSlotFingerprint}:z.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:z.declinedSlotFingerprint}:{}}),!0})}function DB($){let Z=a4($.paths.configPath);if(Z==="shared")return!1;if(Z==="separate")return!0;let J=p8({host:"opencode",paths:$.paths,logger:{warn(){}}});return J.separate||!rQ(J.target)}function PB($){let Z=$.routing;if(Z===void 0)$.routing={mode:"main-first"};else if(F0(Z)&&Z.mode===void 0)$.routing={...Z,mode:"main-first"}}async function b$($){await u1($,(Z)=>{let J=S0(Z);if(!J.pending)return!1;let{pending:X,...z}=J;return N6(Z,z),!0})}async function MB($,Z){await u1($,(J)=>{let X=S0(J);if(Z.identity)J.mainAccountId=Z.identity;return N6(J,{...X,pending:Z}),!0})}async function CB($,Z,J,X){let z=await w1($,h1,$.paths.configPath,$.locks.mainRefreshTtlMs);try{return await TB($,Z,J,X)}finally{await z.release().catch(()=>{})}}async function TB($,Z,J,X){let z=(W)=>({status:"completed",rowId:J.rowId,operation:X,placeholder:W}),G=await p1($);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!==I$($))return{status:"foreign-placeholder"};return await o2($,Z),await $.onStep("after-record-clear"),z("already-present")}if(Object.keys(await $.slot.all()).length===0)return{status:"retry",reason:"torn-read"};if(G.kind==="real"&&G.fingerprint!==J.slotFingerprint&&J.identity!==void 0&&G.identity===J.identity)return await b$($),await $.onStep("after-record-clear"),{status:"restart"};if(G.kind!=="real"||G.fingerprint!==J.slotFingerprint)return await o2($,Z),await $.onStep("after-record-clear"),z("slot-moved-on");await $.onStep("before-placeholder-write");let Q=await $.slot.get({path:{id:r2}}),Y=Q===void 0||Q===null?void 0:i8(Q);if(Y?.kind!=="real"||Y.fingerprint!==J.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await $.slot.set({path:{id:r2},body:{...m1,accountId:I$($)}})}catch(W){if(W instanceof V6)return{status:"retry",reason:"slot-changed"};throw W}await $.onStep("after-placeholder-write");let B=await $.slot.get({path:{id:r2}});if(!v1(B))return{status:"retry",reason:"placeholder-overwritten"};if(F0(B)&&B.accountId===void 0)return{status:"untagged-placeholder"};if(F0(B)&&B.accountId!==I$($))return{status:"foreign-placeholder"};return await o2($,Z),await $.onStep("after-record-clear"),z("written")}async function LB($,Z,J){let{record:X}=J;if(J.fresh)await MB($,X),await $.onStep("after-record-write");if(await r8($,J.credential.refresh))return{status:"restart"};let z=await p1($);if(z.kind!=="real"||z.fingerprint!==X.slotFingerprint)return{status:"restart"};return await jB($,X,J.credential),await $.onStep("after-row-write"),o8($,Z,X,J.fresh?X.operation:"resumed")}async function o8($,Z,J,X){let z=await FB($,J);if(!z)return{status:"retry",reason:"verify-failed"};if(await $.onStep("after-verify"),J.carryLegacyMain)await NB($,z),await $.onStep("after-carry-over");let G=await CB($,Z,J,X);if(G.status==="untagged-placeholder"){await $.store.disable(J.rowId,JB,{extraLocks:q6($.paths,J.rowId,$.locks),attribution:{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}}}),await o2($,Z);let Q=`${$.paths.configPath}\x00${J.rowId}`;if(!w8.has(Q))w8.add(Q),$.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${XB}`,{rowId:J.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(G.status!=="foreign-placeholder")return G;return await $.store.remove(J.rowId,{extraLocks:q6($.paths,J.rowId,$.locks),protect:(Q,Y)=>Y.row?.fingerprint!==J.credentialFingerprint?"the transfer row changed before rollback":void 0}),await b$($),await k$($),{status:"refused",reason:"placeholder-without-main"}}var h8=new Set,m8=new Set,w8=new Set;function I$($){return`openai-auth-pool:${iQ("sha256").update(eQ($.paths.configPath)).digest("hex")}`}async function OB($){try{let Z=await $();return Z.open?[]:Z.blockers}catch(Z){return[{pid:"unknown",version:"unknown",detail:Z instanceof Error?Z.message:String(Z)}]}}async function t8($,Z,J){let X=zB($),z=X.slot.migrationDisabledReason?.();if(z){let W=X.slot.path??W6();if(!m8.has(W))m8.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 t2(X.paths.configPath)}catch(W){return{status:"error",reason:W instanceof Error?W.message:String(W)}}let Q=await e8(X,Z,G);if(Q){if(Q.status==="already-migrated"&&"mainAccountId"in G)await k$(X);return Q}if(J){let W=await OB(J);if(W.length>0){let H=`${X.paths.configPath}\x00${W.map((V)=>`${V.pid}@${V.version}`).join(",")}`;if(!h8.has(H))h8.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 Y,B;try{B=await w1(X,"pool-slot-transfer",X.slot.path??W6(),X.locks.mainRefreshTtlMs,$.signal),Y=await w1(X,n8,X.paths.configPath,X.locks.mainRefreshTtlMs,$.signal)}catch(W){if(await B?.release().catch(()=>{}),W instanceof O2)return{status:"retry",reason:"lock-contention"};throw W}try{return await _B(X,Z)}catch(W){if(W instanceof O2)return{status:"retry",reason:"lock-contention"};if(W instanceof b)return{status:"retry",reason:W.kind==="lock-contention"?"lock-contention":`store-${W.kind}`};throw W}finally{await Y?.release().catch(()=>{}),await B?.release().catch(()=>{})}}async function e8($,Z,J){let X=S0(J);if(X.pending)return;if(Z==="migrate"&&X.migratedAt!==void 0){let z=await $.store.read();if(z.status==="ready"&&!z.rows.some((G)=>G.id==="main")&&!X.pending&&U6(await p1($),z.rows.some((G)=>G.id==="main"),X))return{status:"refused",reason:"placeholder-without-main"};return{status:"already-migrated"}}if(Z==="adopt"&&X.migratedAt===void 0)return{status:"not-migrated"};return}async function _B($,Z){let J;for(let X=0;X<4;X++){let z=await t2($.paths.configPath),G=await e8($,Z,z);if(G){if(G.status==="already-migrated")await k$($);return G}let Q=await $.store.read(),Y=S0(z);if(Q.status==="pending-migration"){if(U6(await p1($),Q.roster.some((V)=>F0(V)&&V.id==="main"),Y))return{status:"refused",reason:"placeholder-without-main"};await $.store.initialize(),await $.onStep("after-pool-key-write"),Q=await $.store.read()}if(Q.status!=="ready")return{status:"error",reason:Q.status==="error"?`${Q.file}: ${Q.reason}`:"pool still pending migration"};let B=await VB($);if(B.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(B.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(U6(B,Q.rows.some((V)=>V.id==="main"),Y))return{status:"refused",reason:"placeholder-without-main"};let W=qB(Z,Y,Q.rows,B,J,$.now(),$.newId);if(W.kind==="nothing"){if(Z==="migrate")await o2($,Z),await $.onStep("after-marker-write");return{status:"nothing-to-import",slot:W.slot}}if(W.kind==="drop-record"){await b$($),await $.onStep("after-record-clear");continue}if(W.kind==="ambiguous")return await o2($,Z,{declinedSlotFingerprint:W.record.slotFingerprint}),await $.onStep("after-record-clear"),$.log.warn("interrupted slot transfer left alone: the row was rotated since, so the slot copy may be stale; the next login resolves it",{rowId: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 o8($,Z,W.record,"resumed"):await LB($,Z,W);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function k$($){await u1($,(Z)=>{if(!("mainAccountId"in Z))return!1;if(S0(Z).pending)return!1;return delete Z.mainAccountId,!0})}function zP($){return t8($,"migrate",$.fence)}function GP($){return t8($,"adopt")}class $J extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function q6($,Z,J={}){let X={...K6,...J},z={renew:X.renew,timeoutMs:X.timeoutMs,retryMs:X.retryMs,...X.renewIntervalMs!==void 0?{renewIntervalMs:X.renewIntervalMs}:{}};return[{name:h1,path:$.configPath,ttlMs:X.mainRefreshTtlMs,...z},{name:s8(Z),path:$.configPath,ttlMs:X.fallbackTtlMs,...z}]}async function QP($,Z,J,X={}){let z=$.now??Date.now,G=$.sleep??((B)=>new Promise((W)=>setTimeout(W,B))),Q=$.leaseWait??{timeoutMs:4000,pollMs:50},Y=async(B,W)=>{let H=g1(B.refresh),V=async()=>{let U=await F6($.paths),j=U?.refresh?.mainRefreshLeaseUntil;return Boolean(j&&j>z()&&U?.refresh?.mainRefreshLeaseTokenHash===H)};if(await V()){let U=z()+Q.timeoutMs;while(z()<U&&await V())await G(Q.pollMs);throw new $J}return J(B,W)};return $.store.refresh(Z,Y,{...X,extraLocks:q6($.paths,Z,$.legacyLocks)})}function ZJ(){let $=crypto.getRandomValues(new Uint8Array(16)),Z=Date.now();$[0]=Z/1099511627776&255,$[1]=Z/4294967296&255,$[2]=Z/16777216&255,$[3]=Z/65536&255,$[4]=Z/256&255,$[5]=Z&255,$[6]=($[6]??0)&15|112,$[8]=($[8]??0)&63|128;let J=Array.from($,(X)=>X.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}import{chmodSync as SB,mkdirSync as JJ,readFileSync as AB,renameSync as EB,writeFileSync as RB}from"node:fs";import{dirname as XJ}from"node:path";var x$="sessions",IB=1e4,bB=5000,kB=25;async function xB($,Z=bB){let J=performance.now()+Z;for(;;){let X=await d0({name:x$,path:$,ttlMs:IB});if(X||performance.now()>=J)return X;await new Promise((z)=>setTimeout(z,kB))}}function yB($){let Z=new Map,J=JSON.parse(AB($,"utf8"));if(!E(J.sessions))return Z;for(let[X,z]of Object.entries(J.sessions)){if(!E(z)||typeof z.threadID!=="string")continue;Z.set(X,z.threadID)}return Z}function jP($,Z=ZJ){let J=new Map,X;try{X=yB($)}catch{return J}for(let[z,G]of X)J.set(z,{threadID:G,turnID:Z(),windowID:`${G}:0`});return J}function gB($,Z){let J=`${$}.tmp-${process.pid}`;JJ(XJ($),{recursive:!0});let X={version:1,sessions:Object.fromEntries([...Z].map(([z,G])=>[z,{threadID:G}]))};RB(J,`${JSON.stringify(X,null,2)}
70
+ `,{encoding:"utf8",mode:384}),SB(J,384),EB(J,$)}var l1=new Map;function FP($){return l1.get($)??Promise.resolve()}function KP($,Z){let X=(l1.get($)??Promise.resolve()).then(async()=>{let z=null;try{if(JJ(XJ($),{recursive:!0}),z=await xB($),!z)return;gB($,[...Z.entries()].map(([G,Q])=>[G,Q.threadID]))}catch{}finally{await z?.release().catch(()=>{})}});return l1.set($,X),X.then(()=>{if(l1.get($)===X)l1.delete($)}),X}import{randomUUID as nB}from"node:crypto";import{chmod as aB,mkdir as iB,rename as rB,rm as f$,writeFile as oB}from"node:fs/promises";import{homedir as tB}from"node:os";import{join as D6}from"node:path";import{chmod as PP,mkdir as MP,readdir as fB,readFile as vB,rename as CP,rm as hB,stat as mB,writeFile as TP}from"node:fs/promises";import{homedir as wB,uptime as uB}from"node:os";import{join as _2}from"node:path";var pB="1.15.0",lB=QJ("openai-auth-");function dB($){let Z=$??(process.env.XDG_STATE_HOME||_2(wB(),".local","state"));return _2(Z,"cortexkit","openai-auth")}function g$($){let Z;for(let J of $){if(J==="legacy")return"legacy";if(J==="shared"||Z===void 0)Z=J}return Z}var BJ=Symbol.for("@cortexkit/openai-auth/pi-settings-records"),YJ=globalThis,cB=YJ[BJ]??new Map;YJ[BJ]=cB;function sB($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}function zJ($){let Z=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec($.trim());if(!Z)return!1;let J=Z.slice(1,4).map(Number);if(!J.every(Number.isSafeInteger))return!1;let X=pB.split(".").map(Number);for(let z=0;z<3;z++){let G=J[z];if(G!==X[z])return G>X[z]}return Z[4]===void 0}async function GJ($,Z){let J;try{J=await vB($,"utf8")}catch(X){return{kind:X.code==="ENOENT"?"gone":"unreadable"}}try{let X=JSON.parse(J);if(X!==null&&typeof X==="object"&&!Array.isArray(X)&&X.pid===Z)return{kind:"ok",version:typeof X.version==="string"?X.version:"unknown",startedAt:X.startedAt,settings:X.settings}}catch{}return{kind:"unreadable"}}async function AP($={}){let Z=dB($.stateHome),J=$.selfPid??process.pid,X=($.now??Date.now)()-($.uptime??uB)()*1000-300000,z=(V)=>typeof V==="number"&&Number.isFinite(V)&&V<X,G=(V)=>{try{return($.isAlive??sB)(V)}catch{return!0}},Q=[],Y=(V,U,j)=>{if(!Q.some((q)=>q.pid===V&&(V!=="unknown"||q.detail===j)))Q.push({pid:V,version:U,detail:j})},B=async(V,U=!1)=>{try{return await fB(V)}catch(j){let q=j.code;if(q!=="ENOENT"&&!(U&&q==="ENOTDIR"))Y("unknown","unknown",V);return[]}},W=(V,U)=>{let j=U.exec(V),q=j?Number(j[1]):NaN;return Number.isSafeInteger(q)&&q>0?q:void 0};for(let V of["processes","pi-processes"]){let U=_2(Z,V);for(let j of await B(U)){let q=W(j,/^(\d+)\.json$/);if(q===void 0||q===J)continue;let F=_2(U,j),K=await GJ(F,q);if(K.kind==="gone")continue;if(K.kind==="ok"&&z(K.startedAt)){await hB(F,{force:!0}).catch(()=>{});continue}if(!G(q))continue;if(K.kind==="unreadable"){Y(q,"unknown",F);continue}if(K.settings==="separate")continue;if(K.settings==="legacy"||K.settings!==void 0&&K.settings!=="shared"||V==="processes"&&!zJ(K.version)||V==="pi-processes"&&K.settings===void 0)Y(q,K.version,F)}}let H=$.rpcDir??_2(Z,"rpc");for(let V of await B(H)){if(!lB(V))continue;let U=_2(H,V);for(let j of await B(U,!0)){let q=W(j,/^port-(\d+)\.json$/);if(q===void 0||q===J||!G(q))continue;let F=_2(U,j),K=await GJ(F,q);if(K.kind==="gone")continue;if(K.kind==="ok"){let N=K.startedAt===void 0?await mB(F).then((D)=>D.mtimeMs).catch(()=>{return}):K.startedAt;if(z(N))continue}if(K.kind==="unreadable"||!zJ(K.version))Y(q,K.kind==="ok"?K.version:"unknown",F)}}return Q.sort((V,U)=>(V.pid==="unknown"?1/0:V.pid)-(U.pid==="unknown"?1/0:U.pid)),Q.length?{open:!1,blockers:Q}:{open:!0}}function P6(){let $=process.env.XDG_STATE_HOME||D6(tB(),".local","state");return D6($,"cortexkit","openai-auth","processes")}function WJ($=process.pid,Z=P6()){return D6(Z,`${$}.json`)}var d1=0,e2,VJ=Symbol.for("@cortexkit/openai-auth/process-layouts"),HJ=globalThis,M6=HJ[VJ]??new Map;HJ[VJ]=M6;var UJ=Symbol.for("@cortexkit/openai-auth/process-settings"),qJ=globalThis,s0=qJ[UJ]??{decisions:new Map,writing:Promise.resolve()};qJ[UJ]=s0;function v$(){return{...Object.fromEntries(M6),...X0()?{"*":"legacy"}:{}}}function eB(){if(X0())return!0;for(let $ of M6.values())if($==="legacy")return!0;return!1}async function h$($,Z){let J=s0.writing.catch(()=>{}).then(()=>$Y($,{...Z,settings:g$(s0.decisions.values())}));return s0.writing=J,J}async function $Y($,Z){await iB($,{recursive:!0,mode:448}),await aB($,448);let J=WJ(Z.pid,$),X=D6($,`0${Z.pid}.json`),z=X0()?[X,J]:[J];if(!X0())await f$(X,{force:!0}).catch(()=>{});for(let G of z){let Q=`${G}.${nB()}.tmp`;try{await oB(Q,`${JSON.stringify(Z)}
71
+ `,{mode:384}),await rB(Q,G)}catch(Y){throw await f$(Q,{force:!0}).catch(()=>{}),Y}}return J}async function fP($){let Z=$.pid??process.pid,J=$.dir??P6();e2??=($.now??Date.now)(),d1++;let X;try{X=await h$(J,{pid:Z,version:$.version,startedAt:e2,layouts:v$()})}catch(G){$.logger.warn("process heartbeat not written",{dir:J,error:G instanceof Error?G.message:String(G)})}let z=!1;return{path:X,async release(){if(z)return;if(z=!0,d1=Math.max(0,d1-1),d1>0)return;let G=s0.writing.catch(()=>{}).then(async()=>{if(d1>0||eB()||g$(s0.decisions.values())==="legacy")return;await f$(WJ(Z,J),{force:!0}).catch((Q)=>{$.logger.warn("process heartbeat not removed",{dir:J,error:Q instanceof Error?Q.message:String(Q)})})});s0.writing=G,await G}}}async function C6($){let Z=X0()?"legacy":$.layout;if(M6.set($.key,Z),Z!=="legacy")return;e2??=($.now??Date.now)(),await h$($.dir??P6(),{pid:$.pid??process.pid,version:$.version,startedAt:e2,layouts:v$()})}async function vP($){let Z=y$($.configPath);if(!s0.decisions.has(Z))s0.decisions.set(Z,$.settings);e2??=($.now??Date.now)(),await h$($.dir??P6(),{pid:$.pid??process.pid,version:$.version,startedAt:e2,layouts:v$()})}import{createHash as ZY}from"node:crypto";import{realpathSync as JY}from"node:fs";import{chmod as XY,mkdir as zY,readdir as TJ,readFile as A0,rmdir as LJ,stat as OJ,unlink as n1}from"node:fs/promises";import{basename as w$,dirname as O6,isAbsolute as GY,join as m,relative as QY,resolve as _6}from"node:path";var BY="runtime-layout",$1="layout-moving.json",_J=1e4,T6=15000,YY=4*T6+_J,WY=50,VY=5,HY=50,UY=[0,10,20,40,80,100],jJ=500,qY="openai-auth keeps its files in OpenCode's config folder until every running OpenCode using it has restarted on this version.",FJ="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 z0 extends Error{stateDir;errorClass;constructor($,Z,J=jY($,Z)){super(J);this.stateDir=$;this.errorClass=Z;this.name="RuntimeLayoutRefusal"}}function jY($,Z){if(Z==="ERR_PRIVATE_FILES_SECURITY")return`openai-auth cannot start: ${$} is not a folder only your user can access, or it is a link, so the plugin will not use it (${Z}). Replace it with a plain folder of your own, then restart OpenCode.`;return`openai-auth cannot start: it could not settle where its runtime files live in ${$} (${Z}). Check that this folder can be created and written by your user, then restart OpenCode.`}function KJ($,Z){return new z0($,"foreign-folder",`openai-auth cannot start: ${$} belongs to another OpenCode config folder, not ${Z}. It was left untouched. Move it aside, then restart OpenCode.`)}function S6($,Z){return new z0($,"credential-conflict",`openai-auth cannot start: runtime credentials conflict between ${Z.old} and ${Z.next}. Keep the newer one, delete the other, then restart OpenCode.`)}function tP(){let $=c0.notice;if(!$||$.shown)return;return $.shown=!0,$.text}function g0($,Z){if(c0.logged.has($))return;c0.logged.add($),Z()}function n0($){if($ instanceof z0)return $.errorClass;let Z=$?.code;if(typeof Z==="string"&&Z)return Z;return $ instanceof Error?$.name:typeof $}function FY($){let{path:Z,stage:J}=$??{};return{...typeof Z==="string"&&Z?{file:w$(Z)}:{},...typeof J==="string"&&J?{stage:J}:{}}}class s1 extends Error{code;constructor($,Z){super(Z);this.code=$;this.name="LayoutMoveError"}}class u$ extends s1{path;constructor($){super("old-credential-kept",`${$} could not be removed`);this.path=$}}function SJ($,Z,J,X){g0(`${$.key}\x00cleanup`,()=>Z.warn("openai-auth could not finish removing its old files from OpenCode's config folder; it tries again at the next start",{configDir:$.configDir,step:J,errorClass:n0(X),...FY(X)}))}function eP($){let Z=Q6(),J=Y6(Z);if(J)return Promise.resolve(J);let X=`${Z.stateHomeDir}\x00${Z.key}`,z=c0.runs.get(X);if(!z)z=KY(Z,$).catch((G)=>{if(G instanceof z0)throw G;throw new z0(Z.stateHomeDir,n0(G))}).finally(()=>{c0.runs.delete(X)}),c0.runs.set(X,z);return z}async function KY($,Z){let J=Z.log??t("runtime-layout");if(X0()){B6($,"legacy"),g0("legacy-generation",()=>J.info("openai-auth keeps its runtime files in OpenCode's config folder until restart: an older plugin version ran in this process"));try{await C6({key:$.key,layout:"legacy",version:Z.version})}catch(K){J.warn("process heartbeat not written",{errorClass:n0(K)})}return"legacy"}let X=$.stateHomeDir,z=m(X,J6),G=l$($),Q=DY(),Y=Q.length>0,B=Q.some((K)=>AJ(K,X)),W=Z.fence??NY(Z.version),H=async()=>{return await C6({key:$.key,layout:"state-home",version:Z.version}),B6($,"state-home"),"state-home"},V=await c1(z,X);if(await CJ($,V),V?.oldFilesRemoved&&!B){await xY($,G,Q,V,J);let K=await K0(m(X,$1)).catch(()=>!0),N=!Y&&(await kJ(G).catch(()=>[!0])).length>0;if(!K&&!N)return H()}let U=await fJ($.configDir,X),j;try{if(!U)await hJ(X);j=await L6(BY,z,Z.layoutLockWaitMs??YY)}catch(K){if(V=await c1(z,X),V&&!B)return H();throw new z0(X,n0(K))}let q=j,F=async()=>{try{await q.assertOwned(),await C6({key:$.key,layout:"legacy",version:Z.version})}catch(K){throw new z0(X,n0(K))}return B6($,"legacy"),"legacy"};try{if(V=await c1(z,X),await CJ($,V),!U)await yY($);if(B)return g0(`${$.key}\x00override`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: a path set by OPENCODE_OPENAI_AUTH_STATE_FILE or OPENCODE_OPENAI_AUTH_FILE is inside its state folder, which it never touches",{stateDir:X,overrides:Q})),await F();if(V){if(!Y&&!U)await MY($,G,z,V,q,{fence:W,log:J,steps:Z.steps});else if(V.oldFilesRemoved)await CY($,q,Z.steps,J);return await H()}if(Y)return await F();if(U)return g0(`${$.key}\x00aliased`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: its state folder is that same folder",{configDir:$.configDir,stateDir:X})),await F();let K=await W();if(!K.open)return NJ($,K.blockers,J),await F();let N=!1;try{let D=await PY($,G,z,q,{fence:W,log:J,steps:Z.steps,onMarker:()=>{N=!0}});if(D.kind==="deferred")return NJ($,D.blockers,J),await F();if(D.kind==="refused")return g0(`${$.key}\x00refused`,()=>J.warn("openai-auth keeps its runtime files in OpenCode's config folder: it will not move them",{reason:D.reason,paths:D.paths,stateDir:X})),await F();if(D.moved)J.info("openai-auth moved its runtime files out of OpenCode's config folder",{from:$.configDir,to:X});return await H()}catch(D){if(D instanceof z0)throw D;if(N&&await c1(z,X))return await H();return g0(`${$.key}\x00failed`,()=>J.warn("openai-auth's runtime files stay in OpenCode's config folder: moving them failed; the move is tried again at the next start",{configDir:$.configDir,errorClass:n0(D)})),await F()}}finally{await q.release().catch(()=>{})}}function NY($){return()=>N8({currentVersion:$,layoutMove:!0})}function NJ($,Z,J){g0(`${$.key}\x00deferred`,()=>J.info(qY,{configDir:$.configDir,blockers:Z}))}function DY(){let $=S8();if($===void 0)return[];let Z=A8();return[$,v4($),...Z?[Z]:[]]}function AJ($,Z){let J=QY(DJ(Z),DJ($));if(J==="")return!0;if(!J.startsWith("..")&&!GY(J))return!0;return G6($,Z)}function DJ($){let Z=_6($),J=[];for(;;){try{return m(JY.native(Z),...J)}catch{}let X=O6(Z);if(X===Z)return _6($);J.unshift(w$(Z)),Z=X}}async function PY($,Z,J,X,z){let G=$.stateHomeDir,Q=await RJ($,Z),Y=!1;try{let B=await z.fence();if(!B.open)return{kind:"deferred",blockers:B.blockers};let W=await gJ($,Z);if(W.length>0)return{kind:"refused",reason:"same-physical-file",paths:W};let H=await gY(G),V=(await EY(Z)).filter((K)=>!H.has(K));if(V.length>0)return{kind:"refused",reason:"destination-in-use",paths:V};let U=await yJ(Z);await X.assertOwned(),await fY(G,[...new Set([...H,...U.map((K)=>K.next)])]);let j=new Set(U.map((K)=>K.next));for(let K of H){if(j.has(K))continue;await X.assertOwned(),await n1(K).catch((N)=>{if(N.code!=="ENOENT")throw N})}for(let K of U)await X.assertOwned(),await RY(K);await z.steps?.afterCopy?.(),await X.assertOwned();for(let K of Q)await K.assertOwned();let q=await OY(Z,U),F={version:1,oldDir:$.key,...q?{keptVaultState:q}:{}};z.onMarker(),await m$(J,F),await z.steps?.afterMarker?.(),await X.assertOwned();try{await vJ($,U,X,{log:z.log,keptVaultState:q,steps:z.steps}),await xJ(Z,X,Q,z.steps)}catch(K){if(!(K instanceof u$))throw K;return SJ($,z.log,"remove-old-copies",K),{kind:"moved",moved:U.length>0}}return Y=!0,await X.assertOwned(),await m$(J,{...F,oldFilesRemoved:!0}),await p$(G,X,z.steps),{kind:"moved",moved:U.length>0}}finally{for(let B of Q.reverse())await B.release().catch(()=>{});if(Y)await EJ(Z,X,z.steps)}}async function MY($,Z,J,X,z,G){let Q=[],Y=!1,B="fence";try{if(!(await G.fence()).open)return;if(B="data-locks",Q=await RJ($,Z),B="fence",!(await G.fence()).open)return;B="same-file-check";let W=await gJ($,Z);if(W.length>0){g0(`${$.key}\x00cleanup-aliased`,()=>G.log.warn("openai-auth leaves its old files in OpenCode's config folder: they are the same files as its new ones",{paths:W}));return}if(B="remove-old-copies",await z.assertOwned(),!X.oldFilesRemoved)await vJ($,await yJ(Z),z,{log:G.log,keptVaultState:X.keptVaultState,steps:G.steps});B="remove-old-temps",await xJ(Z,z,Q,G.steps),Y=!0,B="marker",await z.assertOwned(),await m$(J,{...X,oldFilesRemoved:!0}),B="manifest",await p$($.stateHomeDir,z,G.steps)}catch(W){if(W instanceof z0)throw W;SJ($,G.log,B,W)}finally{for(let W of Q.reverse())await W.release().catch(()=>{});if(Y)await EJ(Z,z,G.steps)}}async function CY($,Z,J,X){try{await p$($.stateHomeDir,Z,J)}catch(z){g0(`${$.key}\x00manifest`,()=>X.warn(`openai-auth could not remove ${$1} from its state folder; it tries again at the next start`,{stateDir:$.stateHomeDir,errorClass:n0(z)}))}}async function p$($,Z,J){let X=m($,$1);if(!await K0(X))return;await J?.beforeRemove?.(X),await Z.assertOwned(),await vY($)}async function EJ($,Z,J){try{await J?.beforeRemove?.($.vault.old),await Z.assertOwned(),await LJ($.vault.old)}catch{}}async function RJ($,Z){let J=[];try{if(await K0($.configDir)){if(J.push(await L6("save",Z.state.old,T6)),await K0(Z.vault.old))J.push(await L6("claustrum-roster-write",D2(Z.vault.old,"opencode").rosterPath,T6));for(let X of Z.sessions)J.push(await L6(x$,X.old,T6))}return J}catch(X){for(let z of J.reverse())await z.release().catch(()=>{});throw X}}function l$($){let Z=m($.configDir,f1),J=m($.stateHomeDir,f1);return{state:{old:Z,next:J},vault:{old:v4(Z),next:v4(J)},sessions:[L$,O$].map((X)=>({old:m($.configDir,X),next:m($.stateHomeDir,X)}))}}var TY=/^[0-9a-f]{64}$/;function IJ($){return ZY("sha256").update($).digest("hex")}function A6($){return{old:D2($.vault.old,"opencode").statePath,next:D2($.vault.next,"opencode").statePath}}var PJ=R9("opencode"),LY="opencode-enrollment-no-token.json";async function bJ($){try{let Z=await x4($,PJ);return Z.state==="blocked"&&Z.code==="missing_token"&&Z.proposedName===PJ}catch{return!1}}async function OY($,Z){let J=A6($);if(!Z.some((z)=>z.old===J.old))return;return await bJ({statePath:J.next,tokenPath:m($.vault.next,LY)})?IJ(await A0(J.next)):void 0}async function _Y($,Z){if(!Z)return!1;try{return IJ(await A0($))===Z}catch{return!1}}async function d$($,Z){if(!Z)return!1;let J=D2($.vault.old,"opencode");if(await _Y(J.statePath,Z))return!0;return bJ(J)}async function $M($){let Z=Q6(),J=l$(Z);if(_6($)!==_6(J.vault.next))return;let X=Z.stateHomeDir,z=await c1(m(X,J6),X);if(!z?.keptVaultState||z.oldDir!==Z.key)return;let G=A6(J).old;if(!await d$(J,z.keptVaultState))return;await n1(G).catch((Q)=>{if(Q.code!=="ENOENT")throw Q}),await LJ(J.vault.old).catch(()=>{})}function SY($){return $.includes(".lock")||$.includes(".tmp")}var AY=/^[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 kJ($){let Z=D2($.vault.old,"opencode"),J=[$.state.old,...$.sessions.map((z)=>z.old),Z.rosterPath,Z.statePath,Z.tokenPath],X=[];for(let z of new Set(J.map(O6))){let G;try{G=await TJ(z,{withFileTypes:!0})}catch(Y){if(Y.code==="ENOENT")continue;throw Y}let Q=J.filter((Y)=>O6(Y)===z).map((Y)=>`${w$(Y)}.`);for(let Y of G)if(Y.isFile()&&Q.some((B)=>Y.name.startsWith(B)&&AY.test(Y.name.slice(B.length))))X.push(m(z,Y.name))}return X}async function xJ($,Z,J,X){for(let z of await kJ($)){await X?.beforeRemove?.(z),await Z.assertOwned();for(let G of J)await G.assertOwned();await n1(z).catch((G)=>{if(G.code!=="ENOENT")throw G})}}async function E6($){let Z;try{Z=await TJ($,{withFileTypes:!0})}catch(J){let X=J.code;if(X==="ENOENT"||X==="ENOTDIR")return[];throw J}return Z.filter((J)=>J.isFile()&&!SY(J.name)).map((J)=>J.name).sort()}async function yJ($){let Z=[];if(await K0($.state.old))Z.push($.state);for(let J of await E6($.vault.old))Z.push({old:m($.vault.old,J),next:m($.vault.next,J)});for(let J of $.sessions)if(await K0(J.old))Z.push(J);return Z}async function EY($){let Z=[];if(await K0($.state.next))Z.push($.state.next);for(let J of await E6($.vault.next))Z.push(m($.vault.next,J));for(let J of $.sessions)if(await K0(J.next))Z.push(J.next);return Z}async function gJ($,Z){let J=[[$.configDir,$.stateHomeDir],[Z.vault.old,Z.vault.next],[Z.state.old,Z.state.next],...Z.sessions.map((z)=>[z.old,z.next])];for(let z of await E6(Z.vault.old))J.push([m(Z.vault.old,z),m(Z.vault.next,z)]);let X=[];for(let[z,G]of J)if(await fJ(z,G))X.push(z);return X}async function fJ($,Z){let J=async(z)=>{try{let G=await OJ(z,{bigint:!0});return G.ino===0n?void 0:`${G.dev}:${G.ino}`}catch(G){let Q=G.code;if(Q==="ENOENT"||Q==="ENOTDIR")return;throw G}},X=await J($);return X!==void 0&&X===await J(Z)}async function RY($){let Z=await A0($.old),J=Z.toString("utf8");if(!Buffer.from(J,"utf8").equals(Z))throw new s1("not-utf8",`${$.old} is not UTF-8 text`);if(await R6($.next,J),!(await A0($.next)).equals(Z))throw new s1("copy-mismatch",`${$.next} does not match ${$.old}`)}async function vJ($,Z,J,X){let z=[],G=[],Q=l$($),Y=A6(Q).old,B=[...Z.filter((H)=>H.old!==Y),...Z.filter((H)=>H.old===Y)];for(let H of B){if(await J.assertOwned(),H.old===Y){if(await d$(Q,X.keptVaultState))continue;if(G.length>0)continue;if(X.keptVaultState&&await IY(H.old,H.next))continue}let V=H.old===Q.state.old||AJ(H.old,Q.vault.old);if(!await kY(H,$.stateHomeDir,V,()=>bY(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:$.configDir,kept:z});let[W]=G;if(W!==void 0)throw new u$(W)}async function IY($,Z){try{return(await A0($)).equals(await A0(Z))}catch{return!1}}async function bY($,Z,J){await J?.beforeRemove?.($),await Z.assertOwned()}function MJ($){let Z=$?.code;return process.platform==="win32"&&(Z==="EBUSY"||Z==="EPERM"||Z==="EACCES")}async function kY($,Z,J,X){let z=performance.now();for(let G of UY){if(G>0)await new Promise((Y)=>setTimeout(Y,G));let Q;try{Q=(await A0($.old)).equals(await A0($.next))}catch(Y){if(Y.code==="ENOENT"&&!await K0($.old))return!0;if(MJ(Y)){if(performance.now()-z>=jJ)return!1;continue}if(J)throw S6(Z,$);return!1}if(!Q){if(J)throw S6(Z,$);return!1}await X();try{return await n1($.old),!0}catch(Y){if(Y.code==="ENOENT")return!0;if(!MJ(Y)||performance.now()-z>=jJ)return!1}}return!1}async function xY($,Z,J,X,z){let G=(Y)=>J.some((B)=>G6(B,Y));if(!G(Z.state.old)&&await K0(Z.state.old))throw S6($.stateHomeDir,Z.state);if(!G(Z.vault.old)){let Y=A6(Z).old;for(let B of await E6(Z.vault.old)){let W=m(Z.vault.old,B);if(W===Y&&await d$(Z,X.keptVaultState))continue;if(!G(W))throw S6($.stateHomeDir,{old:W,next:m(Z.vault.next,B)})}}let Q=[];try{for(let Y of Z.sessions)if(await K0(Y.old))Q.push(Y.old)}catch{}if(Q.length===0)return;g0(`${$.key}\x00reappeared`,()=>{c0.notice={text:`${FJ} Old folder: ${$.configDir}`,shown:!1},z.warn(FJ,{configDir:$.configDir,stateDir:$.stateHomeDir,found:Q})})}async function c1($,Z){let J,X;for(let z=0;z<VY;z++){if(z>0)await new Promise((G)=>setTimeout(G,HY));try{J=await A0($,"utf8");break}catch(G){let Q=G.code;if(Q==="ENOENT"||Q==="ENOTDIR")return;X=G}}if(J===void 0)throw new z0(Z,n0(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"&&TY.test(z.keptVaultState)?{keptVaultState:z.keptVaultState}:{}}}catch{}throw new z0(Z,"malformed-marker",`openai-auth cannot start: ${$} is malformed. The old files are still in OpenCode's config folder. Delete layout.json, then restart OpenCode.`)}async function CJ($,Z){let J=$.stateHomeDir;if(Z?.oldDir!==void 0&&Z.oldDir!==$.key)throw KJ(J,$.key);let X;try{X=await A0(m(J,_$),"utf8")}catch(G){let Q=G.code;if(Q==="ENOENT"||Q==="ENOTDIR")return;throw new z0(J,n0(G))}let z;try{z=JSON.parse(X)?.configDir}catch{}if(z!==$.key)throw KJ(J,$.key)}async function yY($){let Z=m($.stateHomeDir,_$);if(await K0(Z))return;await R6(Z,`${JSON.stringify({version:1,configDir:$.key},null,2)}
72
+ `)}async function gY($){let Z;try{Z=await A0(m($,$1),"utf8")}catch(J){if(J.code==="ENOENT")return new Set;throw J}try{let J=JSON.parse(Z);if(Array.isArray(J?.files))return new Set(J.files.filter((X)=>typeof X==="string"))}catch{}return new Set}async function fY($,Z){await R6(m($,$1),`${JSON.stringify({version:1,files:Z},null,2)}
73
+ `)}async function vY($){await n1(m($,$1)).catch((Z)=>{if(Z.code!=="ENOENT")throw Z})}async function m$($,Z){await R6($,`${JSON.stringify(Z,null,2)}
74
+ `)}async function R6($,Z){await hJ(O6($)),await P0($,null,{serialize:()=>Z,durable:!0,durability:"file-only-on-windows"})}async function hJ($){if(process.platform==="win32")return;await zY($,{recursive:!0,mode:448}),await XY($,448)}async function L6($,Z,J){let X=performance.now();for(;;){let z=null;try{z=await d0({name:$,path:Z,ttlMs:_J,renew:!0})}catch(G){if(G.code!=="ENOENT")throw G}if(z)return z;if(performance.now()-X>=J)throw new s1("lock-timeout",`${$} lock at ${Z}`);await new Promise((G)=>setTimeout(G,WY))}}async function K0($){try{return await OJ($),!0}catch(Z){let J=Z.code;if(J==="ENOENT"||J==="ENOTDIR")return!1;throw Z}}
75
+ export{U1 as oa,u as pa,lX as qa,R as ra,dX as sa,D4 as ta,m0 as ua,K5 as va,E as wa,YZ as xa,Mz as ya,R9 as za,Cz as Aa,v4 as Ba,D2 as Ca,tq as Da,Tz as Ea,eq as Fa,$j as Ga,Oz as Ha,h4 as Ia,HZ as Ja,I9 as Ka,g9 as La,v9 as Ma,C2 as Na,h9 as Oa,d2 as Pa,_1 as Qa,iz as Ra,ez as Sa,$G as Ta,H0 as Ua,T2 as Va,ZG as Wa,R1 as Xa,zG as Ya,WF as Za,VF as _a,HF as $a,UF as ab,qF as bb,jF as cb,$6 as db,_K as eb,n7 as fb,zQ as gb,a7 as hb,xK as ib,vK as jb,j7 as kb,NG as lb,NF as mb,DF as nb,MG as ob,LF as pb,OF as qb,_F as rb,D7 as sb,RF as tb,jQ as ub,QN as vb,HN as wb,UN as xb,DQ as yb,qN as zb,jN as Ab,FN as Bb,KN as Cb,XK as Db,zK as Eb,G2 as Fb,GK as Gb,QK as Hb,fG as Ib,BK as Jb,YK as Kb,WK as Lb,TN as Mb,LN as Nb,ON as Ob,_N as Pb,fF as Qb,LG as Rb,mF as Sb,wF as Tb,vG as Ub,qK as Vb,jK as Wb,FK as Xb,hG as Yb,KK as Zb,c2 as _b,G$ as $b,oG as ac,MK as bc,_Q as cc,dB as dc,AP as ec,N8 as fc,bD as gc,kD as hc,$B as ic,m1 as jc,JB as kc,XB as lc,$P as mc,ZP as nc,QB as oc,JP as pc,S0 as qc,XP as rc,zP as sc,GP as tc,q6 as uc,QP as vc,h1 as wc,I8 as xc,W6 as yc,y8 as zc,V6 as Ac,wD as Bc,ZJ as Cc,bB as Dc,xB as Ec,yB as Fc,jP as Gc,gB as Hc,FP as Ic,KP as Jc,fP as Kc,vP as Lc,tP as Mc,eP as Nc,$M as Oc};