@cortexkit/pi-openai-auth 0.11.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,12 @@
1
- var I3=Object.defineProperty;var R3=($)=>$;function A3($,Z){this[$]=R3.bind(null,Z)}var T3=($,Z)=>{for(var z in Z)I3($,z,{get:Z[z],enumerable:!0,configurable:!0,set:A3.bind(Z,z)})};var C3=($,Z)=>()=>($&&(Z=$($=0)),Z);var a1={};T3(a1,{toResetIso:()=>S0,normalizeWsFrame:()=>R4,normalizeWham:()=>A4,normalizeQuotaHeaders:()=>F4,isCompleteQuotaHeaderFrame:()=>I4});function S0($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let X=Z<100000000000?Z*1000:Z,J=new Date(X);return Number.isNaN(J.getTime())?void 0:J.toISOString()}let z=new Date($);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function u8($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function l1($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function d1($,Z){let z=$.get(Z);if(z===null||z.trim()==="")return;let X=Number(z);if(!Number.isFinite(X)||X<0||X>100)return;let J=Z.slice(0,-13),G=u8($.get(`${J}-window-minutes`)),Q=S0($.get(`${J}-reset-at`)??void 0);if(X===0&&$.get(`${J}-window-minutes`)==="0"&&!Q)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:Q,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}function n1($,Z){let z=$.get(Z);if(z===null)return"absent";if(z.trim()==="")return"invalid";let X=Number(z);return Number.isFinite(X)&&X>=0&&X<=100?"valid":"invalid"}function F4($){if(s1.some((J)=>n1($,J)==="invalid"))return{};let Z={},z=d1($,"x-codex-primary-used-percent");if(z)Z.primary=z;let X=d1($,"x-codex-secondary-used-percent");if(X)Z.secondary=X;return Z}function I4($){let Z=s1.map((z)=>n1($,z));return Z.includes("valid")&&!Z.includes("invalid")}function i1($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=u8($.window_minutes),z=S0($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z}:{}}}function R4($){let Z={},z=i1($.rate_limits?.primary);if(z)Z.primary=z;let X=i1($.rate_limits?.secondary);if(X)Z.secondary=X;return Z}function U0($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function c1($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=u8($.limit_window_seconds),z=S0($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z/60}:{}}}function A4($){let Z={},z=c1($.rate_limit?.primary_window);if(z)Z.primary=z;let X=c1($.rate_limit?.secondary_window);if(X)Z.secondary=X;let J=l1($.rate_limit_reset_credits?.available_count);if(J!==void 0)Z.resetCreditsAvailable=J;let G=l1($.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)Z.resetCreditsApplicable=G;let Q=$.spend_control?.individual_limit;if($.spend_control===null||Q===null)Z.spendControlCleared=!0;if(Q&&typeof $.spend_control?.reached==="boolean"){let W=U0(Q.limit),B=U0(Q.used),V=U0(Q.remaining),j=U0(Q.used_percent),q=U0(Q.remaining_percent);if(W!==void 0&&B!==void 0&&V!==void 0&&j!==void 0&&q!==void 0)Z.spendControl={limit:W,used:B,remaining:V,usedPercent:j,remainingPercent:q,resetsAt:S0(Q.reset_at),unit:Q.unit,source:Q.source,reached:$.spend_control.reached}}let Y=$.credits;if(Y&&typeof Y.has_credits==="boolean"&&typeof Y.unlimited==="boolean"&&typeof Y.overage_limit_reached==="boolean"){let W=U0(Y.balance);Z.credits={hasCredits:Y.has_credits,unlimited:Y.unlimited,overageLimitReached:Y.overage_limit_reached,...W!==void 0?{balance:W}:{}}}return Z}var s1;var l8=C3(()=>{s1=["x-codex-primary-used-percent","x-codex-secondary-used-percent"]});import{createAssistantMessageEventStream as X2}from"@earendil-works/pi-ai";import{streamSimple as J2}from"@earendil-works/pi-ai/compat";import{createHash as z5,randomUUID as c4}from"node:crypto";import{setTimeout as s4}from"node:timers/promises";import{randomUUID as b3}from"node:crypto";import{mkdir as S3,rename as k3,rm as w3,writeFile as f3}from"node:fs/promises";import{dirname as E3}from"node:path";async function x8($,Z){await S3(E3($),{recursive:!0});let z=`${$}.${b3()}.tmp`;await f3(z,`${JSON.stringify(Z,null,2)}
2
- `,{encoding:"utf8",mode:384});try{await k3(z,$)}catch(X){throw await w3(z,{force:!0}).catch(()=>{}),X}}var y3=60000,v3=900000,h3=300000;function C1($){return $ instanceof Error?$.message:String($)}function b1($){let Z=C1($),z=$?.status;if(typeof z==="number")return z===429||z>=500;if(!($ instanceof Error))return!1;let X=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function i0($){let z=($.previous?.retryCount??0)+1,X,J=$.error?.retryAfter;if(typeof J==="number"&&J>0)X=J*1000;else if(b1($.error))X=Math.min(v3,y3*2**Math.min(z-1,6));else X=h3;return{message:C1($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:z}}function F0($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function S1($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let z=Date.parse($);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{setTimeout as L4}from"node:timers/promises";import{appendFileSync as m3,chmodSync as g3,existsSync as R8,renameSync as k1,statSync as p3}from"node:fs";var A8={error:0,warn:1,info:2,debug:3,trace:4},u3=5242880,R0,F8,w1;function l3(){if(R0===void 0)return;return(typeof R0==="function"?R0():R0)||void 0}function d3(){if(w1)return w1;let $=typeof F8==="function"?F8():F8;if($&&$ in A8)return $;return"info"}var i3=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function c3($){if(i3.test($))return!0;let Z=$.toLowerCase().replace(/[-_]/g,"");if(Z==="chatgptaccountid")return!0;if(Z==="email"||Z==="orgname"||Z==="organizationname")return!0;if(Z.includes("apikey"))return!0;if(Z.endsWith("secret")||Z.endsWith("password"))return!0;if(Z.endsWith("token")&&!Z.endsWith("tokens"))return!0;return!1}var f1=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function s3($){return C8($,new WeakSet)}function n3($){return T8($,new WeakSet)}function T8($,Z){if(typeof $==="string")return $.replace(f1,"***REDACTED***");if(Array.isArray($)){if(Z.has($))return"[Circular]";Z.add($);let z=$.map((X)=>T8(X,Z));return Z.delete($),z}if($&&typeof $==="object"){if(Z.has($))return"[Circular]";Z.add($);let z={};for(let[X,J]of Object.entries($))z[X]=T8(J,Z);return Z.delete($),z}return $}function C8($,Z){if(typeof $==="string")return $.replace(f1,"***REDACTED***");if(Array.isArray($)){if(Z.has($))return"[Circular]";Z.add($);let z=$.map((X)=>C8(X,Z));return Z.delete($),z}if($&&typeof $==="object"){if(Z.has($))return"[Circular]";Z.add($);let z={};for(let[X,J]of Object.entries($))z[X]=c3(X)?"***REDACTED***":C8(J,Z);return Z.delete($),z}return $}var A0=[],I8,a3=3;function b8($){try{g3($,384)}catch{}}function t3($){try{if(!(R8($)&&p3($).size>u3))return;for(let z=a3-1;z>=1;z--)if(R8(`${$}.${z}`)){let X=`${$}.${z+1}`;k1(`${$}.${z}`,X),b8(X)}let Z=`${$}.1`;k1($,Z),b8(Z)}catch{}}function E1(){if(!A0.length)return;let $=l3(),Z=A0.join("");if(A0=[],!$)return;try{if(t3($),R8($))b8($);m3($,Z,{encoding:"utf8",mode:384})}catch{}}function o3(){if(!I8)I8=setTimeout(()=>{I8=void 0,E1()},500)}function r3($){try{return` ${JSON.stringify(s3($))}`}catch{return" [unserializable]"}}function I0($,Z,z,X){if(R0===void 0)return;if(A8[Z]>A8[d3()])return;let J=`[${new Date().toISOString()}] ${Z.toUpperCase()} [${$}] ${n3(z)}`+(X===void 0?"":r3(X))+`
3
- `;if(A0.push(J),A0.length>=50)E1();else o3()}function d($){return{error:(Z,z)=>I0($,"error",Z,z),warn:(Z,z)=>I0($,"warn",Z,z),info:(Z,z)=>I0($,"info",Z,z),debug:(Z,z)=>I0($,"debug",Z,z),trace:(Z,z)=>I0($,"trace",Z,z)}}import{createServer as e3}from"node:http";import{setTimeout as $4}from"node:timers/promises";var s0="app_EMoamEEZ73f0CkXaXp7hrann",V0="https://auth.openai.com",T0=1455,Z4=3000,z4="cortexkit-opencode-openai-auth";function y1($){return`${z4}/${$}`}var v1="main",X4=`"${v1}" is a reserved account id; choose a different label.`;function h1($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function J4(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=h1(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:z}}function k8($){if($.length>16384)return;let Z=$.split(".");if(Z.length!==3)return;let z=Z[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function w8($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let z=$["https://api.openai.com/auth"];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.chatgpt_account_id==="string"&&z.chatgpt_account_id.length>0)return z.chatgpt_account_id;let X=$.organizations;if(Array.isArray(X)){let J=X[0];if(J&&typeof J==="object"&&!Array.isArray(J)&&typeof J.id==="string"&&J.id.length>0)return J.id}return}function f8($){if($.id_token){let Z=k8($.id_token),z=Z&&w8(Z);if(z)return z}if($.access_token){let Z=k8($.access_token);return Z?w8(Z):void 0}return}function G4($){return typeof $==="string"&&$.toLowerCase()===v1}function S8($){if(G4($))throw Error(X4);return $}function Q4($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:s0,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:z,originator:"opencode"});return`${V0}/oauth/authorize?${X.toString()}`}async function Y4($,Z,z){let X=await fetch(`${V0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:s0,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function W4($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var B4=`<!doctype html>
1
+ import{createAssistantMessageEventStream as mB}from"@earendil-works/pi-ai";import{streamSimple as pB}from"@earendil-works/pi-ai/compat";var z0="all",m3=Object.freeze(["primary"]);function C4($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function m1($,Z){return JSON.stringify([$,Z])}function p3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function C0($){return typeof $==="number"&&Number.isFinite($)}function _4($){return typeof $==="string"&&$.length>0}function f0($,Z,X){return $[Z]===void 0||X($[Z])}function VX($){return C0($)&&$>0}function w3($){return typeof $==="string"}function jX($){if(!p3($)||!_4($.scope)||!_4($.label))return!1;switch($.kind){case"reading":return C0($.checkedAt)&&C0($.usedPercent)&&f0($,"resetsAt",w3)&&f0($,"windowMinutes",VX);case"retired":return C0($.retiredAt);case"absent":return C0($.checkedAt);default:return!1}}function UX($){if(!p3($)||!C0($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&f0($,"remainingPercent",C0)&&f0($,"usedPercent",C0)&&f0($,"resetsAt",w3)&&f0($,"limit",C0)&&f0($,"used",C0)&&f0($,"remaining",C0)&&f0($,"unit",w3)}function o($){if(!p3($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!jX(X))return!1;let J=m1(X.scope,X.label);if(Z.has(J))return!1;Z.add(J)}return f0($,"budget",UX)}class j6 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function q6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U6($){return typeof $==="number"&&Number.isFinite($)}function T4($){return $===void 0||typeof $==="string"&&$!==""}function A4($){return typeof $==="string"&&$!==""}function N$($,Z){return $[Z]===void 0||U6($[Z])}function u3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function qX($){return q6($)&&T4($.scope)&&A4($.label)&&U6($.usedPercent)&&u3($,"resetsAt")&&($.windowMinutes===void 0||U6($.windowMinutes)&&$.windowMinutes>0)}function KX($){return q6($)&&T4($.scope)&&A4($.label)}function DX($){if(!q6($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&N$($,"remainingPercent")&&N$($,"usedPercent")&&u3($,"resetsAt")&&N$($,"limit")&&N$($,"used")&&N$($,"remaining")&&u3($,"unit")}function R4($){if(!q6($)||!U6($.checkedAt))return!1;let Z=$.readings??[],X=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(X))return!1;let J=new Set;for(let z of Z){if(!qX(z))return!1;let G=m1(z.scope??z0,z.label);if(J.has(G))return!1;J.add(G)}if(!X.every(KX))return!1;return $.budget===void 0||DX($.budget)}function NX($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function MX($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function s0($,Z){if($!==void 0&&!o($))throw new j6("stored quota map is malformed");if(!R4(Z))throw new j6("quota observation is malformed");let X=$??{limits:[]},J=Z.checkedAt,z=new Map;for(let V of X.limits)z.set(m1(V.scope,V.label),V);let G=(V)=>{let j=z.get(V);return j===void 0||J>=C4(j)},Q=new Set;for(let V of Z.readings??[]){let j=V.scope??z0,q=m1(j,V.label);if(Q.add(q),!G(q))continue;z.set(q,{scope:j,label:V.label,kind:"reading",checkedAt:J,usedPercent:V.usedPercent,...V.resetsAt===void 0?{}:{resetsAt:V.resetsAt},...V.windowMinutes===void 0?{}:{windowMinutes:V.windowMinutes}})}for(let V of Z.coverage??[]){let j=V.scope??z0,q=m1(j,V.label);if(Q.has(q)||!G(q))continue;let U=z.get(q);z.set(q,U===void 0||U.kind==="absent"?{scope:j,label:V.label,kind:"absent",checkedAt:J}:{scope:j,label:V.label,kind:"retired",retiredAt:J})}let{limits:Y,budget:B,...H}=X,W=MX(X.budget,Z.budget,J);return{...H,limits:[...z.values()].sort(NX),...W===void 0?{}:{budget:W}}}var l3=Object.freeze({validate:o,merge:s0});var x4=900000,b4="no quota reading yet",E4="no limits reported";function k4($){let Z=Math.max(1,Math.round($/60000));if(Z<60)return`${Z}m`;let X=Math.round(Z/60);if(X<24)return`${X}h`;return`${Math.max(1,Math.round(Z/1440))}d`}function LX($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function K6($){if($.scope!==z0||$.windowMinutes===void 0)return $.label;return LX($.windowMinutes)}function S4($){return`${Math.round(Math.min(100,Math.max(0,$)))}% left`}function I4($,Z){if($===void 0)return"";let X=Date.parse($);if(!Number.isFinite(X)||X<=Z)return"";return`, resets ${k4(X-Z)}`}function FX($,Z){let X=$.windowMinutes,J=Z.windowMinutes;if(X!==void 0&&J!==void 0&&X!==J)return X-J;if(X===void 0!==(J===void 0))return X===void 0?1:-1;if($.scope!==Z.scope){if($.scope===z0)return-1;if(Z.scope===z0)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function p1($,Z){if(!$)return[];let{now:X}=Z,J=(Z.form??"full")==="full",z=[],G=[],Q=$.limits.filter((B)=>B.kind==="reading"&&B.remainingPercent!==void 0).sort(FX);for(let B of Q)G.push(B.checkedAt),z.push(`${K6(B)} ${S4(B.remainingPercent??0)}${J?I4(B.resetsAt,X):""}`);let Y=$.budget;if(Y){G.push(Y.checkedAt);let B=Y.reached?"credits spent":Y.remainingPercent!==void 0?`credits ${S4(Y.remainingPercent)}`:"credits available";z.push(`${B}${J?I4(Y.resetsAt,X):""}`)}if(G.length>0){let B=X-Math.min(...G);if(B>(Z.staleAfterMs??x4))z.push(`checked ${k4(B)} ago`)}return z}function T0($,Z){let X=p1($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?E4:b4}function PX($){if($.kind==="retired")return{scope:$.scope,label:$.label,kind:"retired",checkedAt:$.retiredAt};if($.kind==="absent")return{scope:$.scope,label:$.label,kind:"absent",checkedAt:$.checkedAt};return{scope:$.scope,label:$.label,kind:"reading",checkedAt:$.checkedAt,usedPercent:$.usedPercent,remainingPercent:100-$.usedPercent,...$.windowMinutes===void 0?{}:{windowMinutes:$.windowMinutes},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function OX($,Z){let X=$.windowMinutes!==void 0,J=Z.windowMinutes!==void 0;if(X!==J)return X?-1:1;if(X&&J&&$.windowMinutes!==Z.windowMinutes)return(Z.windowMinutes??0)-($.windowMinutes??0);if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function _X($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function c($,Z=z0){let X=new Map;for(let B of $?.limits??[]){if(B.scope!==Z&&B.scope!==z0)continue;let H=X.get(B.label);if(H===void 0){X.set(B.label,B);continue}let W=B.scope===z0?H:B,V=B.scope===z0?B:H;X.set(B.label,W.kind==="reading"?W:V)}let J=[...X.values()].map(PX).sort(OX),z=J.filter((B)=>B.kind==="reading"),G=z.length>0?z:J,Q=G.length>0?Math.min(...G.map((B)=>B.checkedAt)):void 0,Y=$?.budget?.kind==="reading"?_X($.budget):void 0;return{scope:Z,limits:J,...Q===void 0?{}:{checkedAt:Q},...Y===void 0?{}:{budget:Y}}}function M$($,Z){let X=$?.budget;if(X?.reached!==!0||typeof X.resetsAt!=="string")return;let J=Date.parse(X.resetsAt);if(!Number.isFinite(J)||J<=Z)return;return{resetsAt:X.resetsAt,resetAtMs:J}}function d3($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function D6($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}function f4($,Z,X){let J=Z.rateLimitMarks?.get($);if(J!==void 0&&X<J)return{id:$,reason:"rate-limited",until:J};let z=Z.refreshBackoff?.get($);if(z!==void 0&&X<z)return{id:$,reason:"refresh-backoff",until:z};return}function CX($,Z,X,J){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let G of X)if(!Z.limits.some((Q)=>Q.label===G))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:G},pullRequested:!0};let z=Z.limits.filter(d3);for(let G of z)if(D6(G,J)===void 0)return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of z){let Q=D6(G,J);if(Q!==void 0&&typeof G.resetsAt==="string")return{id:$,stage:1,gate:5,reason:"exhausted",window:{scope:G.scope,label:G.label},resetsAt:G.resetsAt,resetAtMs:Q}}return}function O1($){let Z=$.scope??z0,X=$.requiredLabels??m3,J=[],z=[],G=[];for(let j of $.rows){let q=f4(j.id,$,$.now);if(q){J.push(q);continue}if(j.kind==="api-key"){G.push({id:j.id,kind:j.kind});continue}let U=c(j.quota,Z),L=CX(j.id,U,X,$.now);if(L){z.push(L);continue}G.push({id:j.id,kind:j.kind,projection:U})}let Q=new Map(G.flatMap((j)=>{let q=M$(j.projection,$.now);return q?[[j.id,q]]:[]})),Y=Q.size>0&&Q.size===G.length,B=[];for(let j of G){let q=Q.get(j.id);if(q===void 0)B.push(j);else if(Y)B.push({...j,lastPath:!0});else z.push({id:j.id,stage:2,reason:"budget-spent",...q})}let H=new Map($.rows.map((j,q)=>[j.id,q])),W=(j,q)=>(H.get(j.id)??0)-(H.get(q.id)??0);z.sort(W);let V=z.filter((j)=>("pullRequested"in j)).map((j)=>j.id);for(let j of V)$.requestPull?.(j);return{admitted:B,refused:z,excluded:J,pulls:V}}var N6="main";function c3($){switch($){case"sticky-balanced":return{mode:"sticky-balanced",placement:"roster"};case"main-first":return{mode:"ordered",placement:"main-first"};case"fallback-first":return{mode:"ordered",placement:"fallback-first"};default:return{mode:"ordered",placement:"roster"}}}function u1($,Z,X=N6){if(Z==="roster"||!$.includes(X))return[...$];let J=$.filter((z)=>z!==X);return Z==="main-first"?[X,...J]:[...J,X]}function s3($){let Z=O1($),X=new Set(Z.admitted.map((z)=>z.id));return{order:u1($.rows.map((z)=>z.id),$.placement??"roster",$.formerMainId).filter((z)=>X.has(z)&&$.killswitch?.get(z)!==!1),admission:Z}}function i3($,Z,X){let J=Z.at(-1);if(J!==void 0){if(J.status===void 0||!X.includes(J.status))return}let z=new Set(Z.map((G)=>G.id));return $.find((G)=>!z.has(G))}function L$($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function a3($,Z,X){let J=new Map;for(let[z,G]of $){if(z===X)continue;if(G.quotaCheckedAt!==Z.get(G.accountId))continue;J.set(G.accountId,(J.get(G.accountId)??0)+(G.inputBytes??0))}return J}var o3=900000,v4=0.016666666666666666,n3=0.000001;function M6($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function g4($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function h4($){return $.limits.filter((Z)=>Z.kind==="reading").sort((Z,X)=>{let J=Z.windowMinutes!==void 0,z=X.windowMinutes!==void 0;if(J!==z)return J?-1:1;if(J&&z)return(X.windowMinutes??0)-(Z.windowMinutes??0);return 0})}function t3($){let Z=($.classifyStatus??g4)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=M6($.quota,$.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||$.now-X>o3)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let z of h4($.quota)){let G=z.remainingPercent;if(typeof G==="number"&&Number.isFinite(G)&&G<=0)return{action:"migrate",reason:"exhausted",window:{scope:z.scope,label:z.label},...typeof z.resetsAt==="string"?{resetsAt:z.resetsAt}:{}}}let J=M$($.quota,$.now);if(J)return{action:"migrate",reason:"exhausted",resetsAt:J.resetsAt};return{action:"retain",reason:Z}}function r3($,Z,X){let J=Math.max(0,$.remainingPercent-Z);if(J<=0)return 0;if(!$.resetsAt)return J;let z=Date.parse($.resetsAt);if(!Number.isFinite(z)||z<=X)return J;let G=Math.max((z-X)/3600000,v4);return J/G}function y4($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function TX($,Z){if(!$.quota)return;let X=M6($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>o3)return;let J=h4($.quota).map((Q)=>r3({remainingPercent:Q.remainingPercent??Number.NaN,...Q.resetsAt===void 0?{}:{resetsAt:Q.resetsAt}},$.reservePercent[Q.label]??0,Z)),z=$.quota.budget;if(z&&typeof z.remainingPercent==="number"&&Number.isFinite(z.remainingPercent))J.push(r3({remainingPercent:z.remainingPercent,...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}},0,Z));let G=J.length>0?Math.min(...J):0;return G>0?{candidate:$,quotaCheckedAt:X,weight:G}:void 0}function w4($){let Z=$.candidates.filter((z)=>z.killswitchPasses!==!1);if($.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(Z.length===0)return;let X=Z.map((z)=>TX(z,$.now)).filter((z)=>z!==void 0);if(X.length>0){X.sort((G,Q)=>{let Y=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,n3),B=(($.pendingBytes.get(Q.candidate.accountId)??0)+$.requestBytes)/Math.max(Q.weight,n3);return Y-B||G.candidate.configuredOrder-Q.candidate.configuredOrder||y4(G.candidate.accountId,Q.candidate.accountId)});let z=X[0];if(z)return{accountId:z.candidate.accountId,quotaCheckedAt:z.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let J=[...Z].sort((z,G)=>{let Q=(z.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-Q||z.configuredOrder-G.configuredOrder||y4(z.accountId,G.accountId)})[0];if(!J)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:J.accountId,quotaCheckedAt:M6(J.quota,J.quotaCheckedAt),source:"mode-fallback"}}function e3($){let Z=O1($),X=new Map(Z.admitted.map((U)=>[U.id,U])),J=new Map(Z.refused.map((U)=>[U.id,U])),z=new Set(Z.excluded.map((U)=>U.id)),G=new Set($.rows.map((U)=>U.id)),Q=$.pin!==void 0&&L$($.pin,G,$.identities?.get($.pin.accountId));if(Q&&$.pin){let U=X.get($.pin.accountId);if(U&&$.killswitch?.get(U.id)!==!1)return{outcome:"dispatch",accountId:U.id,source:"pin",...U.projection?.checkedAt===void 0?{}:{quotaCheckedAt:U.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let Y=$.pin?J.get($.pin.accountId):void 0,B=Q&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||Y?.reason==="exhausted"||Y?.reason==="budget-spent"),H=(U)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(U):$.rowReservePercent?.get(U.id))??$.reservePercent??{}},W=$.scope,V=$.rows.map((U,L)=>({row:U,configuredOrder:L})).filter(({row:U})=>!z.has(U.id)).map(({row:U,configuredOrder:L})=>{let N=$.killswitch?.get(U.id),K=$.resetCreditsApplicable?.get(U.id);return{accountId:U.id,quota:U.kind==="api-key"?void 0:X.get(U.id)?.projection??c(U.quota,W),reservePercent:H(U),configuredOrder:L,...K===void 0?{}:{resetCreditsApplicable:K},...N===void 0?{}:{killswitchPasses:N}}}),j=[],q=Q?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(V.length>0){let U=w4({candidates:V,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!U)break;let L=J.get(U.accountId);if(L){j.push(L),V=V.filter((K)=>K.accountId!==U.accountId);continue}let N=$.identities?.get(U.accountId);return{outcome:"dispatch",accountId:U.accountId,source:U.source,...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt},pin:Q&&!B?{action:"retain"}:{action:"assign",pin:{accountId:U.accountId,inputBytes:$.requestBytes,...N===void 0?{}:{wireIdentity:N},...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt}}},refusedSelections:j,admission:Z}}return{outcome:"no-admissible-account",pin:q,refusedSelections:j,admission:Z}}import{appendFileSync as bX,chmodSync as EX,existsSync as $8,renameSync as p4,statSync as kX}from"node:fs";var AX=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,RX=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function SX($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function y0($={}){let Z=[RX,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function X(G){let Q=G.toLowerCase().replace(/[-_]/g,"");return AX.test(G)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function J(G){let Q=G,Y=[["name",G.name],["message",G.message],["stack",G.stack]];for(let H of["code","status","cause"])if(Q[H]!==void 0)Y.push([H,Q[H]]);let B=new Set(Y.map(([H])=>H));for(let H of Object.entries(G))if(!B.has(H[0]))Y.push(H);return Y}function z(G,Q,Y,B=0){if(typeof G==="string")return Z.reduce((H,W)=>H.replace(W,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(Y.has(G))return"[Circular]";Y.add(G);try{if(Array.isArray(G))return G.map((V)=>z(V,Q,Y,B));let H=SX(G);if(H&&B>=8)return"[Truncated]";let W=H?B+1:B;return Object.fromEntries((H?J(G):Object.entries(G)).map(([V,j])=>[V,Q&&X(V)?"***REDACTED***":z(j,Q,Y,W)]))}finally{Y.delete(G)}}return{redact:(G)=>z(G,!0,new WeakSet),redactStrings:(G)=>z(G,!1,new WeakSet)}}var m4=y0(),IX=m4.redact,xX=m4.redactStrings;var L6={error:0,warn:1,info:2,debug:3,trace:4},fX=5242880,yX=3;function Z8($){try{EX($,384)}catch{}}function vX($){try{if(!($8($)&&kX($).size>=fX))return;for(let X=yX-1;X>=1;X--)if($8(`${$}.${X}`)){let J=`${$}.${X+1}`;p4(`${$}.${X}`,J),Z8(J)}let Z=`${$}.1`;p4($,Z),Z8(Z)}catch{}}function gX($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function hX($){let Z,X,J,z=y0(),G,Q=[],Y;function B(K){Z=K.file,X=K.level,z=y0(K),G=K.captureSink}function H(K){if(K===void 0||K in L6)J=K}function W(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function V(){if(J)return J;let K=typeof X==="function"?X():X;if(K&&K in L6)return K;return"info"}function j(){if(Y)clearTimeout(Y),Y=void 0;if(!Q.length)return;let K;try{K=W()}catch{Q=[];return}let F=Q.join("");if(Q=[],!K)return;try{if(vX(K),$8(K))Z8(K);bX(K,F,{encoding:"utf8",mode:384})}catch{}}function q(){if(!Y)Y=setTimeout(()=>{Y=void 0,j()},500)}function U(K,F,C,M){if(Z===void 0&&G===void 0)return;try{if(L6[F]>L6[V()])return;let D=z.redactStrings(C),P;try{P=z.redact(M)}catch{P="[unserializable]"}let S=`[${new Date().toISOString()}] ${F.toUpperCase()} [${K}] ${D}`+(M===void 0?"":gX(P))+`
2
+ `;try{G?.({channel:K,level:F,message:D,data:P})}catch{}if(Z===void 0)return;if(Q.push(S),Q.length>=50)j();else q()}catch{}}function L(K){return{error:(F,C)=>U(K,"error",F,C),warn:(F,C)=>U(K,"warn",F,C),info:(F,C)=>U(K,"info",F,C),debug:(F,C)=>U(K,"debug",F,C),trace:(F,C)=>U(K,"trace",F,C)}}function N(){if(Q=[],Y)clearTimeout(Y),Y=void 0;Z=void 0,X=void 0,J=void 0,z=y0(),G=void 0}if($)B($);return{configure:B,createLogger:L,setLogLevel:H,flushLogs:j,reset:N}}var wX=hX();function s($){return wX.createLogger($)}class E 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 F6 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 l1="identity-contradicted: ",X8="duplicate-identity";function J1($,Z,X){let J=$.rosterRow(Z);if(!J)return;J.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:X})}function F$($,Z){let X=$.rosterRow(Z);if(!X)return;X.enabled=!0;let J=$.entry(Z);if(J&&"disabledReason"in J){let z={...J};delete z.disabledReason,$.setEntry(Z,z)}}function d1($,Z){let X=$.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===Z),J=[];for(let z of X.slice(1))J1($,z.id,"duplicate-identity"),J.push(z.id);return J}function _1($,Z,X){let J=$.rosterRow(Z);if(!J)return[];return J.accountId=X,d1($,X)}import{readFile as DJ}from"node:fs/promises";import{setTimeout as NJ}from"node:timers/promises";import{randomUUID as cX}from"node:crypto";import{mkdir as sX,open as P6,rename as iX,rm as aX}from"node:fs/promises";import{dirname as J8}from"node:path";class P$ extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function P0($,Z,X={}){await z8($,Z,X)}async function z8($,Z,X,J){await sX(J8($),{recursive:!0});let z=`${$}.${(X.stageName??cX)()}.tmp`,G,Q=!1;try{if(G=await P6(z,"wx",384),Q=!0,await G.writeFile(X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
3
+ `,"utf8"),await G.chmod(384),X.durable)try{await G.sync()}catch(Y){throw new P$(Y)}if(await G.close(),G=void 0,await X.beforeRename?.(),await iX(z,$),Q=!1,J?.(),X.durable){let Y=await P6(J8($),"r");try{await Y.sync()}catch(B){throw new P$(B)}finally{await Y.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await aX(z,{force:!0}).catch(()=>{})}}async function G8($){let Z=await P6($,"r");try{await Z.sync()}finally{await Z.close()}let X=await P6(J8($),"r");try{await X.sync()}finally{await X.close()}}import{randomUUID as O6}from"node:crypto";import{mkdir as u4,open as nX,readFile as Q8,rename as l4,rm as c1,stat as d4,writeFile as Y8}from"node:fs/promises";import{dirname as rX,join as c4}from"node:path";var oX=globalThis.setTimeout.bind(globalThis),tX=globalThis.clearTimeout.bind(globalThis);function B8($){let Z=$?.code;return Z==="ENOENT"||Z==="EINVAL"||Z==="ENOTDIR"}async function t($){let Z=W8($.path,$.name),X=c4(Z,"owner.json"),J=O6(),z=$.now??Date.now,G=null,Q=!1,Y,B,H=new Promise((A)=>{B=A});function W(A){try{let x=$.onRenewalTimer?.(A);if(x&&(typeof x==="object"||typeof x==="function")&&"then"in x&&typeof x.then==="function")Promise.resolve(x).catch(()=>{})}catch{}}function V(){if(!G)return;tX(G),G=null,W("cancelled")}function j(A,x){if(Y||Q)return;Y=Object.freeze({reason:A,expectedOwnerId:J,...typeof x?.ownerId==="string"?{observedOwnerId:x.ownerId}:{},...typeof x?.expiresAt==="number"?{observedExpiresAt:x.expiresAt}:{}}),V(),B(Y)}let q=null,U=`${Z}.evicting`,L=c4(U,"owner.json"),N=O6(),K=5000,F=8;async function C(){try{return JSON.parse(await Q8(Z,"utf8"))}catch(A){if(A.code!=="EISDIR")throw A;return JSON.parse(await Q8(X,"utf8"))}}async function M(){let A=`${Z}.${O6()}.tmp`,x,I=!1;try{x=await nX(A,"wx",384),I=!0,await x.writeFile(`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
4
+ `,"utf8"),await x.chmod(384),await x.close(),x=void 0,await l4(A,Z),I=!1}finally{if(await x?.close().catch(()=>{}),I)await c1(A,{force:!0}).catch(()=>{})}}async function D(){try{return await Y8(Z,`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
5
+ `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(A){let x=A.code;if(x==="EEXIST"||x==="EISDIR")return!1;if(x==="ENOENT"){await u4(rX(Z),{recursive:!0});try{return await Y8(Z,`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
6
+ `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(I){let J0=I.code;if(J0==="EEXIST"||J0==="EISDIR")return!1;throw I}}throw A}}async function P(){await new Promise((A)=>setTimeout(A,Math.floor(Math.random()*4)))}async function S(){try{let A=await C();return Number(A?.expiresAt)>z()}catch{try{return(await d4(Z)).mtimeMs+$.ttlMs>z()}catch{return!1}}}async function f(){try{return JSON.parse(await Q8(L,"utf8"))?.ownerId===N}catch{return!1}}async function n(){if(await f())await c1(U,{recursive:!0,force:!0}).catch(()=>{})}async function _0(){await u4(U);try{await Y8(L,`${JSON.stringify({ownerId:N,createdAt:z()})}
7
+ `,{encoding:"utf8",mode:384,flag:"wx"})}catch(A){if(B8(A))return!1;throw await n(),A}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function h(){let A;try{A=await d4(U)}catch(I){if(I.code==="ENOENT")return"missing";throw I}if(A.mtimeMs+K>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let x=`${U}.${O6()}`;try{await l4(U,x)}catch(I){if(I.code==="ENOENT")return"missing";throw I}if($.onStep)await $.onStep("stale-marker-claimed");return await c1(x,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function g(A){try{if(!await _0())return!1}catch(x){if(x.code==="EEXIST")return!1;throw x}try{await A()}finally{await n()}return!0}async function l(){for(let A=0;A<F;A++){if($.onStep)await $.onStep("relinquish-read");let x;try{x=await C()}catch{return}if(x?.ownerId!==J)return;try{await c1(Z,{recursive:!0,force:!0});return}catch{await P()}}}function X0(){if(!$.renew||Q||Y)return;let A=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=oX(()=>{G=null;let x=(async()=>{let I=!Q;try{if(!await g(async()=>{let V6=await C(),HX=z();if(Q||Y){I=!1;return}if(V6?.ownerId!==J){j("taken-over",V6),I=!1;return}if(!(Number(V6?.expiresAt)>HX)){j("expired",V6),I=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||Y){I=!1;return}if(!await f())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||Y){I=!1;return}if(!await f())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||Y){I=!1;return}if(await M(),!await f()){j("marker-lost"),I=!1,await l();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch{try{let J0=await C();if(J0?.ownerId!==J)j("taken-over",J0);else if(!(Number(J0?.expiresAt)>z()))j("expired",J0)}catch{j("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(I&&!Q&&!Y)X0()}})();q=x,x.finally(()=>{if(q===x)q=null})},A),"unref"in G)G.unref();W("scheduled")}function d(){try{let A=$.onContended?.();if(A&&(typeof A==="object"||typeof A==="function")&&"then"in A&&typeof A.then==="function")Promise.resolve(A).catch(()=>{})}catch{}return null}let c0=await D();if(!c0)for(let A=0;A<F;A++){if(c0=await D(),c0)break;if(await S())return d();if($.onStep)await $.onStep("stale-lock-observed");try{if(!await _0()){await P();continue}}catch(x){if(x.code!=="EEXIST")throw x;if(await h()==="fresh")return null;await P();continue}try{if(await S())return d();if(!await f())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await f())return null;if(await c1(Z,{recursive:!0,force:!0}).catch(()=>{}),!await f())return null;if($.onStep)await $.onStep("stale-lock-removed");if(c0=await D(),!c0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await f())return await l(),c0=!1,null;break}finally{await n()}}if(!c0)return null;return X0(),{ownerId:J,whenLost:()=>H,hasLost:()=>Y!==void 0,assertOwned:async()=>{let A;try{let x=await C();if(A=x,!Q&&!Y&&x?.ownerId===J&&Number(x?.expiresAt)>z())return;j(x?.ownerId!==J?"taken-over":"expired",x)}catch{j("unreadable")}throw new s1({target:$.path,name:$.name,expectedOwnerId:J,...typeof A?.ownerId==="string"?{observedOwnerId:A.ownerId}:{},...typeof A?.expiresAt==="number"?{observedExpiresAt:A.expiresAt}:{}})},release:async()=>{Q=!0,V(),await q;for(let A=0;A<F;A++){try{if(await g(async()=>{if((await C())?.ownerId!==J)return;if($.onStep)await $.onStep("release-owner-confirmed");if(!await f())return;await c1(Z,{recursive:!0,force:!0}).catch(()=>{})}))return;await h()}catch{return}await P()}}}}function W8($,Z){return`${$}.${Z}.lock`}class C1 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class s1 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function H8($,Z,X){let J=performance.now();for(;;){let z=await t({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1});if(z)try{return await X(z)}finally{await z.release()}let G=Z.timeoutMs-(performance.now()-J);if(G<=0)throw new C1({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(G))))}}import{AsyncLocalStorage as eX}from"node:async_hooks";var s4=new eX;function G0($){if(s4.getStore()!==void 0)throw new F6($)}function v0($,Z){return s4.run($,async()=>await Z())}async function i4($,Z,X,J,z){if(!Z)return;try{await v0($,()=>Z(X,J))}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:X,error:G instanceof Error?G.message:String(G)})}}var V8=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function $J($,Z,X){let J=(Q)=>{try{let Y=X.onLockEvent?.({type:Q,name:$.name,path:$.path});if(Y&&(typeof Y==="object"||typeof Y==="function")&&"then"in Y&&typeof Y.then==="function")Promise.resolve(Y).catch(()=>{})}catch{}},z={...Z,...ZJ($)},G=performance.now();for(;;){let Q=await t({name:$.name,path:$.path,ttlMs:z.ttlMs,now:X.now,renew:z.renew,onContended:()=>J("contended"),...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...X.onLockStep?{onStep:(H)=>X.onLockStep?.({name:$.name,path:$.path},H)}:{}});if(Q){J("acquired");let H={name:$.name,path:$.path,assertOwned:()=>Q.assertOwned(),release:async()=>{await Q.release(),J("released")}};try{await H.assertOwned()}catch(W){throw await H.release(),W}return H}let Y=z.timeoutMs-(performance.now()-G);if(Y<=0)throw new C1({target:$.path,name:$.name,timeoutMs:z.timeoutMs});let B=Math.floor(Math.random()*(z.retryMs+1));await new Promise((H)=>setTimeout(H,Math.min(z.retryMs+B,Y)))}}function ZJ($){let Z={};if($.ttlMs!==void 0)Z.ttlMs=$.ttlMs;if($.timeoutMs!==void 0)Z.timeoutMs=$.timeoutMs;if($.retryMs!==void 0)Z.retryMs=$.retryMs;if($.renew!==void 0)Z.renew=$.renew;if($.renewIntervalMs!==void 0)Z.renewIntervalMs=$.renewIntervalMs;return Z}class z1{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await $J($,this.defaults,this.env);return this.held.push(Z),await this.assertAll(),Z}async assertAll(){for(let $ of this.held)await $.assertOwned()}async releaseTo($){while(this.held.length>$)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}function T1($,Z,X){if(X!==void 0)throw new E({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 O$}from"node:crypto";var w="commonAuthPool",G1=1,A0="rows",_6="retiredEpochs",_$=1,j8=300000,v=w;function XJ($){let Z=JSON.parse(JSON.stringify($)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(_(J))return`{${Object.keys(J).sort().map((z)=>`${JSON.stringify(z)}:${X(J[z])}`).join(",")}}`;return JSON.stringify(J)};return X(Z)}function A1($){return O$("sha256").update(XJ($)).digest("hex")}function a4($){if(!_($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function JJ($){if(!_($)||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 W0="commonAuthProviderState";function _($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var zJ=new Set(["__proto__","constructor","prototype"]);function i1($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(zJ.has($))return"id is a reserved object key";return}function U8($){let Z=typeof $==="string"?$.trim():"";if(!Z)return!1;try{let X=new URL(Z);return(X.protocol==="http:"||X.protocol==="https:")&&!X.username&&!X.password}catch{return!1}}function n4($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function Q1($){return O$("sha256").update(n4($)).digest("hex")}function g0($){return O$("sha256").update(`credential-stamp\x00${n4($)}`).digest("hex")}function i0($){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 O$("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function q8($,Z,X,J={}){return{credentialEpoch:Z,digest:g0($),dispatch:i0($),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function a1($,Z){let X=$?.credentialBound?$.credentialBound(Z):Z;return O$("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function C$($,Z,X,J){if(!Z||X===void 0)return;if(!_($)||!Object.hasOwn($,W0))return;let z=D0($[v]);if(!z||z.providerState===void 0||z.digest!==g0(Z)||z.credentialEpoch!==X||z.binding?.identity!==J)return;return z.providerState}function e($){return Number.isSafeInteger($)&&$>=1}function D0($){if(!_($))return;let Z=$.credentialEpoch;if(!e(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 X="staged"in $?JJ($.staged):void 0;if("staged"in $&&!X)return;let J={...X?{staged:X}:{},...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(!_(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!U8(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...J,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 GJ($,Z,X){if($.identity!==X)return!1;if($.baseURL!==void 0&&(Z.type!=="api"||Z.baseURL!==$.baseURL))return!1;if($.authHeader!==void 0&&(Z.type!=="api"||Z.authHeader!==$.authHeader))return!1;return!0}function QJ($,Z,X,J){if(!$)return"none";if(!_(J)||!Object.hasOwn(J,v))return"missing";let z=D0(J[v]);if(!z)return"malformed";if(z.digest!==g0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!GJ(z.binding,$,X))return"mismatched";if(z.dispatch!==i0($))return"mismatched";return"bound"}function r4($){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(!_(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(!(w in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let X=Z[w];if(!_(X))return{status:"error",reason:`${w} is not an object`};let J=X.schemaVersion;if(typeof J!=="number"||!Number.isInteger(J)||J<1)return{status:"error",reason:`${w}.schemaVersion is invalid`};if(J>G1)return{status:"error",reason:`${w}.schemaVersion ${J} is newer than ${G1}`};if(A0 in X&&!_(X[A0]))return{status:"error",reason:`${w}.${A0} is not an object`};return{status:"ready",exists:!0,config:Z}}function o4($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!_($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!_($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function n1($){return Array.isArray($.accounts)?$.accounts:[]}function t4($){let Z=$[w];if(!_(Z))return{};let X=Z[A0];return _(X)?X:{}}function YJ($){return _($.accounts)?$.accounts:{}}function BJ($){if(!_($))return"not an object";let Z=i1($.id);if(Z)return Z;if($.type==="api")return U8($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function WJ($,Z){if(!_($))return;let X=$.credentialEpoch;if(!e(X))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;if("quota"in $&&!Z.validate($.quota))return;if("staged"in $&&!a4($.staged))return;return{credentialEpoch:X,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:$.quota}:{}}}function HJ($,Z){if(!_(Z))return;if($.type==="api"){let J=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!J)return;return{type:"api",apiKey:J,baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if($.corrupt===!0)return;let X=Z.refresh;if(typeof X!=="string"||!X.trim())return;return{type:"oauth",refresh:X,...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.lastRefreshedAt==="number"?{lastRefreshedAt:Z.lastRefreshedAt}:{}}}function C6($,Z){return n1($).find((X)=>_(X)&&X.id===Z)}function e4($){if(!_($[w]))$[w]={};return $[w]}function K8($){let Z=e4($);if(!_(Z[A0]))Z[A0]={};return Z[A0]}function Y1($,Z){let X=t4($),J=Object.hasOwn(X,Z)?X[Z]:void 0;return _(J)?J:void 0}function T6($,Z,X){Object.defineProperty(K8($),Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function $9($,Z){let X=$[w];if(!_(X))return;let J=X[_6];if(!_(J)||!Object.hasOwn(J,Z))return;let z=J[Z];return e(z)?z:void 0}function Z9($,Z){let X=Y1($,Z)?.credentialEpoch;return e(X)?X:void 0}function A6($,Z){return Math.max($9($,Z)??0,Z9($,Z)??0)+1}function X9($,Z){let X=[...Z];if(X.length===0)return;let J=e4($),z=_(J[_6])?J[_6]:{},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(e(B))Q(Y,B);for(let Y of X)Q(Y,Math.max($9($,Y)??0,Z9($,Y)??1));J[_6]=G}function B1($,Z,X,J){let z=t4($),G=YJ(Z),Q=new Set,Y=[];for(let B of n1($)){let H=BJ(B),W=_(B)&&typeof B.id==="string"?B.id:void 0,V=W===void 0?void 0:z[W],j=_(V)&&Object.hasOwn(V,"staged"),q=j?a4(V.staged):void 0;if(H||!_(B)||W===void 0||Q.has(W)){if(W!==void 0&&!Q.has(W))Q.add(W);if(W!==void 0)Y.push({id:W,type:_(B)&&B.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,W),candidate:!1,invalid:"roster",stamp:"none",...q?{staged:q}:{}});continue}Q.add(W);let U=B.type==="api"?"api":"oauth",L=Object.hasOwn(z,W),N=L?WJ(z[W],X):void 0,K=HJ(B,G[W]),F=B.enabled!==!1,C=N?N.credentialEpoch:L?void 0:1,M=typeof B.accountId==="string"&&B.accountId?B.accountId:void 0,D={id:W,type:U,enabled:F,needsFirstReading:N?N.needsFirstReading:U==="oauth",hasEntry:L,candidate:!1,...typeof B.label==="string"?{label:B.label}:{},...typeof B.addedAt==="number"?{addedAt:B.addedAt}:{},...M!==void 0?{identity:M}:{},...K?{credential:K,fingerprint:Q1(K)}:{},...N?{credentialEpoch:N.credentialEpoch}:{},...q?{staged:q}:{},...N?.disabledReason!==void 0?{disabledReason:N.disabledReason}:{},...N&&"quota"in N?{quota:N.quota}:{},...VJ(G[W],K,C,M,J),stamp:QJ(K,C,M,G[W])};if(L&&!N)D.invalid="entry";else D.candidate=F&&K!==void 0&&!j;Y.push(D)}return Y}function VJ($,Z,X,J,z){if(!_($)||!Object.hasOwn($,W0))return{};let G=C$($,Z,X,J);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=$[W0];if(!z?.validate(Q))return{providerStateDropped:"invalid"};if(a1(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function p($){return $.identity??$.id}function T$($,Z){if($===void 0||$>Z+j8)return Z;return Math.max(Z,$+1)}function D8($,Z){return T$($,Z)>Z+j8}function r1($){let{id:Z,credential:X,identity:J,label:z,addedAt:G}=$;return{id:Z,...z!==void 0?{label:z}:{},type:X.type,addedAt:G,...J!==void 0?{accountId:J}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}}}function J9($,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 z9($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function G9($,Z={}){if(!_($))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)&&!U8($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var R6="transition",Q9="transitionMark";function jJ($){if(!_($))return;let Z=$[R6];if(!_(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 A$($,Z,X){if(X.enabled)F$($,Z);else J1($,Z,X.reason??"");if(!$.rosterRow(Z))return;let J=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...J,[Q9]:X.mark}),!X.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)d1($,z.identity)}function UJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function qJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function KJ($,Z,X,J={}){let z=_(Z.accounts)?Z.accounts:{},G=new Map;for(let Q of B1($,Z,X)){if(Q.invalid||Q.staged||!Q.credential)continue;let Y=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!_(Y))continue;let B=D0(Y[v]);if(!B?.binding)continue;if(B.digest!==g0(Q.credential))continue;let H=Q.credentialEpoch??1;if(B.credentialEpoch>H){if(!qJ(B))continue;if(J.requireCredentialStamps){if(B.dispatch===void 0)continue;if(B.dispatch!==i0(UJ(Q.credential,B.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...B,binding:B.binding}})}else if(B.credentialEpoch===H&&B.dispatch!==void 0&&B.dispatch===i0(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===H&&B.binding.identity===Q.identity){if(J.requireCredentialStamps&&B.dispatch!==i0(Q.credential))continue;let W=jJ(Y[v]);if(W&&Y1($,Q.id)?.[Q9]!==W.mark)G.set(Q.id,{kind:"transition",transition:W})}}return G}function N8($,Z,X,J){let G={...$.entry(Z)??{},credentialEpoch:X,needsFirstReading:!0};if(delete G.quota,J.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(l1))delete G.disabledReason;$.setEntry(Z,G);let Q=$.rosterRow(Z);if(!Q)return;if(J.identity!==void 0)Q.accountId=J.identity;else delete Q.accountId;if(J.baseURL!==void 0)Q.baseURL=J.baseURL;if(J.authHeader!==void 0)Q.authHeader=J.authHeader}function M8($,Z,X,J={}){let z=KJ($,Z,X,J);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),Q={rows:()=>B1(G,Z,X),rosterRow:(Y)=>C6(G,Y),entry:(Y)=>Y1(G,Y),setEntry:(Y,B)=>T6(G,Y,B)};for(let[Y,B]of z)if(B.kind==="replace")N8(Q,Y,B.stamp.credentialEpoch,B.stamp.binding);for(let[Y,B]of z)if(B.kind==="identity")_1(Q,Y,B.identity);else if(B.kind==="transition")A$(Q,Y,B.transition);else if(B.stamp.binding.identity!==void 0)d1(Q,B.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function L8($,Z,X,J={}){let{config:z,torn:G}=M8($,Z,X,J),Q=B1(z,Z,X,J.providerState);for(let Y of Q){if(G.includes(Y.id))Y.torn=!0,Y.candidate=!1;if(J.requireCredentialStamps&&Y.stamp!=="bound")Y.unbound=!0,Y.candidate=!1}return Q}async function F8($){try{return await DJ($,"utf8")}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function Y9($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function H0($){for(let Z=0;Z<3;Z++){let X=await F8($.configPath),J=await F8($.statePath),z=await F8($.configPath);if(X!==z){if(Z<2)await NJ(2+Math.floor(Math.random()*4));continue}let G=r4(Y9(X));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=o4(Y9(J));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:L8(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 R0($,Z,X,J="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new E({operation:Z,...X!==void 0?{rowId:X}:{},phase:J,kind:"snapshot-contended",retryable:!0,message:$.reason});return new E({operation:Z,...X!==void 0?{rowId:X}:{},phase:J,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 B9{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,X,J,z){this.ctx=$,this.snapshot=Z,this.locks=X,this.progress=J,this.info=z,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return L8(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 X=this.entry($);return X&&Object.hasOwn(X,"staged")?X.staged:void 0}let Z=this.stateAccount($)?.[v];return _(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){T1(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),C6(this.config,$)}dropRosterRows($){let Z=this.roster(),X=Z.filter((J)=>!(_(J)&&J.id===$));return this.config.accounts=X,Z.length-X.length}entries(){return K8(this.config)}entry($){return this.entries(),Y1(this.config,$)}setEntry($,Z){T6(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=M8(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=_(this.state.accounts)?this.state.accounts:{},X=Object.hasOwn(Z,$)?Z[$]:void 0;return _(X)?X:void 0}dropStateAccount($){if(_(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!_(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(),X=new Set;for(let B of Z)if(_(B)&&typeof B.id==="string")X.add(B.id);let J=new Set;for(let B of n1(this.snapshot.config))if(_(B)&&typeof B.id==="string"&&!X.has(B.id))J.add(B.id);for(let B of Object.keys(this.entries()))if(!X.has(B))J.add(B);X9(this.config,J);let z=this.entries(),G={};for(let[B,H]of Object.entries(z))if(X.has(B))Object.defineProperty(G,B,{value:H,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[w],Y={...this.config,version:_$,accounts:Z,[w]:{...Q,schemaVersion:G1,[A0]:G}};await this.write(this.ctx.configPath,Y,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let B of J)this.ctx.removedIds.add(B);this.config=Y}),this.config=Y}async commitState($,Z={}){let X={...this.state,version:_$,accounts:_(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,X,"state",!0,Z.durable??!1),this.state=X,$)this.progress.committed=$}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await G8(this.ctx.statePath)}catch($){throw new E({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 G8(this.ctx.configPath)}async write($,Z,X,J=!0,z=!1,G){await z8($,Z,{durable:z,beforeRename:async()=>{await this.ctx.onStep?.(`before-${X}-write`,this.info),await this.locks.assertAll()}},()=>{if(J)this.progress.writes++;G?.()}),await this.ctx.onStep?.(`after-${X}-write`,this.info)}}async function W9($,Z){let X=new z1($.lockDefaults,$.lockEnv),J={writes:0};try{for(let Y of $.storeLocks)await X.acquire(Y);let z=await H0($);if(z.status==="error")throw R0(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=_$,G[w]={schemaVersion:G1,[A0]:{}};let Q={operation:"initialize",rowId:void 0};return await P0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",Q),await X.assertAll()}}),J.writes++,await $.onStep?.("after-config-write",Q),"initialized"}catch(z){throw o1(z,"initialize",void 0,J)}finally{await X.releaseAll()}}async function i($,Z,X,J,z,G={}){let Q=Z.held.length;try{for(let H of $.storeLocks)await Z.acquire(H);let Y=await H0($);if(Y.status!=="ready")throw R0(Y,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let B=new B9($,Y,Z,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))B.assertNotStaged(J.rowId);if(G.completeTorn??!0)await B.completeTorn();return await z(B)}finally{await Z.releaseTo(Q)}}function o1($,Z,X,J){let z=Z==="pull"?"pull":J.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?J.committed:void 0;if(Z==="publishRoster"&&J.publicationDecided)return new E({operation:Z,...X!==void 0?{rowId:X}:{},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 P$)return new E({operation:Z,...X!==void 0?{rowId:X}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof E){if($.phase===z&&$.rowId===X&&$.operation===Z&&$.committed===G)return $;return new E({operation:Z,...X!==void 0?{rowId:X}:{},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,...X!==void 0?{rowId:X}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof s1)return new E({...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 C1)return new E({...Q,retryable:!0,kind:"lock-contention",message:$.message});return new E({...Q,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function Q0($,Z,X,J,z){let G=new z1($.lockDefaults,$.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(Y){let B=o1(Y,Z,X,Q);if(B.kind!=="after-persist-hook")await i4(Z,J,X,B,$.logger);throw B}finally{await G.releaseAll()}}function M0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(p(Z))}`,path:$.ctx.statePath}}async function a0($,Z,X){let J=await H0($.ctx);if(J.status!=="ready")throw R0(J,Z,X);let z=J.rows.find((H)=>H.id===X),G=Y1(J.config,X),Q=J.state.accounts,Y=_(Q)&&Object.hasOwn(Q,X)?Q[X]:void 0,B=_(Y)?Y[v]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))T1(Z,X,G.staged);if(!z&&_(B)&&Object.hasOwn(B,"staged"))T1(Z,X,B.staged);if(!z)throw S0(Z,X);return{result:J,row:z}}function S0($,Z){return new E({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function V0($,Z){if(Z.unbound)throw O($,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 O($,Z,X,J,z=!1){return new E({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:X,message:J})}async function S6($,Z,X,J){let{ctx:z}=$,G=new z1(z.lockDefaults,z.lockEnv),Q={writes:0};try{if(!e(X?.credentialEpoch))throw O("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await i(z,G,Q,{operation:"pull",rowId:Z},async(Y)=>{Y.assertNotStaged(Z);let B=Y.row(Z);if(!B)throw S0("pull",Z);if(B.invalid)throw O("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!B.credential)throw O("pull",Z,"no-credential",`row ${Z} holds no credential`);V0("pull",B);let H=Y.entry(Z);if(B.torn||!H||H.credentialEpoch!==X.credentialEpoch||B.identity!==X.identity)throw new E({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${Z} was issued for a credential the row no longer holds`});let W=z.codec.merge(H.quota,J);if(!z.codec.validate(W))throw O("pull",Z,"invalid-quota","the quota codec rejected the merged map");Y.setEntry(Z,{...H,quota:W,needsFirstReading:!1}),await Y.commitConfig()},{completeTorn:!1})}catch(Y){throw o1(Y,"pull",Z,Q)}finally{await G.releaseAll()}}function n0($,Z,X,J,z="the provider state"){if(!$)throw O(Z,X,"invalid-input","the store was opened without a provider-state codec");let G;try{let Q=JSON.stringify(J);G=Q===void 0?void 0:JSON.parse(Q)}catch{G=void 0}if(G===void 0)throw O(Z,X,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!$.validate(G))throw O(Z,X,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function R$($,Z,X,J,z){if(J===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:n0($,Z,X,$.merge(structuredClone(J),structuredClone(z)),"the merged provider state")}}function H9($,Z,X,J,z){let G=$?.onReplace,Q=G?G(Z.providerState===void 0?void 0:structuredClone(Z.providerState),{id:Z.id,credentialEpoch:X,...Z.identity!==void 0?{previousIdentity:Z.identity}:{},...J!==void 0?{identity:J}:{},...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:n0($,"replace",Z.id,Q,"the provider state onReplace returned")}}function V9($,Z,X,J,z){if(Z.kind==="set")return a1($,Z.value);if(Z.kind==="clear")return;return C$(X,J?.credential,z,J?.identity)}async function j9($,Z,X,J,z={}){G0("updateProviderState");let{ctx:G}=$,Q="updateProviderState";return Q0(G,Q,Z,z.onFailure,async(Y,B)=>{let H=G.providerState;if(!H)throw O(Q,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw O(Q,Z,"invalid-input","a mutator is required");let W=_(X)?X.credentialEpoch:void 0;if(!e(W))throw O(Q,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await a0($,Q,Z);await Y.acquire(M0($,V));for(let j of z.extraLocks??[])await Y.acquire(j);return i(G,Y,B,{operation:Q,rowId:Z},async(j)=>{let q=j.row(Z);if(!q)throw S0(Q,Z);if(p(q)!==p(V))throw O(Q,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(q.invalid)throw O(Q,Z,"invalid-row",`row ${Z} failed validation`);if(!q.credential)throw O(Q,Z,"no-credential",`row ${Z} holds no credential`);if(V0(Q,q),(q.credentialEpoch??1)!==W||q.identity!==X.identity)throw O(Q,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let L=await P8(j,H,Q,q,J);if(L.kind!=="changed")return{id:Z,outcome:"unchanged",...L.kind==="unchanged"&&L.value!==void 0?{providerState:L.value}:{}};return j.setStateAccount(Z,L.account),await j.commitState(),L.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:L.value}})})}var U9=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function P8($,Z,X,J,z,G=!1){let{id:Q,credential:Y}=J;if(!Y)throw O(X,Q,"no-credential",`row ${Q} holds no credential`);let B=J.credentialEpoch??1,H=$.stateAccount(Q),W=H?.[v],V=D0(W);if(!_(W)||!V?.binding||V.digest!==g0(Y)||V.credentialEpoch!==B||V.binding.identity!==J.identity)throw O(X,Q,"unbound-credential",`row ${Q}'s credential carries no stamp of this store to bind a provider state to (stamp ${J.stamp}); rotate or replace it first`);let j=J.providerState===void 0?void 0:structuredClone(J.providerState),q=await v0(X,()=>z(j,J));if(G&&q===U9)return{kind:"declined"};let U=q===void 0?void 0:n0(Z,X,Q,q,"the provider state the mutator returned"),L=H!==void 0&&Object.hasOwn(H,W0);if(U===void 0?!L:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let N={...H};if(U===void 0){delete N[W0];let K={...W};delete K.providerState,N[v]=K}else{N[W0]=U;let K=a1(Z,U);if(V.providerState!==K)N[v]={...W,providerState:K}}return{kind:"changed",...U!==void 0?{value:U}:{},account:N}}import{randomUUID as q9}from"node:crypto";async function E6($,Z,X){if(!X)return;let J=$.rows().map((G)=>{let{id:Q,type:Y,label:B,enabled:H,disabledReason:W,identity:V,credentialEpoch:j,stamp:q,staged:U,torn:L,invalid:N}=G;return{id:Q,type:Y,label:B,enabled:H,disabledReason:W,identity:V,credentialEpoch:j,stamp:q,staged:U,torn:L,invalid:N}}),z=await v0($.info.operation,()=>X({id:Z,row:J.find((G)=>G.id===Z),rows:J,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw O($.info.operation,Z,"row-protected",z)}var MJ=["access","refresh","expires","lastRefreshedAt","apiKey"];function LJ($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function FJ($,Z,X){if(X.type!=="api")return X;let J=$.rosterRow(Z);if(!_(J)){if(X.baseURL===void 0)throw O($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...X,baseURL:X.baseURL}}let z=$.row(Z)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:LJ(J),Q=X.baseURL?.trim()??G.baseURL,Y=X.authHeader??G.authHeader;if(Q!==G.baseURL||Y!==G.authHeader)throw O($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...X,baseURL:Q,authHeader:Y}}function K9($,Z,X,J){let z=$.rosterRow(Z),G=$.row(Z),Q=J??(G?G.identity:_(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...Q!==void 0?{identity:Q}:{},...X.type==="api"?{baseURL:X.baseURL,authHeader:X.authHeader??"authorization-bearer"}:{}}}function I6($,Z,X,J,z={}){let G=FJ(Z,X,J),Q=Z.stateAccount(X),Y=z.providerState??{kind:"keep"},B=Z.row(X)?.credentialEpoch??Z.entry(X)?.credentialEpoch,H=typeof B==="number"?B:1,W=V9($.ctx.providerState,Y,Q,Q&&Object.hasOwn(Q,W0)?Z.row(X):void 0,H),V=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??T$(V,$.ctx.now()):void 0,q={...Q??{}};for(let N of MJ)delete q[N];if(z.clearErrors)delete q.lastRefreshError,delete q.lastQuotaRefreshError,delete q.quota;if(Y.kind==="clear")delete q[W0];else if(Y.kind==="set")q[W0]=Y.value;let U=z9(G,j),L={...q,...J9(G,j),[v]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[R6]:z.transition}:{},...q8(U,H,z.binding??K9(Z,X,U,z.identity),{replace:z.binding!==void 0,...W!==void 0?{providerState:W}:{}})}};return{stored:U,account:L}}async function x6($,Z,X){return $.setStateAccount(Z,X.account),await $.commitState(X.stored),X.stored}async function k6($,Z,X,J,z={}){return x6(Z,X,I6($,Z,X,J,z))}async function PJ($,Z,X){if(!Z.credential||Z.stamp!=="bound")return;let J=$.stateAccount(Z.id),z=C$(J,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...J??{},[v]:q8(Z.credential,Z.credentialEpoch??1,K9($,Z.id,Z.credential,X),z!==void 0?{providerState:z}:{})}),await $.commitState()}function _8($,Z,X){let J=$==="add"?i1(Z):void 0;if(J)throw O($,Z,"invalid-input",J);let z=G9(X,{baseURLOptional:$==="rotate"});if(z)throw O($,Z,"invalid-input",z)}function f6($,Z,X,J){if(!X)throw S0($,Z);if(X.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if(J&&J.type!==X.type)throw O($,Z,"type-mismatch",`row ${Z} holds a ${X.type} credential`);return X}function e1($,Z,X){if(X!==void 0&&!e(_(X)?X.credentialEpoch:void 0))throw O($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function y6($,Z,X,J){if(!X)throw S0($,Z);if(X.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw O($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function b6($,Z){return O($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function S$($,Z){return O($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function OJ($,Z,X,J){let{id:z,credential:G,identity:Q}=X;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!t1(Z.state,z))return;let Y=()=>{throw O("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),H=D0(B?.[v]);if(!H?.binding||H.dispatch===void 0||H.replace)return Y();if(G.type==="api"&&(H.binding.baseURL===void 0||H.binding.authHeader===void 0))return Y();let W=G.type==="api"?{...G,baseURL:H.binding.baseURL,authHeader:H.binding.authHeader}:G,[V]=B1({accounts:[r1({id:z,credential:W,identity:H.binding.identity,addedAt:0})],[w]:{rows:{[z]:{credentialEpoch:A6(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(g0(G)!==H.digest)return Y();if(G.type==="api"){if(G.baseURL.trim()!==H.binding.baseURL)return Y();if((G.authHeader??"authorization-bearer")!==H.binding.authHeader)return Y()}else if(i0(G)!==H.dispatch)return Y();if(H.providerState!==void 0&&V.providerState===void 0)return Y();if(J!==void 0&&a1($.ctx.providerState,J)!==H.providerState)return Y();return V}function _J($,Z,X,J){let{id:z,credential:G,identity:Q,label:Y}=X,B=Z.rosterRow(z),H=()=>{throw O("add",z,B?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},W=Z.stateAccount(z),V=D0(W?.[v]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return H();if(B&&(B.type!==G.type||B.label!==Y||B.accountId!==Q))return H();if(j.reservation!==X.stage?.reservation||j.label!==Y||j.disabledReason!==X.disabled?.reason||V.binding.identity!==Q)return H();let q=J===void 0?void 0:A1(J),U=W?.[W0],L=U===void 0?void 0:A1(U);if(j.providerState!==q||j.providerState!==L)return H();if(g0(G)!==V.digest||i0(G)!==V.dispatch)return H();let N=B?Z.config:{accounts:[{...r1({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[w]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},K=B1(N,Z.state,$.ctx.codec,$.ctx.providerState).find((F)=>F.id===z);if(!K?.credential||K.invalid||K.stamp!=="bound"||K.type!==G.type||K.enabled||K.label!==j.label||K.identity!==V.binding.identity||K.disabledReason!==j.disabledReason||K.staged?.reservation!==j.reservation)return H();if(B)return{id:z,outcome:"exists",credential:K.credential,credentialEpoch:V.credentialEpoch};if(A6(Z.config,z)!==V.credentialEpoch)return H();return Z.roster().push({...r1({id:z,credential:G,identity:Q,label:Y,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:K.credential,credentialEpoch:V.credentialEpoch}))}async function D9($,Z,X={}){G0("add");let{ctx:J}=$,{id:z,credential:G,identity:Q,label:Y}=Z,B=Z.stage!==void 0||Z.disabled!==void 0,H=await Q0(J,"add",z,X.onFailure,async(W,V)=>{_8("add",z,G);let j=X.onExisting??"rotate";if(Z.stage!==void 0&&j==="rotate")throw O("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||Z.stage!==void 0&&(Y!==void 0&&typeof Y!=="string"||Q!==void 0&&(typeof Q!=="string"||!Q))||Z.disabled!==void 0&&(!_(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!_(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||j==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw O("add",z,"invalid-input","staging requires a reservation and a disabled reason");let q=Z.providerState===void 0?void 0:n0(J.providerState,"add",z,Z.providerState);if(await W.acquire(M0($,{id:z,identity:Q})),G.type==="oauth")await W.acquire(X.providerLock??$.providerLock);for(let U of X.extraLocks??[])await W.acquire(U);return i(J,W,V,{operation:"add",rowId:z},async(U)=>{await E6(U,z,X.protect);let L=_(U.state.accounts)?U.state.accounts:{},N=Object.entries(L).find(([h,g])=>{if(h===z||U.rosterRow(h)||!_(g))return!1;let l=g[v];if(!_(l)||!Object.hasOwn(l,"staged"))return!1;return G.type==="oauth"?g.refresh===G.refresh:typeof g.apiKey==="string"&&g.apiKey.trim()===G.apiKey.trim()});if(N)throw O("add",N[0],"row-staged",`orphan ${N[0]} reserves this secret until its staged add is replayed or removed`);if(J.removedIds.has(z))throw O("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&j!=="rotate"&&(U.rosterRow(z)||t1(U.state,z)))return _J($,U,Z,q);if(j==="rotate"){U.assertNotStaged(z);let h=U.rows().find((g)=>g.fingerprint===Q1(G));if(h)U.assertNotStaged(h.id)}if(j==="refuse"){let h=U.rows().find((d)=>d.fingerprint===Q1(G)||d.id===z&&d.credential),g=_(U.state.accounts)?U.state.accounts:{},l=Object.entries(g).find(([,d])=>{if(!_(d))return!1;if(G.type==="oauth")return d.refresh===G.refresh;return typeof d.apiKey==="string"&&d.apiKey.trim()===G.apiKey.trim()})?.[0],X0=h?.id??l??z;if(h||l!==void 0||t1(U.state,z))throw O("add",X0,"credential-exists",`row ${X0} already holds this secret or id`)}if(j==="stage-duplicate"&&(U.rosterRow(z)||t1(U.state,z)))throw O("add",z,"id-exists",`row ${z} already exists`);let K=OJ($,U,Z,q),F=U.rows(),C=Q1(G),M=j==="rotate"&&!K&&F.find((h)=>h.invalid===void 0&&h.fingerprint===C);if(M){if(U.assertNotStaged(M.id),V0("add",M),Q!==void 0&&M.identity!==void 0&&Q!==M.identity)throw b6("add",M.id);let h=I6($,U,M.id,G,{...q!==void 0?{providerState:R$(J.providerState,"add",M.id,M.providerState,q)}:{}});await U.completeTorn(),U.assertNotStaged(M.id);let g=await x6(U,M.id,h);return{id:M.id,outcome:"rotated",credential:g,credentialEpoch:M.credentialEpoch??1}}let D=F.find((h)=>h.id===z);if(D){if(D.invalid)throw O("add",z,"invalid-row",`row ${z} is invalid`);if(D.credential)throw O("add",z,"id-exists",`row ${z} already holds a credential`);if(V0("add",D),D.type!==G.type)throw O("add",z,"type-mismatch",`row ${z} is a ${D.type} row`);if(Q!==void 0&&D.identity!==void 0&&Q!==D.identity)throw b6("add",z);if(!D.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let h=I6($,U,z,G,{clearErrors:!0,...q!==void 0?{providerState:{kind:"set",value:q}}:{}});await U.completeTorn();let g=await x6(U,z,h);if(!D.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:g,credentialEpoch:D.credentialEpoch??1}}let P=A6(U.config,z);if(!e(P))throw O("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let S=K?.identity??Q;U.roster().push(r1({id:z,credential:G,...S!==void 0?{identity:S}:{},...Y!==void 0?{label:Y}:{},addedAt:J.now()})),U.setEntry(z,{credentialEpoch:P,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let f="added";if(Z.disabled)J1(U,z,Z.disabled.reason),f="added-disabled";if(!Z.disabled&&S!==void 0&&G.type==="oauth"){if(F.find((g)=>g.invalid===void 0&&g.type==="oauth"&&g.enabled&&g.identity===S))J1(U,z,X8),f="added-disabled"}if(K?.credential)return await U.commitConfig(),{id:z,outcome:f,credential:K.credential,credentialEpoch:K.credentialEpoch??P};U.dropStateAccount(z);let n=I6($,U,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...Y!==void 0?{label:Y}:{},...q!==void 0?{providerState:A1(q)}:{}}}:{},...q!==void 0?{providerState:{kind:"set",value:q}}:{}});if(j==="rotate")await U.completeTorn();let _0=await x6(U,z,n);return await U.commitConfig(),{id:z,outcome:f,credential:_0,credentialEpoch:P}},{completeTorn:!1})});if(!B&&G.type==="oauth"&&(H.outcome==="added"||H.outcome==="completed"))$.firePull(H.id,"add");return H}async function N9($,Z,X,J={},z={}){G0("replace");let{ctx:G}=$,Q=await Q0(G,"replace",Z,z.onFailure,async(Y,B)=>{_8("replace",Z,X),e1("replace",Z,z.attribution);let H=J.providerState===void 0?void 0:n0(G.providerState,"replace",Z,J.providerState),{row:W}=await a0($,"replace",Z);if(await Y.acquire(M0($,W)),X.type==="oauth")await Y.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await Y.acquire(V);return i(G,Y,B,{operation:"replace",rowId:Z},async(V)=>{if(z.attribution!==void 0)y6("replace",Z,V.row(Z),z.attribution),await V.completeTorn();let j=f6("replace",Z,V.row(Z),X);if(p(j)!==p(W))throw S$("replace",Z);let q=V.entry(Z)?.credentialEpoch,U=(typeof q==="number"?q:1)+1;if(!e(U))throw O("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 L=H9(G.providerState,j,U,J.identity,H),N={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(N8(V,Z,U,N),J.identity!==void 0)d1(V,J.identity);let K=await k6($,V,Z,X,{clearErrors:!0,binding:N,providerState:L});return await V.commitConfig(),{id:Z,credential:K,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(X.type==="oauth")$.firePull(Z,"replace");return Q}async function M9($,Z,X,J={},z={}){G0("rotate");let{ctx:G}=$;return Q0(G,"rotate",Z,z.onFailure,async(Q,Y)=>{_8("rotate",Z,X),e1("rotate",Z,z.attribution);let B=J.providerState===void 0?void 0:n0(G.providerState,"rotate",Z,J.providerState),{row:H}=await a0($,"rotate",Z);if(await Q.acquire(M0($,H)),J.identity!==void 0&&X.type==="oauth")await Q.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await Q.acquire(W);return i(G,Q,Y,{operation:"rotate",rowId:Z},async(W)=>{if(z.attribution!==void 0)y6("rotate",Z,W.row(Z),z.attribution),await W.completeTorn();let V=f6("rotate",Z,W.row(Z),X);if(p(V)!==p(H))throw S$("rotate",Z);if(V0("rotate",V),J.identity!==void 0&&V.identity!==void 0&&J.identity!==V.identity)throw b6("rotate",Z);let j=J.identity!==void 0&&V.identity===void 0?J.identity:void 0,q=await k6($,W,Z,X,{identity:j,...B!==void 0?{providerState:R$(G.providerState,"rotate",Z,V.providerState,B)}:{}}),U=!1;if(!V.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),U=!0;if(J.identity!==void 0&&V.identity!==J.identity)_1(W,Z,J.identity),U=!0;if(U)await W.commitConfig();return{id:Z,credential:q}},{completeTorn:z.attribution===void 0})})}async function L9($,Z,X,J,z){G0(Z);let{ctx:G}=$,Q=G.providerState,Y=z.attribution,B=z.providerState;return Q0(G,Z,X,z.onFailure,async(H,W)=>{if(e1(Z,X,Y),B!==void 0){if(typeof B!=="function")throw O(Z,X,"invalid-input","the provider-state mutator must be a function");if(Y===void 0)throw O(Z,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!Q)throw O(Z,X,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await a0($,Z,X);await H.acquire(M0($,V));for(let j of z.extraLocks??[])await H.acquire(j);return i(G,H,W,{operation:Z,rowId:X},async(j)=>{await E6(j,X,z.protect),j.assertNotStaged(X);let q=j.row(X),U=J.enabled?f6("enable",X,q):q;if(!U||!j.rosterRow(X))throw S0(Z,X);if(p(U)!==p(V))throw S$(Z,X);if(Y!==void 0)y6(Z,X,U,Y);if(J.enabled&&U.disabledReason?.startsWith(l1))throw O("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let L=!J.enabled||!U.enabled||U.disabledReason!==void 0;if(J.enabled&&L&&U.type==="oauth"){let M=U.identity===void 0?void 0:j.rows().find((D)=>D.id!==X&&D.invalid===void 0&&D.type==="oauth"&&D.enabled&&D.identity===U.identity);if(M)throw O("enable",X,"duplicate-identity",`row ${M.id} is enabled with the same identity as row ${X}`)}if(B===void 0||Q===void 0){if(await j.completeTorn(),!L)return{id:X};if(J.enabled)F$(j,X);else J1(j,X,J.reason);return await j.commitConfig(),{id:X}}if(!U.credential)throw O(Z,X,"no-credential",`row ${X} holds no credential`);V0(Z,U);let N=await P8(j,Q,Z,U,B,!0);if(N.kind==="declined")return{id:X,declined:!0};await j.completeTorn();let K={id:X,providerStateOutcome:N.kind==="unchanged"?"unchanged":N.value===void 0?"cleared":"updated",...N.value!==void 0?{providerState:N.value}:{}};if(N.kind==="unchanged"){if(L){if(J.enabled)F$(j,X);else J1(j,X,J.reason);await j.commitConfig()}return K}if(!L)return j.setStateAccount(X,N.account),await j.commitState(),K;let F=J.enabled?{mark:q9(),enabled:!0}:{mark:q9(),enabled:!1,reason:J.reason},C=N.account[v];return j.setStateAccount(X,{...N.account,[v]:{...C,[R6]:F}}),await j.commitState(),A$(j,X,F),await j.commitConfig(),K},{completeTorn:!1})})}function F9($,Z,X,J={}){return L9($,"disable",Z,{enabled:!1,reason:X},J)}function P9($,Z,X={}){return L9($,"enable",Z,{enabled:!0},X)}async function O9($,Z,X={}){G0("remove");let{ctx:J}=$;return Q0(J,"remove",Z,X.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw O("remove",Z,"invalid-input","id must be non-empty");let Q=X.attribution;if(e1("remove",Z,Q),X.staged!==void 0&&(!_(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw O("remove",Z,"invalid-input","a staged removal needs a reservation");let Y=await H0(J);if(Y.status!=="ready")throw R0(Y,"remove",Z);let B=Y.rows.find((W)=>W.id===Z);if(!B&&!t1(Y.state,Z))throw S0("remove",Z);let H=p(B??{id:Z});await z.acquire(M0($,B??{id:Z}));for(let W of X.extraLocks??[])await z.acquire(W);return i(J,z,G,{operation:"remove",rowId:Z},async(W)=>{let V=W.reservation(Z);if(V!==void 0){if(!_(V)||!X.staged||V.reservation!==X.staged.reservation)throw O("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(X.staged)throw O("remove",Z,"attribution",`row ${Z} is no longer reserved`);let j=W.row(Z),q=t1(W.state,Z);if(!j&&!q)throw S0("remove",Z);if(p(j??{id:Z})!==H)throw S$("remove",Z);if(Q!==void 0)if(j)v6(Z,j,Q);else CJ($,W,Z,Q);let U=X.protect;if(U){let L={row:j,config:W.snapshot.config,state:W.snapshot.state},N=await v0("remove",()=>U(Z,L));if(N!==void 0)throw O("remove",Z,"row-protected",N)}if(j){if(Q===void 0)await W.completeTorn();W.dropRosterRows(Z),await W.commitConfig()}if(q)W.dropStateAccount(Z),await W.commitState();return{id:Z,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function v6($,Z,X,J="remove"){if(y6(J,$,Z,X),Z.torn)throw O(J,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw O(J,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function CJ($,Z,X,J){let z=()=>O("remove",X,"unbound-credential",`orphan ${X} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=Z.stateAccount(X),Q=D0(G?.[v]);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]=B1({accounts:[r1({id:X,credential:Y,identity:Q.binding.identity,addedAt:0})],[w]:{rows:{[X]:{credentialEpoch:Q.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!B?.credential||B.invalid||B.stamp!=="bound")throw z();if(Q.credentialEpoch!==J.credentialEpoch||Q.binding.identity!==J.identity)throw O("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function t1($,Z){let X=$.accounts;return _(X)&&Object.hasOwn(X,Z)}function O8($){return _($)&&typeof $.id==="string"?$.id:void 0}function TJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let X=new Set;for(let G of $){let Q=O8(G);if(Q!==void 0)X.add(Q)}let J=new Set;for(let G of Z){if(typeof G!=="string")return"ids must be an array of roster ids";if(J.has(G))return`id ${G} appears more than once`;if(!X.has(G))return`id ${G} is not in the roster`;J.add(G)}let z=[...X].filter((G)=>!J.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function AJ($,Z){let X=new Map;for(let G of $){let Q=O8(G);if(Q===void 0)continue;let Y=X.get(Q);if(Y)Y.push(G);else X.set(Q,[G])}let J=Z.flatMap((G)=>X.get(G)??[]),z=0;return $.map((G)=>O8(G)===void 0?G:J[z++])}async function _9($,Z,X={}){G0("reorder");let{ctx:J}=$,z=X.onFailure;return Q0(J,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let Y of X.extraLocks??[])await G.acquire(Y);return i(J,G,Q,{operation:"reorder",rowId:void 0},async(Y)=>{let B=Y.roster(),H=TJ(B,Z);if(H)throw new E({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:H});let W=[...Z],V=AJ(B,W);if(V.every((j,q)=>j===B[q]))return{ids:W,outcome:"unchanged"};return Y.config.accounts=V,await Y.commitConfig(),{ids:W,outcome:"reordered"}},{completeTorn:!1})})}async function C9($,Z,X,J,z={}){return G0("recordIdentity"),Q0($.ctx,"recordIdentity",Z,z.onFailure,async(G,Q)=>{if(typeof X!=="string"||X.length===0)throw O("recordIdentity",Z,"invalid-input","identity must be non-empty");let Y=_(J)?J.credentialEpoch:void 0;if(!e(Y))throw O("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:B}=await a0($,"recordIdentity",Z);await G.acquire(M0($,B)),await G.acquire(z.providerLock??$.providerLock);for(let H of z.extraLocks??[])await G.acquire(H);return i($.ctx,G,Q,{operation:"recordIdentity",rowId:Z},async(H)=>{let W=f6("recordIdentity",Z,H.row(Z));if(p(W)!==p(B))throw S$("recordIdentity",Z);if(V0("recordIdentity",W),(W.credentialEpoch??1)!==Y)throw O("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(W.identity!==void 0&&W.identity!==X)throw b6("recordIdentity",Z);if(W.identity===void 0)await PJ(H,W,X);let V=_1(H,Z,X);return await H.commitConfig(),{id:Z,disabled:V}})})}function A9($){let Z=$[w];return _(Z)&&_(Z.publications)?Z.publications:{}}function R9($,Z){let X=A9($);if(!Object.hasOwn(X,Z))return;let J=X[Z];if(!_(J)||J.operationId!==Z||typeof J.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(J.planDigest)||!["committed","cleaned"].includes(String(J.phase))||!Array.isArray(J.removed)||!Array.isArray(J.finalized)||J.removed.some((z)=>!_(z)||typeof z.id!=="string"||!e(z.credentialEpoch))||J.finalized.some((z)=>!_(z)||typeof z.id!=="string"||!e(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw O("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function S9($,Z){let X=await H0($.ctx);if(X.status!=="ready")throw R0(X,"publishRoster",Z);return R9(X.config,Z)}function RJ($,Z){let X=()=>{throw O("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!_(Z)||typeof Z.operationId!=="string"||!Z.operationId||!Array.isArray(Z.remove)||!Array.isArray(Z.finalize)||!Array.isArray(Z.order))X();let J=new Set;for(let z of[...Z.remove,...Z.finalize]){if(!_(z)||typeof z.id!=="string"||i1(z.id)||J.has(z.id)||!z.attribution)X();if(J.add(z.id),e1("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))X()}for(let z of Z.remove)if($.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")X();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"))X();if(Z.order.some((z)=>typeof z!=="string"||i1(z))||new Set(Z.order).size!==Z.order.length)X()}function I9($,Z){$.entries();let X=$.config[w],J={...A9($.config)};Object.defineProperty(J,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function SJ($,Z,X){let J=new Set;for(let Q of n1($.config)){if(!_(Q)||typeof Q.id!=="string")continue;if(J.has(Q.id))throw O("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");J.add(Q.id)}let z=new Set(Z.remove.map((Q)=>Q.id)),G=X.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 O("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function T9($,Z){await $.assertAll();for(let J of Z.removed)if(D0($.stateAccount(J.id)?.[v])?.credentialEpoch===J.credentialEpoch&&!$.rosterRow(J.id))$.dropStateAccount(J.id);for(let J of Z.finalized){let z=$.stateAccount(J.id),G=D0(z?.[v]);if(z&&G?.credentialEpoch===J.credentialEpoch&&G.staged?.reservation===J.reservation){let Q={...z[v]};delete Q.staged,$.setStateAccount(J.id,{...z,[v]:Q})}}await $.commitState(void 0,{durable:!0});let X={...Z,phase:"cleaned"};return I9($,X),await $.commitConfig({durable:!0}),X}async function x9($,Z,X={}){return G0("publishRoster"),Q0($.ctx,"publishRoster",Z?.operationId??"",X.onFailure,async(J,z)=>{if(!_(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw O("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=A1(Z),Q=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((Y)=>_(Y)&&typeof Y.id==="string");for(let Y=0;;Y++){let B=await H0($.ctx);if(B.status!=="ready")throw R0(B,"publishRoster",Z.operationId);let H=new Map(Q.map(({id:V})=>[V,p(B.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(H.values())].sort())await J.acquire(M0($,{id:V}));await J.acquire(X.providerLock??$.providerLock);for(let V of X.extraLocks??[])await J.acquire(V);let W=await i($.ctx,J,z,{operation:"publishRoster",rowId:Z.operationId},async(V)=>{let j=V.rows();if(Q.some(({id:D})=>p(j.find((P)=>P.id===D)??{id:D})!==H.get(D)))return;let q=R9(V.config,Z.operationId);if(q){if(q.planDigest!==G)throw O("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(q.phase==="cleaned")return{outcome:"already-cleaned",receipt:q};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await T9(V,q)}}RJ($,Z);let U=SJ(V,Z,j),L=[];for(let D of Z.remove){V.assertNotStaged(D.id);let P=j.find((S)=>S.id===D.id);if(!P)throw O("publishRoster",D.id,"attribution","the removed row no longer exists");if(v6(D.id,P,D.attribution,"publishRoster"),!P.credential||D.fingerprint!==void 0&&Q1(P.credential)!==D.fingerprint)throw O("publishRoster",D.id,"attribution","the removed secret no longer matches");L.push(P)}let N=[];for(let D of Z.finalize){let P=j.find((g)=>g.id===D.id),S=D0(V.stateAccount(D.id)?.[v]);if(!P||P.staged?.reservation!==D.reservation||S?.staged?.reservation!==D.reservation||P.enabled)throw O("publishRoster",D.id,"row-staged","the finalized row is not disabled under this reservation");let f=V.stateAccount(D.id),n=V.rosterRow(D.id),_0=f?.[W0],h=_0===void 0?void 0:A1(_0);if(!S?.staged||S.staged.label!==n?.label||S.staged.disabledReason!==P.disabledReason||S.staged.providerState!==h)throw O("publishRoster",D.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");v6(D.id,P,D.attribution,"publishRoster"),N.push(P)}let K=U.find((D)=>D.torn);if(K)throw O("publishRoster",Z.operationId,"attribution",`Row ${K.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let F=new Set;for(let D of U){if(!(Z.finalize.find((S)=>S.id===D.id)?.enabled??D.enabled)||D.type!=="oauth"||D.identity===void 0)continue;if(F.has(D.identity))throw O("publishRoster",D.id,"invalid-input","the final enabled roster repeats a known identity");F.add(D.identity)}for(let D of U)if(D.identity!==void 0&&D.fingerprint!==void 0&&U.some((P)=>P.id!==D.id&&P.identity!==void 0&&P.identity!==D.identity&&P.fingerprint===D.fingerprint))throw O("publishRoster",D.id,"attribution","the resulting pool gives the same secret different known identities");for(let D of N)if(D.identity!==void 0&&L.some((P)=>P.identity!==void 0&&P.identity!==D.identity&&P.fingerprint===D.fingerprint))throw O("publishRoster",D.id,"attribution","the staged secret belonged to a different known identity");await E6(V,Z.operationId,X.protect);let C={operationId:Z.operationId,planDigest:G,phase:"committed",removed:L.map((D)=>({id:D.id,credentialEpoch:D.credentialEpoch??1})),finalized:Z.finalize.map((D,P)=>({id:D.id,credentialEpoch:N[P]?.credentialEpoch??1,reservation:D.reservation,enabled:D.enabled}))};for(let D of Z.remove)V.dropRosterRows(D.id);for(let D of Z.finalize){let P=V.rosterRow(D.id);P.enabled=D.enabled;let S={...V.entry(D.id)};if(delete S.staged,D.enabled)delete S.disabledReason;else S.disabledReason=D.disabledReason;V.setEntry(D.id,S)}let M=V.roster().filter((D)=>!_(D)||typeof D.id!=="string"||j.find((P)=>P.id===D.id)?.invalid==="roster");return V.config.accounts=[...Z.order.map((D)=>V.rosterRow(D)),...M],I9(V,C),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await T9(V,C)}},{completeTorn:!1});if(W)return W;if(await J.releaseAll(),Y>=1)throw O("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class C8{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,X,J,z){this.rt=$,this.hook=Z,this.onFailure=X,this.firedAtLoad=J,this.logger=z}fire($,Z){if(!this.hook)return;if(Z==="load"){if(this.firedAtLoad.has($))return;this.firedAtLoad.add($)}let X=this.run($,Z);this.inflight.add(X),X.finally(()=>this.inflight.delete(X))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run($,Z){let X=this.rt(),{ctx:J}=X,z=new z1(J.lockDefaults,J.lockEnv),G={writes:0};try{let Q=await i(J,z,G,{operation:"pull",rowId:$},async(B)=>{if(B.reservation($)!==void 0)return;await B.completeTorn();let H=B.row($);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)V0("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.hasEntry)B.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await B.commitConfig();let W=B.row($);if(!W?.credential||W.credentialEpoch===void 0)return;return{id:$,credential:W.credential,credentialEpoch:W.credentialEpoch,...W.identity!==void 0?{identity:W.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!Q){this.firedAtLoad.delete($);return}await J.hold?.("pull-before-request",$);let Y;try{Y=await this.hook?.(Q)}catch(B){throw new E({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:B})}await S6(X,$,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},Y)}catch(Q){this.firedAtLoad.delete($);let Y=o1(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()}}}import{randomUUID as IJ}from"node:crypto";function T8($,Z){if(T1("refresh",$,Z?.staged),!Z)throw O("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw O("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw O("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw O("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function b9($){return O("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 E9($,Z,X,J={}){G0("refresh");let{ctx:z}=$;return Q0(z,"refresh",Z,J.onFailure,async(G,Q)=>{let{row:Y}=await a0($,"refresh",Z);T8(Z,Y);let B=await J.refuse?.(Y);if(B!==void 0)return{status:"refused",rowId:Z,reason:B};let H=p(Y),W;for(let U=0;;U++){await G.acquire(M0($,{id:Z,identity:H===Z?void 0:H})),await G.acquire(J.providerLock??$.providerLock);for(let K of J.extraLocks??[])await G.acquire(K);let N=await i(z,G,{writes:0},{operation:"refresh",rowId:Z},async(K)=>{let F=T8(Z,K.row(Z));if(V0("refresh",F),!F.hasEntry)K.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await K.commitConfig(),F=T8(Z,K.row(Z));if(p(F)!==H)return{keyNow:p(F)};let C=await J.refuse?.(F);if(C!==void 0)return{refused:C};return{row:F,credential:F.credential,credentialEpoch:F.credentialEpoch,identity:F.identity}});if("refused"in N)return{status:"refused",rowId:Z,reason:N.refused};if("keyNow"in N){if(await G.releaseAll(),U>=1)throw O("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);H=N.keyNow;continue}W=N;break}if(D8(W.credential.lastRefreshedAt,z.now()))throw b9(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let V;try{V=await X(W.credential,W.row)}catch(U){throw new E({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw O("refresh",Z,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:n0(z.providerState,"refresh",Z,V.providerState,"the provider state the provider returned"),q=await i(z,G,Q,{operation:"refresh",rowId:Z},async(U)=>{let L=U.row(Z),N=U.entry(Z);if(!L||L.invalid||!N||N.credentialEpoch!==W.credentialEpoch||L.identity!==W.identity)throw new E({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`});V0("refresh",L);let K=await J.refuse?.(L);if(K!==void 0)return{refused:K};let F=z.now(),C=L.credential?.type==="oauth"?L.credential.lastRefreshedAt:void 0;if(D8(C,F))throw b9(Z);let M={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},D=L.identity!==void 0&&V.identity!==void 0&&L.identity!==V.identity?{expectedIdentity:L.identity,returnedIdentity:V.identity}:void 0,P=D?{mark:IJ(),enabled:!1,reason:`${l1}${JSON.stringify(D)}`}:void 0,S=L.identity===void 0&&V.identity?V.identity:void 0,f=await k6($,U,Z,M,{stamp:T$(C,F),transition:P,identity:S,...j!==void 0?{providerState:R$(z.providerState,"refresh",Z,L.providerState,j)}:{}});if(P!==void 0)A$(U,Z,P),await U.commitConfig();let n=L.identity;if(S!==void 0)_1(U,Z,S),n=S,await U.commitConfig();return{stored:f,identity:n,contradiction:D,refused:void 0}});if(q.refused!==void 0)return{status:"refused",rowId:Z,reason:q.refused};if(q.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...q.contradiction,credential:q.stored};if(J.onPersisted)try{let U=J.onPersisted;await v0("refresh",()=>U(Z,q.stored))}catch(U){throw new E({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:q.stored,message:"the after-persist hook threw; the rotation stays committed",cause:U})}return{status:"rotated",rowId:Z,credential:q.stored,...q.identity!==void 0?{identity:q.identity}:{}}})}import{isDeepStrictEqual as xJ}from"node:util";var h6=Object.freeze(["version","accounts",w]);function A8($){let Z={};for(let[X,J]of Object.entries($))if(!h6.includes(X))g6(Z,X,J);return Z}function g6($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function bJ($,Z){let X={};for(let[J,z]of Object.entries($))if(h6.includes(J))g6(X,J,z);else if(Object.hasOwn(Z,J))g6(X,J,Z[J]);for(let[J,z]of Object.entries(Z))if(!Object.hasOwn($,J))g6(X,J,z);return X}function k9($){return new E({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}async function f9($){let Z=await H0($.ctx);if(Z.status==="error")return Z;return{status:Z.status,settings:A8(Z.config)}}async function y9($,Z,X={}){G0("updateSettings");let{ctx:J}=$,z=X.onFailure;return Q0(J,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of X.extraLocks??[])await G.acquire(B);let Y=G.held.length;try{for(let N of J.storeLocks)await G.acquire(N);let B=await H0(J);if(B.status!=="ready")throw R0(B,"updateSettings",void 0);let H=A8(B.config),W=structuredClone(H),V=await v0("updateSettings",()=>Z(W)),j=V===void 0?W:V;if(!_(j))throw k9("the settings mutator must produce an object");let q=h6.filter((N)=>Object.hasOwn(j,N));if(q.length>0)throw k9(`settings cannot set the pool-owned key(s) ${q.join(", ")}`);if(xJ(j,H))return{settings:H,outcome:"unchanged"};let U=bJ(B.config,j),L={operation:"updateSettings",rowId:void 0};return await P0(J.configPath,U,{beforeRename:async()=>{await J.onStep?.("before-config-write",L),await G.assertAll()}}),Q.writes++,await J.onStep?.("after-config-write",L),{settings:A8(U),outcome:"updated"}}finally{await G.releaseTo(Y)}})}var v9=new Map;function EJ($){let Z=v9.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},v9.set($,Z);return Z}function g9($){if($.status==="ready")return{status:"ready",schemaVersion:G1,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function R8($){let Z=EJ($.configPath),X={...V8,...$.lockOptions},J={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:X,lockEnv:{now:$.now??Date.now,...$.onLockEvent?{onLockEvent:$.onLockEvent}:{},...$.onLockStep?{onLockStep:$.onLockStep}:{}},removedIds:Z.removedIds,requireCredentialStamps:$.requireCredentialStamps===!0,requireRemovedFingerprint:$.requireRemovedFingerprint===!0,...$.logger?{logger:$.logger}:{},...$.onStep?{onStep:$.onStep}:{},...$.hold?{hold:$.hold}:{}},z=new C8(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:J,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(Q,Y)=>z.fire(Q,Y)};return{async load(){let Q=await H0(J);if(Q.status==="ready"){for(let Y of Q.rows)if((Y.candidate||Y.torn&&Y.enabled)&&Y.type==="oauth"&&Y.needsFirstReading)z.fire(Y.id,"load")}return g9(Q)},async read(){return g9(await H0(J))},async initialize(Q={}){return{status:await W9(J,Q.dropKeys??[])}},add:(Q,Y)=>D9(G,Q,Y),publishRoster:(Q,Y)=>x9(G,Q,Y),publication:(Q)=>S9(G,Q),replace:(Q,Y,B,H)=>N9(G,Q,Y,B,H),rotate:(Q,Y,B,H)=>M9(G,Q,Y,B,H),updateProviderState:(Q,Y,B,H)=>j9(G,Q,Y,B,H),disable:(Q,Y,B)=>F9(G,Q,Y,B),enable:(Q,Y)=>P9(G,Q,Y),remove:(Q,Y)=>O9(G,Q,Y),reorder:(Q,Y)=>_9(G,Q,Y),readSettings:()=>f9(G),updateSettings:(Q,Y)=>y9(G,Q,Y),recordIdentity:(Q,Y,B,H)=>C9(G,Q,Y,B,H),refresh:(Q,Y,B)=>E9(G,Q,Y,B),recordQuota:(Q,Y,B)=>S6(G,Q,Y,B),requestReading:(Q)=>z.fire(Q,"admission"),pullsSettled:()=>z.settled()}}var kJ=[/\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 x8($={}){let{redactStrings:Z}=y0({...$,extraValuePatterns:[...kJ,...$.extraValuePatterns??[]]});return(X)=>Z(X)}class j0 extends Error{code;constructor($,Z,X){super(Z,X);this.name="CommandError",this.code=$}}var h9=/^[a-z][a-z0-9-]{0,63}$/,S8={code:"action-failed",text:"That action failed."},fJ=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 I$($){if($ instanceof j0)return{code:h9.test($.code)?$.code:S8.code,text:$.message};if($ instanceof E)return{code:`pool-${$.kind}`,text:fJ.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return S8}var w9="This cannot be undone. Continue?",yJ=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function vJ($){let Z=$.toLowerCase().replace(/[-_]/g,"");return yJ.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function gJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function I8($,Z,X){if(typeof $==="string"){let z=X.redact($);if(z!==$)X.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>I8(z,`${Z}[${G}]`,X));if(!gJ($))return $;let J={};for(let[z,G]of Object.entries($)){if(vJ(z)){X.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(J,z,{value:I8(G,`${Z}.${z}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function m9($,Z,X){let J={redact:X.redact,dropped:[],redacted:[]},z=I8($,"payload",J);if(J.dropped.length>0)X.logger.warn("credential-shaped field dropped from a command payload",{command:Z,fields:J.dropped});if(J.redacted.length>0)X.logger.warn("secret-shaped text masked in a command payload",{command:Z,fields:J.redacted});return z}function hJ($){return{value:String($.value),label:String($.label)}}function wJ($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(hJ),...$.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 b8($){if($.irreversible===!0)return{message:$.confirm||w9,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function p9($){let Z=b8($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(wJ),...Z?{confirm:Z}:{}}}function mJ($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function pJ($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:mJ($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(p9)}}function uJ($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(pJ),actions:(Z.actions??[]).map(p9),...Z.facts!==void 0?{facts:Z.facts}:{}}}function u9($,Z,X){return{command:$,title:Z,sections:X.map(uJ)}}function l9($,Z,X,J){return m9({command:$,menu:u9($,Z,X)},$,J)}function d9($,Z,X,J,z){return m9({command:$,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:h9.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:u9($,Z,X)},$,z)}var i9="disabled from the command menu";function lJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function r0($){return lJ($)?{...$}:{}}function dJ($){if($.status!=="ready")return[];let Z=new Set;return $.rows.filter((X)=>{if(Z.has(X.id))return!1;return Z.add(X.id),!0})}function cJ($,Z){return $.label??Z??$.id}function w6($,Z){return o($.quota)?c($.quota,Z):void 0}function a9($,Z){return`${$} ${Z}${$===1?"":"s"}`}var x$="Actions";function sJ($){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 c9($,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 s9($){return I$($).text}async function iJ($){let Z=await $.read(),X=await $.readSettings();return{load:Z,rows:dJ(Z),settings:X.status==="error"?{}:X.settings}}function m6($,Z){let X=Z.accounts?.describeIdentity?Z.accounts.describeIdentity($):$.identity;return{account:{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...X!==void 0?{identity:X}:{}},name:cJ($,X)}}function aJ($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=Z.rows.map((V)=>V.id),Q=sJ(Z.load),Y=Z.rows.filter((V)=>V.enabled).length,B=Z.rows.map((V,j)=>{let{account:q,name:U}=m6(V,$),L=[V.type==="api"?"API key":"OAuth",...q.identity!==void 0?[q.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),N=V.invalid?"invalid":V.enabled?"enabled":"disabled",K=[];if(!V.invalid&&V.enabled)K.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(V.id,i9,z),`Disabled ${U}.`}});if(!V.invalid&&!V.enabled)K.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(V.id,z),`Enabled ${U}.`}});if(G.length>1)K.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((F,C)=>({value:String(C+1),label:String(C+1)})),value:String(j+1)}],run:async({values:F})=>{let C=Number(F.position),M=G.filter((P)=>P!==V.id);return M.splice(C-1,0,V.id),(await X.reorder(M,z)).outcome==="unchanged"?`${U} is already at position ${C}.`:`Moved ${U} to position ${C}.`}});return K.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await X.remove(V.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${U}.`}}),{id:V.id,label:U,detail:L,group:"Accounts",status:N,account:q,actions:K}}),H=$.accounts?.login,W=[];if(H&&!Q)W.push({id:"add",label:H.label??"Add account",group:x$,knobs:H.knobs??[],run:async({values:V,invocation:j})=>{let q=await H.run(V,j);if(q.status==="cancelled")return{ok:!1,text:q.message??"Login cancelled."};if(q.status==="ready"){let U=await X.add(q.account,z);return c9(q.account.label??U.id,U)}return q.completion.then(async(U)=>{if(!U){j.notify("Login cancelled.","warning");return}let L=await X.add(U,z);j.notify(c9(U.label??L.id,L))},(U)=>{j.notify(`Adding the account failed: ${s9(U)}`,"error")}).catch((U)=>{j.notify(`Adding the account failed: ${s9(U)}`,"error")}),q.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[Z.rows.length===0?"No accounts yet":`${a9(Z.rows.length,"account")}, ${Y} enabled`],items:Q?[]:B,actions:W}}}function nJ($,Z){let X=$.quota?.scope??"all",J=$.now(),z=X==="all"?"Accounts":`Accounts · ${X}`,G=async(W,V)=>{if($.quota?.check)await $.quota.check(W,V);else{for(let j of W)$.store.requestReading(j);await $.store.pullsSettled()}},Q=Z.rows.filter((W)=>W.candidate),Y=Q.map((W)=>{let{account:V,name:j}=m6(W,$),q=w6(W,X);return{id:W.id,label:j,group:z,status:T0(q,{now:J,form:"compact"}),detail:T0(q,{now:J,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([W.id],U),`Checked quota for ${j}.`}}]}}),B=Z.rows.filter((W)=>!W.candidate).map((W)=>{let{name:V}=m6(W,$),j=W.invalid?"invalid":!W.enabled?"disabled":W.credential===void 0?"no credential":"unavailable",q=T0(w6(W,X),{now:J,form:"compact"});return`${V} (${j}): ${q}`}),H=[];if(Q.length>0)H.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:x$,run:async({invocation:W})=>{let V=Q.map((j)=>j.id);return await G(V,W),`Checked quota for ${a9(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:B,items:Y,actions:H}}}function rJ($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],Q=r0(Z.settings.routing).mode,Y=typeof Q==="string"&&G.some((U)=>U.value===Q)?Q:"ordered",B=c3(Y),H=Z.rows.map((U)=>U.id),W=u1(H,B.placement,$.routing?.formerMainId??N6),j=[`Mode: ${G.find((U)=>U.value===Y)?.label??Y}`];if(H.length>0)j.push(`Roster order: ${H.join(", ")}`);if(B.mode==="ordered"&&W.join()!==H.join())j.push(`Tried in order: ${W.join(", ")}`);let q=[{id:"mode",label:"Change mode",group:x$,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:Y}],run:async({values:U})=>{let L=String(U.mode);return await X.updateSettings((N)=>{N.routing={...r0(N.routing),mode:L};return},z),`Routing mode set to ${G.find((N)=>N.value===L)?.label??L}.`}}];if(H.length>1)q.push({id:"order",label:"Set order",group:x$,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:H.join(", "),required:!0}],run:async({values:U})=>{let L=String(U.order).split(/[\s,]+/).filter((K)=>K.length>0),N=await X.reorder(L,z);return N.outcome==="unchanged"?"The order is unchanged.":`Order set to ${N.ids.join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:q}}}function oJ($,Z){if($.limits?.labels)return[...$.limits.labels];let X=$.quota?.scope??"all",J=[];for(let z of Z.rows)for(let G of w6(z,X)?.limits??[])if(!J.includes(G.label))J.push(G.label);return J.length>0?J:["primary"]}function tJ($,Z){let X=$.quota?.scope??"all",J=new Map;for(let z of Z.rows)for(let G of w6(z,X)?.limits??[])if(G.windowMinutes!==void 0&&!J.has(G.label))J.set(G.label,K6(G));return(z)=>J.get(z)??z}function eJ($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=r0(Z.settings.killswitch),Q=G.enabled===!0,Y=r0(G.accounts),B=oJ($,Z),H=tJ($,Z),W=Q?"on":"off",V=Z.rows.map((j)=>{let{account:q,name:U}=m6(j,$),L=r0(Y[j.id]),N=B.filter((K)=>typeof L[K]==="number");return{id:j.id,label:U,group:`Floors · killswitch ${W}`,status:N.length===0?"no floors":N.map((K)=>`${H(K)} ≥${L[K]}%`).join(" · "),account:q,actions:[{id:"floors",label:"Set floors",knobs:B.map((K)=>({kind:"number",id:K,label:`Minimum % left for ${H(K)}`,min:0,max:100,...typeof L[K]==="number"?{value:L[K]}:{}})),run:async({values:K})=>{return await X.updateSettings((F)=>{let C=r0(F.killswitch),M=r0(C.accounts),D=r0(M[j.id]);for(let P of B){let S=K[P];if(typeof S==="number")D[P]=S;else if(S===null)delete D[P]}if(Object.keys(D).length>0)M[j.id]=D;else delete M[j.id];if(Object.keys(M).length>0)C.accounts=M;else delete C.accounts;F.killswitch=C;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${W}`],items:V,actions:[{id:"killswitch",label:Q?"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:x$,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!Q}],run:async({values:j})=>{let q=j.enabled===!0;return await X.updateSettings((U)=>{U.killswitch={...r0(U.killswitch),enabled:q};return},z),`Killswitch ${q?"on":"off"}.`}}]}}}async function n9($){let Z=await iJ($.store);return[aJ($,Z),nJ($,Z),rJ($,Z),eJ($,Z)]}var $z=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),E8=["accounts","quota","routing","limits"];function r9($,Z){let{sessionId:X}=$,J=$.notify.bind($);return Object.freeze({...X!==void 0?{sessionId:X}:{},notify:(z,G)=>G===void 0?J(Z(String(z))):J(Z(String(z)),G)})}function Zz($,Z){switch($.kind){case"choice":{let X=Z??$.value;if(typeof X==="string"&&$.choices.some((J)=>J.value===X))return{value:X};return{problem:`Choose one of the options for ${$.label}.`}}case"toggle":{let X=Z??$.value;return typeof X==="boolean"?{value:X}:{problem:`${$.label} must be on or off.`}}case"number":{let X=Z===void 0?$.value??null:Z;if(X===null||X==="")return $.required?{problem:`${$.label} needs a number.`}:{value:null};let J=typeof X==="number"?X:Number(X);if(typeof X==="boolean"||!Number.isFinite(J))return{problem:`${$.label} needs a number.`};if($.min!==void 0&&J<$.min)return{problem:`${$.label} must be at least ${$.min}.`};if($.max!==void 0&&J>$.max)return{problem:`${$.label} must be at most ${$.max}.`};return{value:J}}case"text":{let X=Z===void 0?$.value??null:Z;if(X===null||X==="")return $.required?{problem:`${$.label} cannot be empty.`}:{value:null};return typeof X==="string"?{value:X}:{problem:`${$.label} must be text.`}}}}function Xz($,Z){let X={};for(let J of $){let z=Z&&Object.hasOwn(Z,J.id)?Z[J.id]:void 0,G=Zz(J,z);if("problem"in G)return G;X[J.id]=G.value}return{values:X}}function Jz($,Z){let X=$.find((z)=>z.id===Z.sectionId);if(!X)return;return(Z.itemId===void 0?X.content.actions:X.content.items?.find((z)=>z.id===Z.itemId)?.actions)?.find((z)=>z.id===Z.actionId)}function R1($){let Z=$.logger??s("commands"),X=x8($.redaction),J={logger:Z,redact:X},z=$.now??Date.now,G=$.extras??[],Q=$.replace??{},Y=E8.filter((j)=>!Q[j]);for(let j of E8)if(Q[j]&&$[j]!==void 0)throw Error(`the ${j} 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 H=new Set;for(let j of G){if($z.has(j.id)||H.has(j.id))throw Error(`extra section id ${j.id} is taken`);H.add(j.id)}async function W(j,q,U,L){try{return{id:j,slot:q,title:U.title,content:await U.build(L)}}catch(N){return Z.warn("command menu section failed to build",{command:$.command,section:j,error:X(N instanceof Error?N.message:String(N))}),{id:j,slot:q,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let q=B&&Y.length>0?await n9({store:B,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],U=[];for(let L of E8){let N=Q[L];if(N)U.push(await W(L,L,N,j));else{let K=q.find((F)=>F.slot===L);if(K)U.push(K)}}if($.cache)U.push(await W("cache","cache",$.cache,j));if($.diagnostics)U.push(await W("diagnostics","diagnostics",$.diagnostics,j));for(let L of G)U.push(await W(L.id,"extra",L,j));return U}return{command:$.command,async open(j){let q=r9(j,X);return l9($.command,$.title,await V(q),J)},async apply(j,q){let U=r9(q,X),L=async(M)=>d9($.command,$.title,await V(U),M,J),N=j.command===$.command?Jz(await V(U),j):void 0;if(!N)return L({ok:!1,code:"unavailable",text:"That action is no longer available."});let K=b8(N);if(K&&j.confirmed!==!0)return L({ok:!1,code:"needs-confirmation",text:K.message,needsConfirmation:!0});let F=Xz(N.knobs??[],j.values);if("problem"in F)return L({ok:!1,code:"invalid-input",text:F.problem});let C;try{let M=await N.run({values:F.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:U});C=typeof M==="string"?{ok:!0,text:M}:{ok:M.ok,text:M.text,...M.ok?{}:{code:M.code??"refused"}}}catch(M){let D=I$(M);Z.warn("command menu action failed",{command:$.command,section:j.sectionId,action:j.actionId,code:D.code,error:X(M instanceof Error?M.message:String(M))}),C={ok:!1,...D}}return L(C)}}}async function b$($,Z,X){let J=new Map,z=[];for(let Q of X){let Y=Q.label;for(let B=2;J.has(Y);B++)Y=`${Q.label} (${B})`;J.set(Y,Q.value),z.push(Y)}let G=await $.select(Z,z);return G===void 0?void 0:J.get(G)}function o9($,Z){return Z.length>0?`${$}
8
+ ${Z.join(`
9
+ `)}`:$}function p6($){return $.status?`${$.label} · ${$.status}`:$.label}function zz($){let Z=[...$.lines],X;for(let J of $.items){if(J.actions.length>0)continue;if(J.group!==void 0&&J.group!==X)Z.push(J.group);X=J.group,Z.push(J.group!==void 0?` ${p6(J)}`:p6(J))}return Z}function Gz($){let Z=$.detail?[$.detail]:[];for(let[X,J]of Object.entries($.facts??{}))Z.push(`${X}: ${String(J)}`);return o9(p6($),Z)}async function Qz($,Z){switch(Z.kind){case"choice":{let X=await b$($,Z.label,Z.choices.map((J)=>({label:J.value===Z.value?`${J.label} (current)`:J.label,value:J.value})));return X===void 0?void 0:{value:X}}case"toggle":{let X=await b$($,Z.label,[{label:Z.value?"On (current)":"On",value:!0},{label:Z.value?"Off":"Off (current)",value:!1}]);return X===void 0?void 0:{value:X}}case"number":{let X=Z.min!==void 0&&Z.max!==void 0?` (${Z.min}-${Z.max}${Z.required?"":", empty clears"})`:Z.required?"":" (empty clears)",J=await $.input(`${Z.label}${X}`,Z.value!==void 0?String(Z.value):void 0);if(J===void 0)return;let z=J.trim();if(z==="")return Z.required&&Z.value!==void 0?{value:Z.value}:{value:null};let G=Number(z);if(!Number.isFinite(G)){$.notify(`${Z.label} needs a number.`,"error");return}return{value:G}}case"text":{let X=await $.input(Z.label,Z.value??Z.placeholder);if(X===void 0)return;let J=X.trim();if(J==="")return Z.required&&Z.value!==void 0?{value:Z.value}:{value:null};return{value:J}}}}async function Yz($,Z){let X={};for(let J of Z.knobs){let z=await Qz($,J);if(!z)return;X[J.id]=z.value}return X}async function k8($,Z,X={}){let J={...X.sessionId!==void 0?{sessionId:X.sessionId}:{},notify:(G,Q)=>Z.notify(G,Q)},z=(await $.open(J)).menu;for(;;){let G=await b$(Z,z.title,z.sections.map((Q)=>({label:Q.lines[0]?`${Q.title}: ${Q.lines[0]}`:Q.title,value:Q.id})));if(G===void 0)return;for(;;){let Q=z.sections.find((U)=>U.id===G);if(!Q)break;let Y=[...Q.items.filter((U)=>U.actions.length>0).map((U)=>({label:p6(U),value:{kind:"item",item:U}})),...Q.actions.map((U)=>({label:U.label,value:{kind:"action",action:U}}))],B=zz(Q);if(Y.length===0&&B.length===0){Z.notify("Nothing to do here.");break}let H=await b$(Z,o9(Q.title,B),[...Y,{label:"Back",value:{kind:"back"}}]);if(!H||H.kind==="back")break;let W,V;if(H.kind==="item"){if(V=H.item,W=await b$(Z,Gz(V),V.actions.map((U)=>({label:U.label,value:U}))),!W)continue}else W=H.action;let j=await Yz(Z,W);if(!j)continue;if(W.confirm){if(!await Z.confirm(W.label,W.confirm.message)){Z.notify("Cancelled.");continue}}let q=await $.apply({command:z.command,sectionId:Q.id,...V?{itemId:V.id}:{},actionId:W.id,values:j,...W.confirm?{confirmed:!0}:{},...X.sessionId!==void 0?{sessionId:X.sessionId}:{}},J);Z.notify(q.text,q.ok?"info":"error"),z=q.menu}}}import{createHash as gQ,randomUUID as hQ}from"node:crypto";import{setTimeout as wQ}from"node:timers/promises";var Bz=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});import{createHash as Wz}from"node:crypto";var Hz=86400000,Vz=300000,jz=3600000,Uz=60000,qz=900000,Kz=300000;function f8($){return $ instanceof Error?$.message:String($)}function y8($){let Z=$?.status;if(typeof Z==="number")return Z===429||Z>=500;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.name==="TimeoutError"||$.message.includes("fetch failed")||"code"in $&&($.code==="ECONNRESET"||$.code==="ECONNREFUSED"||$.code==="ETIMEDOUT"||$.code==="UND_ERR_CONNECT_TIMEOUT")}function v8($){let Z=f8($),X=$?.status;if(typeof X==="number")return X===429||X>=500;if(!($ instanceof Error))return!1;let J=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||J==="ECONNRESET"||J==="ECONNREFUSED"||J==="ETIMEDOUT"||J==="UND_ERR_CONNECT_TIMEOUT"}function E$($){return Wz("sha256").update($).digest("hex")}function u6($){let Z=E$($.refreshToken),J=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,z,G=$.error?.retryAfter;if(typeof G==="number"&&G>0)z=G*1000;else if(y8($.error))z=Math.min(jz,Vz*2**Math.min(J-1,6));else z=Hz;return{message:f8($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:J,tokenHash:Z}}function W1($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===E$(Z)}function k$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function f$($){let X=($.previous?.retryCount??0)+1,J,z=$.error?.retryAfter;if(typeof z==="number"&&z>0)J=z*1000;else if(v8($.error))J=Math.min(qz,Uz*2**Math.min(X-1,6));else J=Kz;return{message:f8($.error),checkedAt:$.now,nextRetryAt:$.now+J,retryCount:X}}function $$($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function g8($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let X=Date.parse($);if(Number.isFinite(X)){let J=Math.ceil((X-Date.now())/1000);return J>0?J:void 0}return}function Dz($){return $==="chatgptaccountid"||$==="email"||$==="orgname"||$==="organizationname"}var t9=y0({extraSecretKeys:Dz}),Mj=t9.redact,e9=t9.redactStrings;import{createServer as $Z}from"node:http";import{setTimeout as Nz}from"node:timers/promises";var c6="app_EMoamEEZ73f0CkXaXp7hrann",x1="https://auth.openai.com",v$=1455,Mz=3000,Lz="cortexkit-opencode-openai-auth";function XZ($){return`${Lz}/${$}`}var JZ="main",Fz=`"${JZ}" is a reserved account id; choose a different label.`;function zZ($){let Z=new Uint8Array($),X=String.fromCharCode(...Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Pz(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[J%66]).join(""),X=zZ(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function Z$($){if($.length>16384)return;let Z=$.split(".");if(Z.length!==3)return;let X=Z[1];if(!X||X.length>8192)return;try{return JSON.parse(Buffer.from(X,"base64url").toString())}catch{return}}function X$($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let X=$["https://api.openai.com/auth"];if(X&&typeof X==="object"&&!Array.isArray(X)&&typeof X.chatgpt_account_id==="string"&&X.chatgpt_account_id.length>0)return X.chatgpt_account_id;let J=$.organizations;if(Array.isArray(J)){let z=J[0];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.id==="string"&&z.id.length>0)return z.id}return}function g$($){if($.id_token){let Z=Z$($.id_token),X=Z&&X$(Z);if(X)return X}if($.access_token){let Z=Z$($.access_token);return Z?X$(Z):void 0}return}function Oz($){return typeof $==="string"&&$.toLowerCase()===JZ}function h8($){if(Oz($))throw Error(Fz);return $}function _z($,Z,X){let J=new URLSearchParams({response_type:"code",client_id:c6,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:X,originator:"opencode"});return`${x1}/oauth/authorize?${J.toString()}`}async function Cz($,Z,X){let J=await fetch(`${x1}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:c6,code_verifier:X.verifier}).toString()});if(!J.ok)throw Error(`Token exchange failed: ${J.status}`);return await J.json()}function Tz($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var Az=`<!doctype html>
4
10
  <html>
5
11
  <head>
6
12
  <title>CortexKit OpenAI Auth - Authorization Successful</title>
@@ -40,7 +46,7 @@ var I3=Object.defineProperty;var R3=($)=>$;function A3($,Z){this[$]=R3.bind(null
40
46
  setTimeout(() => window.close(), 2000)
41
47
  </script>
42
48
  </body>
43
- </html>`,c0=($)=>`<!doctype html>
49
+ </html>`,l6=($)=>`<!doctype html>
44
50
  <html>
45
51
  <head>
46
52
  <title>CortexKit OpenAI Auth - Authorization Failed</title>
@@ -83,134 +89,34 @@ var I3=Object.defineProperty;var R3=($)=>$;function A3($,Z){this[$]=R3.bind(null
83
89
  <div class="container">
84
90
  <h1>Authorization Failed</h1>
85
91
  <p>An error occurred during authorization.</p>
86
- <div class="error">${W4($)}</div>
92
+ <div class="error">${Tz($)}</div>
87
93
  </div>
88
94
  </body>
89
- </html>`,b0,C0,$0=new Map;function W0(){return $0.size}function j0($){if($0.delete($),W0()===0)B0()}async function V4(){let $=`http://localhost:${T0}/auth/callback`;if(b0)return{port:T0,redirectUri:$};if(C0)return C0;C0=(async()=>{let Z=e3((z,X)=>{let J=new URL(z.url||"/",`http://127.0.0.1:${T0}`);if(J.pathname==="/auth/callback"){let G=J.searchParams.get("code"),Q=J.searchParams.get("state"),Y=J.searchParams.get("error"),W=J.searchParams.get("error_description");if(Y){let V=W||Y;if(Q){let j=$0.get(Q);if(j)j.reject(Error(V)),j0(Q);else if(W0()===0)B0()}else if(W0()===0)B0();X.writeHead(200,{"Content-Type":"text/html"}),X.end(c0(V));return}if(!Q){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Missing state parameter"));return}if(!G){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Missing authorization code"));return}let B=$0.get(Q);if(!B){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Unknown state — authorization may have expired"));return}j0(Q),Y4(G,$,B.pkce).then((V)=>B.resolve(V)).catch((V)=>B.reject(V)),X.writeHead(200,{"Content-Type":"text/html"}),X.end(B4);return}if(J.pathname==="/cancel"){let G=J.searchParams.get("state"),Q=G?[G]:[...$0.keys()];X.writeHead(200),X.end("Login cancelled");for(let Y of Q){let W=$0.get(Y);if(!W)continue;W.reject(Error("Login cancelled")),j0(Y)}if(W0()===0)B0();return}X.writeHead(404),X.end("Not found")});return await new Promise((z,X)=>{Z.once("error",X),Z.listen(T0,"127.0.0.1",()=>{Z.off("error",X),z()})}),b0=Z,{port:T0,redirectUri:$}})();try{return await C0}finally{C0=void 0}}function B0(){if(b0){let $=b0;b0=void 0,$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}}function j4($,Z,z=300000,X){return new Promise((J,G)=>{if(X?.aborted){j0(Z),G(Error("Login cancelled"));return}let Q=setTimeout(()=>{if($0.get(Z))j0(Z),G(Error("OAuth callback timeout — authorization took too long"))},z),Y=()=>{if(clearTimeout(Q),$0.get(Z))j0(Z),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",Y);$0.set(Z,{pkce:$,state:Z,resolve:(W)=>{if(clearTimeout(Q),X)X.removeEventListener("abort",Y);J(W)},reject:(W)=>{if(clearTimeout(Q),X)X.removeEventListener("abort",Y);G(W)}})})}async function q4($){let Z=await fetch(`${V0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y1($)},body:JSON.stringify({client_id:s0})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${V0}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function H4($,Z,z){let X=Math.max(parseInt($.interval,10)||5,1)*1000,J=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(J)&&J>0?J*1000:900000,Q=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-Q>G)throw Error("Device authorization expired");let Y=await fetch(`${V0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y1(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(Y.ok){let V=await Y.json(),j=await fetch(`${V0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:V.authorization_code,redirect_uri:`${V0}/deviceauth/callback`,client_id:s0,code_verifier:V.code_verifier}).toString()});if(!j.ok)throw Error(`Token exchange failed: ${j.status}`);return await j.json()}if(Y.status!==403&&Y.status!==404)throw Error(`Device authorization failed: ${Y.status}`);let W=G-(Date.now()-Q);if(W<=0)throw Error("Device authorization expired");let B=Math.min(X+Z4,W);try{await $4(B,void 0,{signal:z})}catch(V){if(V instanceof Error&&V.name==="AbortError")throw Error("Device authorization cancelled");throw V}}}function m1($,Z){let z=-1;if(Z.accountId)z=$.findIndex((X)=>X.accountId&&X.accountId===Z.accountId);if(z<0)z=$.findIndex((X)=>X.id===Z.id);if(z<0&&Z.label&&!Z.accountId)z=$.findIndex((X)=>X.label===Z.label);if(z>=0)return $[z]={...$[z],...Z,addedAt:$[z]?.addedAt??Z.addedAt},z;return $.push(Z),$.length-1}async function g1($){let{label:Z,headless:z=!1,signal:X,version:J}=$;if(S8(Z),z){let{deviceData:V,url:j,instructions:q}=await q4(J),K=(async()=>{let L=await H4(V,J,X),U=Date.now(),D=f8(L);return{id:S8(Z||D||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:L.access_token,refresh:L.refresh_token,expires:U+(L.expires_in??3600)*1000,enabled:!0,addedAt:U,lastUsed:U,lastRefreshedAt:U,accountId:D}})();return{url:j,instructions:q,completion:K}}let{redirectUri:G}=await V4(),Q=await J4(),Y=h1(crypto.getRandomValues(new Uint8Array(32)).buffer),W=Q4(G,Q,Y),B=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let V=await j4(Q,Y,void 0,X),j=Date.now(),q=f8(V);return{id:S8(Z||q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:j+(V.expires_in??3600)*1000,enabled:!0,addedAt:j,lastUsed:j,lastRefreshedAt:j,accountId:q}}finally{j0(Y)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:B}}var N4=d("custody");var U4="claustrum-tombstone:v1:",D4=Symbol("custody-refuse"),P4=Symbol("custody-excluded");function y8($){return`${U4}${$}`}function p1($,Z){if($.corrupt)return!1;return $.refresh===y8(Z)}var E8=3600000;class O4{#z;#J=new Map;#B=new Map;#Y=new Map;#G=new Map;#$=new Set;#X=new Map;#Q=new Map;#W;#Z=!1;constructor($){this.#z=$.connector({connectionFile:"",handshakeTimeoutMs:5000}),this.#W=$.now??Date.now}async peek($){return this.#J.get($)}async peekMetadata($){let Z=this.#J.get($);if(!Z)return;return{recordVersion:Z.recordVersion,expiresAtMs:Z.expiresAtMs}}isBlocked($){return this.#$.has($)}isReauth($,Z=this.#W()){let z=this.#X.get($);if(z===void 0)return!1;return z>Z}markVaultSuccess($){this.#X.delete($),this.#Q.delete($),this.#Y.delete($)}async get($,Z,z={}){if(this.#Z)throw Error("Claustrum cache is closed");if(!z.force){let Y=this.#J.get($);if(Y)return Y}let X=!!z.force,J=this.#B.get($);if(J&&J.force===X)return J.promise;let G=this.#V($,Z),Q={force:X,promise:G.finally(()=>{this.#B.delete($)})};return this.#B.set($,Q),Q.promise}async#V($,Z){let z=await this.#z,X=8;for(let J=0;J<8;J++){let G=await z.getCredential($,Z),Q=G.expiresAtMs??Number.MAX_SAFE_INTEGER;if(!this.#G.get($)?.has(G.recordVersion)){let W={payload:{access:G.material},recordVersion:G.recordVersion,expiresAtMs:Q,servedAccountId:G.accountId};return this.#J.set($,W),this.#$.delete($),this.#G.delete($),W}await L4(5*(J+1))}throw Error("custody credential rejected version after retries")}async reportAuthFailure($){if(this.#Z)return;let{handle:Z,recordVersion:z,providerStatus:X}=$,J=this.#W(),G=this.#Y.get(Z);if(G!==void 0&&G>=z)return;let Q=this.#Q.get(Z);if(Q&&Q.count>=2)if(Q.reauthUntil!==void 0&&J>=Q.reauthUntil)this.#Q.delete(Z),this.#X.delete(Z),this.#Y.delete(Z),Q=void 0;else return;let Y=await this.#z;try{await Y.reportAuthFailure({handle:Z,providerStatus:X,recordVersion:z,reporterSource:"direct"}),this.#Y.set(Z,z),this.#$.add(Z);let W=this.#Q.get(Z);if(this.#Q.set(Z,{count:(W?.count??0)+1,firstReportedAt:W?.firstReportedAt??J,reauthUntil:(W?.count??0)+1>=2?J+E8:void 0}),(W?.count??0)+1>=2)this.#X.set(Z,J+E8),N4.warn("custody report bound reached; entering reauth",{reauthMs:E8})}finally{let W=this.#J.get(Z);if(W&&W.recordVersion===z)this.#J.delete(Z);let B=this.#G.get(Z);if(!B)B=new Set,this.#G.set(Z,B);B.add(z)}}close(){if(this.#Z)return;this.#Z=!0,this.#J.clear(),this.#B.clear(),this.#Y.clear(),this.#G.clear(),this.#$.clear(),this.#X.clear(),this.#Q.clear(),this.#z.then(($)=>$.close()).catch(()=>{})}}class v8 extends Error{code="CUSTODY_TOMBSTONED";status=503;isRefreshError=!0;constructor($){super(`custody tombstoned: ${y8($)}`);this.name="CustodyTombstoneRefreshError"}}function h8($,Z){if(p1($,Z))throw new v8(Z)}import{basename as M4,dirname as _4,join as x4}from"node:path";var n0="openai-auth.json",u1="openai-auth-state.json";function g8($){return M4($)===n0?x4(_4($),u1):`${$}.state.json`}function p8($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var T4=d("quota");var C4="https://chatgpt.com/backend-api/wham/usage";async function d8($){let Z=$.logger??T4,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let J=await $.fetchImpl(C4,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!J.ok){let Y=S1(J.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${J.status}`),{status:J.status,retryAfter:Y})}let{normalizeWham:G}=await Promise.resolve().then(() => (l8(),a1)),Q=G(await J.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:J.status,elapsedMs:Date.now()-X}),Q}catch(J){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof J?.status==="number"?J.status:"error",elapsedMs:Date.now()-X,error:p8(J)}),J}}import{createHash as v4}from"node:crypto";import{randomUUID as i8}from"node:crypto";import{mkdir as t1,readFile as c8,rename as b4,rm as D0,stat as o1,writeFile as a0}from"node:fs/promises";import{dirname as S4,join as r1}from"node:path";var k4=globalThis.setTimeout.bind(globalThis),w4=globalThis.clearTimeout.bind(globalThis);function f4($){let Z=$?.code;return Z==="ENOENT"||Z==="EINVAL"||Z==="ENOTDIR"}async function k0($){let Z=`${$.path}.${$.name}.lock`,z=r1(Z,"owner.json"),X=i8(),J=$.now??Date.now,G=null,Q=!1,Y=null,W=`${Z}.evicting`,B=r1(W,"owner.json"),V=i8(),j=5000,q=8;async function K(){try{return JSON.parse(await c8(Z,"utf8"))}catch(O){if(O.code!=="EISDIR")throw O;return JSON.parse(await c8(z,"utf8"))}}async function L(){await a0(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
90
- `,{encoding:"utf8",mode:384})}async function U(){try{return await a0(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
91
- `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(O){let R=O.code;if(R==="EEXIST"||R==="EISDIR")return!1;if(R==="ENOENT"){await t1(S4(Z),{recursive:!0});try{return await a0(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
92
- `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(T){let d0=T.code;if(d0==="EEXIST"||d0==="EISDIR")return!1;throw T}}throw O}}async function D(){await new Promise((O)=>setTimeout(O,Math.floor(Math.random()*4)))}async function P(){try{let O=await K();return Number(O?.expiresAt)>J()}catch{try{return(await o1(Z)).mtimeMs+$.ttlMs>J()}catch{return!1}}}async function A(){try{return JSON.parse(await c8(B,"utf8"))?.ownerId===V}catch{return!1}}async function x0(){if(await A())await D0(W,{recursive:!0,force:!0}).catch(()=>{})}async function _8(){await t1(W);try{await a0(B,`${JSON.stringify({ownerId:V,createdAt:J()})}
93
- `,{encoding:"utf8",mode:384,flag:"wx"})}catch(O){if(f4(O))return!1;throw await x0(),O}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function N0(){let O;try{O=await o1(W)}catch(T){if(T.code==="ENOENT")return"missing";throw T}if(O.mtimeMs+j>J())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let R=`${W}.${i8()}`;try{await b4(W,R)}catch(T){if(T.code==="ENOENT")return"missing";throw T}if($.onStep)await $.onStep("stale-marker-claimed");return await D0(R,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function k(O){try{if(!await _8())return!1}catch(R){if(R.code==="EEXIST")return!1;throw R}try{await O()}finally{await x0()}return!0}async function x3(){for(let O=0;O<q;O++){if($.onStep)await $.onStep("relinquish-read");let R;try{R=await K()}catch{return}if(R?.ownerId!==X)return;try{await D0(Z,{recursive:!0,force:!0});return}catch{await D()}}}function A1(){if(!$.renew||Q)return;let O=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=k4(()=>{let R=(async()=>{let T=!Q;try{if(!await k(async()=>{let T1=await K(),F3=J();if(Q||T1?.ownerId!==X){T=!1;return}if(Number(T1?.expiresAt)<=F3){T=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q){T=!1;return}if(!await A())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q){T=!1;return}if(!await A())return;if($.onStep)await $.onStep("renewal-write-ready");if(await L(),!await A()){T=!1,await x3();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch{}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(T&&!Q)A1()}})();Y=R,R.finally(()=>{if(Y===R)Y=null})},O),"unref"in G)G.unref()}let Y0=await U();if(!Y0)for(let O=0;O<q;O++){if(Y0=await U(),Y0)break;if(await P())return null;try{if(!await _8()){await D();continue}}catch(R){if(R.code!=="EEXIST")throw R;if(await N0()==="fresh")return null;await D();continue}try{if(await P())return null;if(!await A())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await A())return null;if(await D0(Z,{recursive:!0,force:!0}).catch(()=>{}),!await A())return null;if(Y0=await U(),!Y0)return null;if(!await A())return await D0(Z,{recursive:!0,force:!0}).catch(()=>{}),Y0=!1,null;break}finally{await x0()}}if(!Y0)return null;return A1(),{release:async()=>{if(Q=!0,G)w4(G),G=null;await Y;for(let O=0;O<q;O++){try{if(await k(async()=>{if((await K())?.ownerId!==X)return;if($.onStep)await $.onStep("release-owner-confirmed");if(!await A())return;await D0(Z,{recursive:!0,force:!0}).catch(()=>{})}))return;await N0()}catch{return}await D()}}}}var h4=globalThis.setTimeout,m4=5;function w0($){let Z=$?.quota?.checkIntervalMinutes??m4;return Math.max(1,Z)*60000}function g4($){return $?.quota?.enabled!==!1}function p4($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function e1($,Z,z){if(!g4(Z))return z+w0(Z);let X=p4(Z),J=[];for(let G of["primary","secondary"]){let Q=$?.[G];if(!Q)continue;if(Q.remainingPercent>=X[G])continue;let Y=Q.resetsAt?Date.parse(Q.resetsAt):Number.NaN;if(!Number.isFinite(Y)||Y<=z)return z+w0(Z);J.push(Y)}if(!J.length)return z+w0(Z);return Math.min(...J)+60000}function u4($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function l4($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function l($){return v4("sha256").update($).digest("hex").slice(0,16)}class n{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;configPath;constructor($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath,this.now=$.now??Date.now,this.fetchQuotaFn=$.fetchQuotaFn,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.seedMainFromStorage($.storage),this.seedMainBackoffFromStorage($.storage)}getMain($){if($&&this.main&&this.mainTokenFp&&this.mainTokenFp!==l($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let z=this.fallbacks.get($)??null;if(!Z||!z)return z;if(this.fallbackTokenFps.get($)!==l(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!$$(Z.quota))return;if(this.mainTokenFp=l($),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=Z,s8(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let z=this.fallbacks.get($)??null;if(Z&&z?.accountId&&z.accountId!==Z)return null;return z}setFallback($,Z,z,X=!1,J){if(!X&&!$$(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(J&&G&&J!==G)this.clearRateLimited($);let Q=J??G;if(this.fallbacks.set($,{...Z,accountId:Q}),z)this.fallbackTokenFps.set($,l(z));else this.fallbackTokenFps.delete($);if(s8(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let z=this.rateLimitedUntilMap.get($);if(z!==void 0&&z>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=l($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let z=n.fallbackInflightKey($,Z),X=this.inflightFallbacks.get(z);if(X)return X;if(this.isFallbackBackedOff($,Z)){let G=this.getFallback($,Z);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let J=this._fetchFallback($,Z);return this.inflightFallbacks.set(z,J),J}async refreshAllFallbacks($){let Z=this.now();for(let z of $){if(z.enabled===!1)continue;if(h8(z,"openai"),!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&Z<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground($){let Z=l($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale($,Z){let z=this.getFallback($,Z);if(!z)return!0;return this.now()>=z.refreshAfter}shouldRefreshOnRequestCount($){let Z=l4(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($){return this.isMainStale()||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let z=u4($);if(!z)return;let X=Z?l(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let J={quota:z.quota,refreshAfter:e1(z.quota,$,z.checkedAt),checkedAt:z.checkedAt};if(this.main&&this.main.checkedAt>=J.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=J,this.mainTokenFp=z.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&F0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=w0(this.storage);for(let z of $){if(z.enabled===!1)continue;if(!z.quota)continue;let X=Math.max(z.quota.primary?.checkedAt??0,z.quota.secondary?.checkedAt??0);if(X<=0)continue;let J=this.getFallback(z.id,z.access);if(J&&J.checkedAt>=X)continue;this.setFallback(z.id,{quota:z.quota,refreshAfter:X+Z,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return F0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==l(Z))return!1}return F0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,l(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let X=this.now()-this.lastApiCallAt;if(X<n.API_CALL_GAP_MS)await new Promise((J)=>{let G=h4(J,n.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},z=this.apiGate.then(Z,Z);return this.apiGate=z.catch(()=>{}),z}async _fetchMain($){let Z=l($);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let z=await k0({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!z){let X=this.main;if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=this.now(),J=await this._fetchQuota($),G=this.now();if(this.mainTokenFp=l($),this.main={quota:J,refreshAfter:e1(J,this.storage,G),checkedAt:G},s8(J))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(J,G,this.mainTokenFp,X),J}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback($,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff($,Z)){let X=this.getFallback($,Z);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let z=await k0({name:n.quotaLockName($),ttlMs:30000,path:this.configPath});if(!z){let X=this.getFallback($,Z);if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=await this._fetchQuota(Z),J=this.now();return this.setFallback($,{quota:X,refreshAfter:J+w0(this.storage),checkedAt:J},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError($,Z,z),z}finally{this.inflightFallbacks.delete(n.fallbackInflightKey($,Z))}})}async _fetchQuota($){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:$,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError($){return $?.status===401}_handleMainFetchError($){if(n.isAuthError($))return;this.mainLastApiError=i0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(n.isAuthError(z))return;let X=l(Z),J=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,i0({error:z,now:this.now(),previous:J})),this.fallbackErrorTokenFps.set($,X)}}function $$($){return Boolean($.primary||$.secondary)}function s8($){let{primary:Z,secondary:z}=$;if(!Z&&!z)return!1;if(Z&&Z.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{readFile as X6}from"node:fs/promises";var K5=d("refresh"),J$=d("accounts"),n4=1e4,a4=15000,n8=50;function m8($){return $.type==="oauth"&&$.corrupt!==!0}function t4($){let Z=$?.trim();if(!Z)return!1;try{let z=new URL(Z);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}function N($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var o4=new Set(["__proto__","constructor","prototype"]);function i($){return $.length>0&&!o4.has($)}function t0($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():c4(),label:typeof $.label==="string"?$.label:void 0,enabled:typeof $.enabled==="boolean"?$.enabled:void 0,addedAt:typeof $.addedAt==="number"?$.addedAt:void 0,lastUsed:typeof $.lastUsed==="number"?$.lastUsed:void 0,accountId:typeof $.accountId==="string"?$.accountId:void 0}}function Z$($){if(!N($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let z=Number($.nextRetryAt),X=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function r4($){if(!N($))return;let Z={};for(let J of["primary","secondary"]){let G=$[J];if(!N(G))continue;let Q=Number(G.usedPercent),Y=Number(G.remainingPercent),W=Number(G.checkedAt);if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(W))continue;let B=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[J]={usedPercent:Q,remainingPercent:Y,checkedAt:W,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(B)&&B>0?{windowMinutes:B}:{}}}for(let J of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[J]==="number"?$[J]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[J]=G}let z=$.spendControl;if(N(z)){let J=Number(z.limit),G=Number(z.used),Q=Number(z.remaining),Y=Number(z.usedPercent),W=Number(z.remainingPercent);if(Number.isFinite(J)&&Number.isFinite(G)&&Number.isFinite(Q)&&Number.isFinite(Y)&&Number.isFinite(W)&&typeof z.reached==="boolean")Z.spendControl={limit:J,used:G,remaining:Q,usedPercent:Y,remainingPercent:W,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=$.credits;if(N(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&typeof X.overageLimitReached==="boolean"){let J=Number(X.balance);Z.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,overageLimitReached:X.overageLimitReached,...Number.isFinite(J)?{balance:J}:{}}}return Object.keys(Z).length?Z:void 0}function e4($){if(!N($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!t4(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...t0($),type:"api",apiKey:z||void 0,baseURL:Z,authHeader:X}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...t0($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...t0($),type:"oauth",corrupt:!0}}return{...t0($),type:"oauth",access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:Z$($.lastRefreshError),lastQuotaRefreshError:Z$($.lastQuotaRefreshError),quota:r4($.quota)}}function $6($){if(!N($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!i(z)||!N(X))continue;let J={};if(N(X.inFlight))J.inFlight={...X.inFlight};if(N(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))J.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...N(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))J.cooldownUntil=X.cooldownUntil;if(Object.keys(J).length>0)Z[z]=J}return Object.keys(Z).length>0?Z:void 0}var z$=new Set;function G$($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(z$.has(Z))return;z$.add(Z),J$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function Q$($){if(!N($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(e4).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let Q of Z)if(N(Q)&&typeof Q.id==="string"&&Q.id.trim())X.add(Q.id.trim());let J=new Set(z.map((Q)=>Q.id)),G=[];for(let Q of X)if(!J.has(Q))G.push(Q);G$(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:N($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:N($.refresh)?$.refresh:void 0,quota:N($.quota)?$.quota:void 0,reset:$6($.reset),dump:N($.dump)?$.dump:void 0,costZeroing:N($.costZeroing)?$.costZeroing:void 0,killswitch:N($.killswitch)?$.killswitch:void 0,logging:N($.logging)?$.logging:void 0,cachekeep:N($.cachekeep)?$.cachekeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,claustrum:Z6($.claustrum),accounts:z}}function Z6($){if(!N($))return;let Z=$.mode==="claustrum"?"claustrum":"local",z=z6($.transition),X=Array.isArray($.rowHistory)?$.rowHistory.filter((J)=>typeof J==="string"):void 0;return{mode:Z,transition:z,rowHistory:X}}function z6($){if(!N($)||!N($.fingerprints))return;if(typeof $.manifestRevision!=="string"||typeof $.storeGeneration!=="string"||!N($.fingerprints.fallbacks))return;let Z=Object.fromEntries(Object.entries($.fingerprints.fallbacks).filter((z)=>typeof z[1]==="string"));return{manifestRevision:$.manifestRevision,storeGeneration:$.storeGeneration,fingerprints:{main:typeof $.fingerprints.main==="string"?$.fingerprints.main:void 0,fallbacks:Z}}}async function f0($){try{return{exists:!0,value:JSON.parse(await X6($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function J0($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function Y$($){return(await J6($)).roster}async function J6($){let Z;try{Z=(await f0($)).value}catch{return{roster:null,mode:"claustrum"}}return{roster:a8(Z),mode:f(N(Z)?Z:void 0)}}function W$($,Z){if(!N($))return $;let z=N(Z)?Z:{},X=N(z.main)?z.main:void 0,J=N(z.accounts)?z.accounts:{},G=N($.quota)?$.quota:{},Q=N($.refresh)?$.refresh:{},Y=X??G,W=X??Q,V=Array.isArray($.accounts)?$.accounts.map((j)=>{if(!N(j))return j;let q=typeof j.id==="string"&&N(J[j.id])?J[j.id]:{};return{...j,...q}}):void 0;return V$({...$,refresh:J0({...Q,mainLastRefreshError:W.lastRefreshError,mainRefreshLeaseId:W.refreshLeaseId,mainRefreshLeaseUntil:W.refreshLeaseUntil,mainRefreshLeaseTokenHash:W.refreshLeaseTokenHash}),quota:J0({...G,mainQuota:Y.quota,mainQuotaCheckedAt:Y.quotaCheckedAt,mainQuotaToken:Y.quotaToken,mainLastQuotaApiError:Y.lastQuotaApiError}),accounts:V})}async function B$($){let Z=await f0($.configPath);if(!Z.exists)return null;let z=await f0($.statePath);return Q$(W$(Z.value,z.value))}function V$($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function G6($){return J0({id:$.id,label:$.label,type:$.type,corrupt:$.type==="oauth"&&$.corrupt===!0?!0:void 0,enabled:$.enabled,addedAt:$.addedAt,accountId:$.accountId,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function Q6($){if($.type==="api")return J0({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return J0({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function Y6($){let Z=$.refresh?J0({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?J0({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return V$({version:1,main:$.main,routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:z,reset:$.reset,dump:$.dump,costZeroing:$.costZeroing,killswitch:$.killswitch,logging:$.logging,cachekeep:$.cachekeep,mainAccountId:$.mainAccountId,...$.claustrum!==void 0?{claustrum:{mode:$.claustrum.mode??"local",...$.claustrum.transition?{transition:$.claustrum.transition}:{},...$.claustrum.rowHistory?{rowHistory:$.claustrum.rowHistory}:{}}}:{},accounts:$.accounts.map(G6)})}async function X$($,Z=!1){let z=Date.now(),X=z+a4,J=0;while(Date.now()<=X){J++;let Y=await k0({name:"save",ttlMs:n4,path:$,renew:Z});if(Y)return Y;let W=X-Date.now();if(W<=0)break;await s4(Math.min(n8+H6(n8),W))}let G=Date.now()-z,Q=Math.round(G/Math.max(1,J));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${J} attempts, ~${Q}ms apart; retry interval is ${n8}ms). A gap near the retry interval means lock contention; a much larger one means this process's event loop was saturated and the wait expired without getting scheduled.`)}function f($){return $?.claustrum?.mode==="claustrum"?"claustrum":"local"}function W6($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,Q6(z)]));return{version:1,main:J0({quota:$.quota?.mainQuota,quotaCheckedAt:$.quota?.mainQuotaCheckedAt,quotaToken:$.quota?.mainQuotaToken,lastQuotaApiError:$.quota?.mainLastQuotaApiError,lastRefreshError:$.refresh?.mainLastRefreshError,refreshLeaseId:$.refresh?.mainRefreshLeaseId,refreshLeaseUntil:$.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:$.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}function a8($){if(!N($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!N(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function B6($,Z,z,X){if(!N($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let J=[],G=[];for(let Q of Z){if(z.has(Q))continue;if(X.has(Q))continue;let Y=$.accounts.find((W)=>N(W)&&typeof W.id==="string"&&W.id.trim()===Q);if(!Y)continue;J.push(Y),G.push(Q)}return{preservedRawEntries:J,preservedIds:G}}function V6($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!N(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function j6($,Z,z){let X=a8($);if(X===null)return[];let{preservedRawEntries:J,preservedIds:G}=B6($,X,Z,z);return G$(G),J}async function G0($,Z,z={}){let{configPath:X,statePath:J}=Z,G=await X$(X);try{let Q=await X$(J);try{let Y=await f0(X),W=await f0(J),B=(Y.exists?Q$(W$(Y.value,W.value)):null)??q6(),V=new Set(B.accounts.map((k)=>k.id)),j=a8(Y.value)??new Set,q=$(B,{rawRosterIds:[...j],loadedRosterIds:[...V]})??B,K=new Set(q.accounts.map((k)=>k.id)),L=[...V].filter((k)=>!K.has(k));if(L.length>0)q.claustrum={...q.claustrum,mode:q.claustrum?.mode??"local",rowHistory:[...new Set([...q.claustrum?.rowHistory??[],...L])]};let U=new Set(z.allowDrop??[]),D=j6(Y.value,V,U),P=Y6(q),A=new Set((Array.isArray(P.accounts)?P.accounts:[]).map((k)=>N(k)&&typeof k.id==="string"?k.id.trim():"").filter(Boolean)),x0=D.filter((k)=>{if(!N(k))return!1;if(typeof k.id!=="string")return!1;return!A.has(k.id.trim())}),N0={...N(Y.value)?Y.value:{},...P,accounts:[...Array.isArray(P.accounts)?P.accounts:[],...x0]};return await x8(X,N0),await x8(J,W6(q)),J$.debug("account config written",{accountCount:N0.accounts.length,accountIds:V6(N0.accounts)}),q}finally{await Q.release()}}finally{await G.release()}}function q6(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function H6($){return Math.floor(Math.random()*($+1))}var N5=globalThis.setTimeout.bind(globalThis),U5=globalThis.clearTimeout.bind(globalThis);var t8="/backend-api/wham/rate-limit-reset-credits",K6=`https://chatgpt.com${t8}`,L$=`${t8}/consume`,L6=`https://chatgpt.com${L$}`,N6=300000,U6=60000,D6=15000,P6=60000;function o0($){return{configPath:$.configPath,statePath:$.statePath}}class c extends Error{kind;cooldownUntil;constructor($,Z,z){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=z}}class q0 extends Error{kind;status;constructor($,Z,z){super(Z);this.name="ResetCreditError",this.kind=$,this.status=z}}function N$($,Z,z){return{authorization:`Bearer ${$}`,...z?{"chatgpt-account-id":z}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function r0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U$($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function o8($){if(!r0($)||typeof $.redeemRequestId!=="string"||$.redeemRequestId.length===0||typeof $.creditId!=="string"||$.creditId.length===0||typeof $.startedAt!=="number"||!Number.isFinite($.startedAt))return;return{redeemRequestId:$.redeemRequestId,creditId:$.creditId,startedAt:$.startedAt}}function D$($){return Boolean($&&Object.hasOwn($,"inFlight"))}function P$($,Z){return Z-$.startedAt<N6}function e0($,Z){if(!i(Z))return;return $.reset?.[Z]}function O$($){if(!$.reset)$.reset=Object.create(null);return $.reset}function M$($,Z,z){if(!i(Z))return;let X=O$($),J=X[Z]??{},G=J.lastOutcome;delete J.inFlight,J.lastOutcome={code:"ambiguous_local",at:z,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[Z]=J}function _$($,Z){let z=U$($),X=o8($?.inFlight);if(D$($)&&!X)return{kind:"corrupt",beforeState:z};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:z,cooldownUntil:$.cooldownUntil};if(X&&P$(X,Z))return{kind:"claim",beforeState:z,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:z,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:z}}async function O6($,Z){if(!i(Z))return{kind:"fresh",beforeState:void 0};let z=await $.loadAccountsFn(o0($));return _$(z?e0(z,Z):void 0,$.now())}async function M6($,Z){let z;if(await $.mutateAccountsFn((X)=>{let J=$.now(),G=e0(X,Z);if(z=_$(G,J),z.kind==="corrupt")M$(X,Z,J);return X},o0($)),!z)throw Error("corrupt reset state mutation did not run");return z}async function _6($,Z,z){if(!i(Z))return{kind:"fresh",beforeState:void 0};let X;if(await $.mutateAccountsFn((J)=>{let G=$.now(),Q=e0(J,Z),Y=U$(Q),W=o8(Q?.inFlight);if(D$(Q)&&!W)return M$(J,Z,G),X={kind:"corrupt",beforeState:Y},J;if(Q?.cooldownUntil!==void 0&&Q.cooldownUntil>G)return X={kind:"cooldown",beforeState:Y,cooldownUntil:Q.cooldownUntil},J;if(W&&P$(W,G))return X={kind:"claim",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},J;if(W)return X={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},J;let B=$8(z);if(!B)return X={kind:"fresh",beforeState:Y},J;let V={redeemRequestId:$.randomUUID(),creditId:B.id,startedAt:G},j=O$(J);return j[Z]={...Q,inFlight:V},X={kind:"claim",beforeState:Y,claim:{inFlight:V,selectedCredit:B}},J},o0($)),!X)throw Error("reset claim mutation did not run");return X}async function x6($,Z,z,X){if(!i(Z))return;if(!$1(X.kind))return;await $.mutateAccountsFn((J)=>{let G=e0(J,Z),Q=o8(G?.inFlight);if(!G||!Q||Q.redeemRequestId!==z.redeemRequestId||Q.creditId!==z.creditId)return J;let Y=$.now();if(delete G.inFlight,G.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")G.cooldownUntil=Y+P6;else delete G.cooldownUntil;return J},o0($))}function E0($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return!Number.isFinite(z)||z>Z}function r8($,Z,z){if(!(Z||E0($.primary,z)||E0($.secondary,z)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function j$($,Z){let z=$[Z];if(z===void 0||z===null)return;return typeof z==="string"?z:null}function F6($){if(!r0($))return;let Z=j$($,"granted_at"),z=j$($,"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||z===null)return;return{id:$.id,status:$.status,...Z===void 0?{}:{grantedAt:Z},expiresAt:$.expires_at,...z===void 0?{}:{resetType:z},isSupportedByPlan:$.is_supported_by_plan}}async function e8($,Z,z){let X;try{X=await $(K6,{method:"GET",headers:N$(Z,t8,z),signal:AbortSignal.timeout(D6)})}catch{throw new q0("http_error","reset credit list request failed")}if(!X.ok)throw new q0("http_error",`reset credit list request failed: ${X.status}`,X.status);let J;try{J=await X.json()}catch{throw new q0("invalid_response","reset credit list response was not valid JSON",X.status)}if(!r0(J))throw new q0("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(J.credits)?J.credits:[]).flatMap((Q)=>{let Y=F6(Q);return Y===void 0?[]:[Y]}),availableCount:typeof J.available_count==="number"&&Number.isFinite(J.available_count)?J.available_count:void 0}}function $8($){return[...$].filter(x$).sort((Z,z)=>Date.parse(Z.expiresAt)-Date.parse(z.expiresAt))[0]}function x$($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function F$($){return $.filter(x$).length}function $1($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function I6($,Z,z,X,J){let G;try{G=await $(L6,{method:"POST",headers:{...N$(Z,L$,z),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:J,credit_id:X}),signal:AbortSignal.timeout(U6)})}catch(B){return{kind:"ambiguous",raw:B}}let Q;try{Q=await G.text()}catch(B){return G.ok?{kind:"ambiguous",raw:B}:{kind:"http_error",raw:B,status:G.status}}let Y=Q,W=!1;try{Y=JSON.parse(Q),W=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Y,status:G.status};if(!W||!r0(Y)||!$1(Y.code))return{kind:"ambiguous",raw:Y};return{kind:Y.code,raw:Y}}function q$($){if($.kind==="cooldown")throw new c("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function H$(){throw new c("expired_unreconciled","the previous reset attempt outcome is unknown")}function K$($,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 R6($){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.";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."}async function I$($,Z){if(!i(Z.accountKey))throw new c("invalid_account_key","the reset account key is reserved");let z=await $.resolveTarget(Z.accountKey);if(z.chatgptAccountId!==Z.expectedChatgptAccountId)throw new c("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=z.accountKey==="main"?void 0:z.chatgptAccountId,J=await O6($,Z.accountKey);if(J.kind==="corrupt"){if(J=await M6($,Z.accountKey),J.kind==="corrupt")return K$(z,J.beforeState)}if(J.kind==="cooldown")q$(J);let G;if(J.kind==="claim")G=J.claim;else if(J.kind==="expired_unreconciled"){if(!Z.retry)H$();G=J.claim}else{if(Z.retry)throw new c("retry_without_inflight","there is no active reset credit redemption to retry");let[W,B]=await Promise.all([$.fetchUsage(z),e8($.fetchImpl,z.accessToken,X)]),V=r8(W,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!V.ok)throw new c("not_exhausted",V.reason);if(!$8(B.credits))throw new c("no_eligible_credit","no eligible reset credit was returned");let j=await _6($,Z.accountKey,B.credits);if(j.kind==="corrupt")return K$(z,j.beforeState);if(j.kind==="cooldown")q$(j);if(j.kind==="expired_unreconciled")H$();if(j.kind!=="claim")throw new c("no_eligible_credit","no eligible reset credit was available while claiming");G=j.claim}let Q=await I6($.fetchImpl,z.accessToken,X,G.inFlight.creditId,G.inFlight.redeemRequestId),Y=!1;try{await x6($,Z.accountKey,G.inFlight,Q)}catch{Y=$1(Q.kind)}return{target:z,selectedCredit:G.selectedCredit,beforeState:J.beforeState,outcome:Q,retrySafety:Y?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":R6(Q),...Y?{finalizeStateWriteFailed:!0}:{}}}function R$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var z8="openai-quota",X8="openai-account",J8="openai-routing";var y0="openai-reset";var _=d("commands");function m($){return{configPath:$.accountStoragePath,statePath:$.accountStatePath}}function A$($){if($==="fallback-first")return"Try usable fallback accounts before the main account.";if($==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}var A6=900000;function T$($,Z){if(typeof $!=="number"||!Number.isFinite($))return" (age unknown)";let z=Z-$;if(z<A6)return"";let X=Math.floor(z/3600000);if(X>=24)return` (${Math.floor(X/24)}d old)`;if(X>=1)return` (${X}h old)`;return` (${Math.floor(z/60000)}m old)`}function C$($,Z=""){let z=$.resetsAt?` · resets ${$.resetsAt}`:"",X=(Q)=>Math.round(Q).toLocaleString("en-US"),J=$.unit??"unit",G=$.limit===1||J.endsWith("s")?J:`${J}s`;return`${Z}- credits: ${Math.round($.usedPercent)}% used (${X($.used)} / ${X($.limit)} ${G}, ${X($.remaining)} remaining)${z}`}async function T6($){let Z=await $.refreshAllQuota?.(),z=$.quotaManager.getMain(),X=Date.now(),J=["## OpenAI Quota",""];if(z?.quota){let Y=z.quota;J.push("### Main account");for(let W of["primary","secondary"]){let B=Y[W];if(B){let V=Math.round(B.usedPercent),j="█".repeat(Math.max(0,Math.min(Math.round(V/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(V/10),10)));J.push(`- ${W}: ${j} ${V}% used (${Math.round(B.remainingPercent)}% remaining)${T$(B.checkedAt??z.checkedAt,X)}`)}}if(Y.resetCreditsAvailable!==void 0)J.push(`- resets: ${Y.resetCreditsAvailable}`);if(Y.spendControl)J.push(C$(Y.spendControl))}else J.push("No main quota snapshot available. Send a request first.");let Q=[...$.quotaManager.getAllFallbacks().entries()].filter(([,Y])=>Y);if(Q.length>0){J.push(""),J.push("### Fallback accounts");for(let[Y,W]of Q){if(!W?.quota)continue;J.push(`**${Y}**`);for(let B of["primary","secondary"]){let V=W.quota[B];if(V){let j=Math.round(V.usedPercent);J.push(` - ${B}: ${j}% used (${Math.round(V.remainingPercent)}% remaining)${T$(V.checkedAt??W.checkedAt,X)}`)}}if(W.quota.resetCreditsAvailable!==void 0)J.push(` - resets: ${W.quota.resetCreditsAvailable}`);if(W.quota.spendControl)J.push(C$(W.quota.spendControl," "))}}if(Z?.length){let Y=Z.filter((W)=>!W.ok);if(Y.length>0){J.push("");for(let W of Y)J.push(W.permanent?`- ${W.account}: sign-in no longer accepted — remove and add this account again`:`- ${W.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:J.join(`
94
- `),knobs:{}}}function h($){return{id:$.id,type:$.type??"oauth",enabled:$.enabled,label:$.label}}async function C6($,Z){let z=$.trim().split(/\s+/).filter(Boolean);_.info("account command parsed",{args:$,tokens:z});let X=await Z.loadAccounts(m(Z))??{version:1,accounts:[]},J=X.accounts??[];if(z[0]==="claustrum"){if(_.info("claustrum mode requested",{hasEnterFn:typeof Z.enterClaustrumMode==="function",accounts:J.length}),!Z.enterClaustrumMode)return _.warn("claustrum refused: transition fn absent from command context"),{command:"openai-account",text:`## Claustrum Unavailable
95
+ </html>`,d6=[],y$,o0=new Map;function ZZ($,Z){return new Promise((X,J)=>{let z=(Q)=>{$.off("listening",G),J(Q)},G=()=>{$.off("error",z),X()};$.once("error",z),$.once("listening",G),$.listen(v$,Z)})}function GZ($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function S1(){return o0.size}function b1($){if(o0.delete($),S1()===0)I1()}async function Rz(){let $=`http://localhost:${v$}/auth/callback`;if(d6.length>0)return{port:v$,redirectUri:$};if(y$)return y$;y$=(async()=>{let Z=(G,Q)=>{let Y=new URL(G.url||"/",`http://127.0.0.1:${v$}`);if(Y.pathname==="/auth/callback"){let B=Y.searchParams.get("code"),H=Y.searchParams.get("state"),W=Y.searchParams.get("error"),V=Y.searchParams.get("error_description");if(W){let q=V||W;if(H){let U=o0.get(H);if(U)U.reject(Error(q)),b1(H);else if(S1()===0)I1()}else if(S1()===0)I1();Q.writeHead(200,{"Content-Type":"text/html"}),Q.end(l6(q));return}if(!H){if(S1()===0)I1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(l6("Missing state parameter"));return}if(!B){if(S1()===0)I1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(l6("Missing authorization code"));return}let j=o0.get(H);if(!j){if(S1()===0)I1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(l6("Unknown state — authorization may have expired"));return}b1(H),Cz(B,$,j.pkce).then((q)=>j.resolve(q)).catch((q)=>j.reject(q)),Q.writeHead(200,{"Content-Type":"text/html"}),Q.end(Az);return}if(Y.pathname==="/cancel"){let B=Y.searchParams.get("state"),H=B?[B]:[...o0.keys()];Q.writeHead(200),Q.end("Login cancelled");for(let W of H){let V=o0.get(W);if(!V)continue;V.reject(Error("Login cancelled")),b1(W)}if(S1()===0)I1();return}Q.writeHead(404),Q.end("Not found")},X=$Z(Z);await ZZ(X,"127.0.0.1");let J=[X],z=$Z(Z);try{await ZZ(z,"::1"),J.push(z)}catch(G){let Q=G.code;if(Q!=="EADDRNOTAVAIL"&&Q!=="EAFNOSUPPORT")throw GZ(X),G}return d6=J,{port:v$,redirectUri:$}})();try{return await y$}finally{y$=void 0}}function I1(){let $=d6;d6=[];for(let Z of $)GZ(Z)}function Sz($,Z,X=300000,J){return new Promise((z,G)=>{if(J?.aborted){b1(Z),G(Error("Login cancelled"));return}let Q=setTimeout(()=>{if(o0.get(Z))b1(Z),G(Error("OAuth callback timeout — authorization took too long"))},X),Y=()=>{if(clearTimeout(Q),o0.get(Z))b1(Z),G(Error("Login cancelled"))};if(J)J.addEventListener("abort",Y);o0.set(Z,{pkce:$,state:Z,resolve:(B)=>{if(clearTimeout(Q),J)J.removeEventListener("abort",Y);z(B)},reject:(B)=>{if(clearTimeout(Q),J)J.removeEventListener("abort",Y);G(B)}})})}async function Iz($){let Z=await fetch(`${x1}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":XZ($)},body:JSON.stringify({client_id:c6})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${x1}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function xz($,Z,X){let J=Math.max(parseInt($.interval,10)||5,1)*1000,z=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(z)&&z>0?z*1000:900000,Q=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-Q>G)throw Error("Device authorization expired");let Y=await fetch(`${x1}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":XZ(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(Y.ok){let W=await Y.json(),V=await fetch(`${x1}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:W.authorization_code,redirect_uri:`${x1}/deviceauth/callback`,client_id:c6,code_verifier:W.code_verifier}).toString()});if(!V.ok)throw Error(`Token exchange failed: ${V.status}`);return await V.json()}if(Y.status!==403&&Y.status!==404)throw Error(`Device authorization failed: ${Y.status}`);let B=G-(Date.now()-Q);if(B<=0)throw Error("Device authorization expired");let H=Math.min(J+Mz,B);try{await Nz(H,void 0,{signal:X})}catch(W){if(W instanceof Error&&W.name==="AbortError")throw Error("Device authorization cancelled");throw W}}}async function QZ($){let{label:Z,headless:X=!1,signal:J,version:z}=$;if(h8(Z),X){let{deviceData:W,url:V,instructions:j}=await Iz(z),q=(async()=>{let U=await xz(W,z,J),L=Date.now(),N=g$(U);return{id:h8(Z||N||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:U.access_token,refresh:U.refresh_token,expires:L+(U.expires_in??3600)*1000,enabled:!0,addedAt:L,lastUsed:L,lastRefreshedAt:L,accountId:N}})();return{url:V,instructions:j,completion:q}}let{redirectUri:G}=await Rz(),Q=await Pz(),Y=zZ(crypto.getRandomValues(new Uint8Array(32)).buffer),B=_z(G,Q,Y),H=(async()=>{try{if(J?.aborted)throw Error("Login cancelled");let W=await Sz(Q,Y,void 0,J),V=Date.now(),j=g$(W);return{id:h8(Z||j||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:W.access_token,refresh:W.refresh_token,expires:V+(W.expires_in??3600)*1000,enabled:!0,addedAt:V,lastUsed:V,lastRefreshedAt:V,accountId:j}}finally{b1(Y)}})();return{url:B,instructions:"Complete authorization in your browser. This window will close automatically.",completion:H}}import{basename as bz,dirname as Ez,join as kz}from"node:path";var s6="openai-auth.json",YZ="openai-auth-state.json";function w8($){return bz($)===s6?kz(Ez($),YZ):`${$}.state.json`}function i6($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let J=Z<100000000000?Z*1000:Z,z=new Date(J);return Number.isNaN(z.getTime())?void 0:z.toISOString()}let X=new Date($);return Number.isNaN(X.getTime())?void 0:X.toISOString()}function m8($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function BZ($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function WZ($,Z){let X=$.get(Z);if(X===null||X.trim()==="")return;let J=Number(X);if(!Number.isFinite(J)||J<0||J>100)return;let z=Z.slice(0,-13),G=m8($.get(`${z}-window-minutes`)),Q=i6($.get(`${z}-reset-at`)??void 0);if(J===0&&$.get(`${z}-window-minutes`)==="0"&&!Q)return;return{usedPercent:J,remainingPercent:100-J,resetsAt:Q,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var jZ=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function UZ($,Z){let X=$.get(Z);if(X===null)return"absent";if(X.trim()==="")return"invalid";let J=Number(X);return Number.isFinite(J)&&J>=0&&J<=100?"valid":"invalid"}function qZ($){if(jZ.some((z)=>UZ($,z)==="invalid"))return{};let Z={},X=WZ($,"x-codex-primary-used-percent");if(X)Z.primary=X;let J=WZ($,"x-codex-secondary-used-percent");if(J)Z.secondary=J;return Z}function KZ($){let Z=jZ.map((X)=>UZ($,X));return Z.includes("valid")&&!Z.includes("invalid")}function HZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=m8($.window_minutes),X=i6($.reset_at);if($.used_percent===0&&Z===void 0&&!X)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:X,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z}:{}}}function DZ($){let Z={},X=HZ($.rate_limits?.primary);if(X)Z.primary=X;let J=HZ($.rate_limits?.secondary);if(J)Z.secondary=J;return Z}function J$($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function VZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=m8($.limit_window_seconds),X=i6($.reset_at);if($.used_percent===0&&Z===void 0&&!X)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:X,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z/60}:{}}}function NZ($){let Z={},X=VZ($.rate_limit?.primary_window);if(X)Z.primary=X;let J=VZ($.rate_limit?.secondary_window);if(J)Z.secondary=J;let z=BZ($.rate_limit_reset_credits?.available_count);if(z!==void 0)Z.resetCreditsAvailable=z;let G=BZ($.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)Z.resetCreditsApplicable=G;let Q=$.spend_control?.individual_limit;if($.spend_control===null||Q===null)Z.spendControlCleared=!0;if(Q&&typeof $.spend_control?.reached==="boolean"){let B=J$(Q.limit),H=J$(Q.used),W=J$(Q.remaining),V=J$(Q.used_percent),j=J$(Q.remaining_percent);if(B!==void 0&&H!==void 0&&W!==void 0&&V!==void 0&&j!==void 0)Z.spendControl={limit:B,used:H,remaining:W,usedPercent:V,remainingPercent:j,resetsAt:i6(Q.reset_at),unit:Q.unit,source:Q.source,reached:$.spend_control.reached}}let Y=$.credits;if(Y&&typeof Y.has_credits==="boolean"&&typeof Y.unlimited==="boolean"&&typeof Y.overage_limit_reached==="boolean"){let B=J$(Y.balance);Z.credits={hasCredits:Y.has_credits,unlimited:Y.unlimited,overageLimitReached:Y.overage_limit_reached,...B!==void 0?{balance:B}:{}}}return Z}import{readdirSync as MG,statSync as LG}from"node:fs";import{tmpdir as rZ,userInfo as FG}from"node:os";import{join as Y$}from"node:path";import{debuglog as cz}from"node:util";import{createHmac as gz,randomBytes as hz,timingSafeEqual as wz}from"node:crypto";import vz from"node:net";var L0=2,a6=21,n6=5,p8=67108864,T;(function($){$[$.Request=0]="Request",$[$.Response=1]="Response",$[$.Push=2]="Push",$[$.StreamData=3]="StreamData",$[$.StreamEnd=4]="StreamEnd",$[$.Error=5]="Error",$[$.Cancel=6]="Cancel",$[$.Ping=7]="Ping",$[$.Pong=8]="Pong",$[$.Hello=9]="Hello",$[$.HelloAck=10]="HelloAck",$[$.Goodbye=11]="Goodbye"})(T||(T={}));var MZ=T.Goodbye;function LZ($){return $===T.Cancel||$===T.Ping||$===T.Pong||$===T.Goodbye}var r;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(r||(r={}));var Y0;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(Y0||(Y0={}));var FZ=1,PZ=6,u8=1,fz=8,OZ=48,l8=4;var _Z=0;function U0($,Z,X,J=Y0.Normal){let z=0;if($)z|=FZ;if(z|=Z<<u8,X)z|=fz;return z|=J<<l8,z}function d8($){return($&FZ)!==0}function CZ($){let Z=new Uint8Array(21),X=new DataView(Z.buffer);return X.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,X.setUint16(7,$.channel,!0),X.setUint32(9,$.epoch,!0),X.setBigUint64(13,$.corr,!0),Z}class m extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function yz($){let Z=$.len>>>0,X=$.ver>>>0&255,J=$.ty>>>0&255,z=$.flags>>>0&255,G=$.channel>>>0&65535,Q=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),X!==2)throw new m(`unsupported envelope version ${X}`,"unsupported_version");if(J>MZ)throw new m(`unknown frame type byte ${J}`,"unknown_frame_type");let Y=J;if((z&_Z)!==0)throw new m(`reserved flag bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((z&PZ)>>u8===3)throw new m(`reserved priority bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let B=(z&OZ)>>l8;if(B===3)throw new m(`reserved admission class set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(B===Y0.Sheddable&&Y!==T.Push&&Y!==T.StreamData)throw new m(`SHEDDABLE admission class is illegal on ${T[Y]} in flags 0b${z.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(G===0&&Q!==0)throw new m(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(LZ(Y)&&Z!==0)throw new m(`pure-header frame ${T[Y]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function c8($){if($.length<5)throw new m(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new m(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new m(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let X=new DataView($.buffer,$.byteOffset,$.byteLength),J=X.getUint32(0,!0),z=$[5];if(z>MZ)throw new m(`unknown frame type byte ${z}`,"unknown_frame_type");let G=z,Q=$[6];if((Q&_Z)!==0)throw new m(`reserved flag bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((Q&PZ)>>u8===3)throw new m(`reserved priority bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Y=(Q&OZ)>>l8;if(Y===3)throw new m(`reserved admission class set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Y===Y0.Sheddable&&G!==T.Push&&G!==T.StreamData)throw new m(`SHEDDABLE admission class is illegal on ${T[G]} in flags 0b${Q.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let B=X.getUint16(7,!0),H=X.getUint32(9,!0);if(B===0&&H!==0)throw new m(`control channel carried nonzero epoch ${H}`,"nonzero_epoch_on_control_channel");if(LZ(G)&&J!==0)throw new m(`pure-header frame ${T[G]} declared non-zero body length ${J}`,"pure_header_frame_with_body");return{len:J,ver:Z,ty:G,flags:Q,channel:B,epoch:H,corr:X.getBigUint64(13,!0)}}function B0($,Z,X,J,z,G){return h0(2,$,Z,X,J,z,G)}function h0($,Z,X,J,z,G,Q){if(Q.length>67108864)throw new m(`frame body ${Q.length} exceeds max 67108864`,"frame_body_too_large");let Y={len:Q.length,ver:$,ty:Z,flags:X,channel:J,epoch:z,corr:G};return yz(Y),{header:Y,body:Q}}function I0($){if($.header.len!==$.body.length)throw new m(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=CZ($.header),X=new Uint8Array(Z.length+$.body.length);return X.set(Z,0),X.set($.body,Z.length),X}class t0 extends Error{}class x0 extends Error{}class w0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}class H1 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function TZ($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var AZ=Symbol("subc.socket.writeBorrowed"),RZ=Symbol("subc.socket.writeTrackedBorrowed");function b0($,Z,X){let J=$[AZ];return J?J.call($,Z,X):$.write(Z,X)}function s8($,Z,X){let J=$[RZ];return J?J.call($,Z,X):$.writeTracked(Z,X)}class E1{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(X)=>{this.chunks.push(X),this.buffered+=X.length,this.tryServe()});let Z=(X)=>{if(!this.closedErr)this.closedErr=X;this.tryServe()};$.on("error",(X)=>Z(X instanceof Error?X:Error(String(X)))),$.on("end",()=>Z(new t0("subc closed the connection"))),$.on("close",()=>Z(new t0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,X){return new Promise((J,z)=>{let G=vz.connect({host:$,port:Z});G.setNoDelay(!0);let Q=setTimeout(()=>{G.destroy(),z(new x0(`timed out connecting to ${$}:${Z}`))},Math.max(0,X-Date.now()));G.once("connect",()=>{clearTimeout(Q),J(new E1(G))}),G.once("error",(Y)=>{clearTimeout(Q),z(Y)})})}async readFrame($,Z,X){let J=await this.readExact(n6,$),z=J[4];if(z!==L0)throw new m(`unsupported envelope version ${z}`,"unsupported_version");let G=await this.readExact(a6-n6,$),Q=new Uint8Array(a6);Q.set(J),Q.set(G,n6);let Y=c8(Q);if(Y.len>p8)throw new m(`frame body ${Y.len} exceeds max ${p8}`,"frame_body_too_large");X?.();let B=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,H=Y.len===0?new Uint8Array(0):await this.readExact(Y.len,B);return{header:Y,body:H}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((X,J)=>{let z=null;if(Number.isFinite(Z)){let G=Z-Date.now();if(G<=0){J(new x0(`timed out waiting for ${$} bytes`));return}z=setTimeout(()=>{this.waiter=null,J(new x0(`timed out waiting for ${$} bytes`))},G)}this.waiter={need:$,resolve:X,reject:J,timer:z},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[AZ]($,Z){await this.writeBuffer(TZ($),Z)}[RZ]($,Z){return this.writeTrackedBuffer(TZ($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(X){if(X instanceof w0||X instanceof H1)throw X.cause??X;throw X}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new w0("subc socket was closed before bytes could be queued",this.closedErr))};let X=!1,J=!1,z=null,G=new Promise((Q,Y)=>{let B=(W)=>{if(J)return;if(J=!0,z)clearTimeout(z);W()},H=Z-Date.now();if(H<=0){B(()=>Y(new w0("timed out before bytes could be queued to subc",new x0("timed out writing to subc"))));return}z=setTimeout(()=>{let W=new x0("timed out writing to subc");B(()=>Y(X?new H1("timed out after bytes were handed to the subc socket",W):new w0("timed out before bytes could be queued to subc",W)))},H);try{this.sock.write($,(W)=>{B(()=>{if(W)Y(new H1("subc socket reported a write error after bytes were handed to the socket",W instanceof Error?W:Error(String(W))));else Q()})}),X=!0}catch(W){B(()=>Y(new w0("subc socket write threw before bytes could be queued",W instanceof Error?W:Error(String(W)))))}});return{queued:X,completed:G}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),X=0;while(X<$){let J=this.chunks[0],z=$-X;if(J.length<=z)J.copy(Z,X),X+=J.length,this.chunks.shift();else J.copy(Z,X,0,z),this.chunks[0]=J.subarray(z),X+=z}return this.buffered-=$,Z}}var xZ=32;var r6=4096,bZ="subc-server-v1",EZ="subc-client-v1",mz="client";class q0 extends Error{}function a8($,Z,X,J,z){let G=gz("sha256",Buffer.from($));return G.update(Buffer.from(Z,"utf8")),G.update(Buffer.from(X)),G.update(Buffer.from(J)),G.update(Buffer.from(z)),new Uint8Array(G.digest())}function SZ($,Z){if($.length!==Z.length)return!1;return wz(Buffer.from($),Buffer.from(Z))}async function IZ($,Z,X){let J=Buffer.from(JSON.stringify(Z),"utf8");if(J.length>r6)throw new q0(`auth message too large: ${J.length} > ${r6}`);let z=new Uint8Array(4);new DataView(z.buffer).setUint32(0,J.length,!0),await b0($,z,X),await b0($,J,X)}async function pz($,Z){let X=await $.readExact(4,Z),J=new DataView(X.buffer,X.byteOffset,4).getUint32(0,!0);if(J>r6)throw new q0(`auth message too large: ${J} > ${r6}`);let z=J===0?new Uint8Array(0):await $.readExact(J,Z);try{return JSON.parse(Buffer.from(z).toString("utf8"))}catch(G){throw new q0(`auth message JSON decode failed: ${String(G)}`)}}function i8($,Z){if(!Array.isArray($))throw new q0(`auth field '${Z}' must be a byte array`);for(let X of $)if(typeof X!=="number"||!Number.isInteger(X)||X<0||X>255)throw new q0(`auth field '${Z}' has invalid byte ${String(X)}`);return Uint8Array.from($)}async function h$($,Z,X){let J=new Uint8Array(hz(xZ));await IZ($,{client_nonce:Array.from(J),role:mz},X);let z=await pz($,X),G=i8(z.server_nonce,"server_nonce"),Q=i8(z.daemon_id,"daemon_id"),Y=i8(z.server_proof,"server_proof"),B=a8(Z.key,bZ,J,G,Q);if(!SZ(B,Y))throw new q0("server proof mismatch — wrong key or impostor daemon");if(!SZ(Q,Z.daemonId))throw new q0("daemon id mismatch — connection file points at a different daemon");let H=a8(Z.key,EZ,J,G,Q);await IZ($,{client_auth:Array.from(H)},X)}import{promises as n8}from"node:fs";var kZ=1,fZ=32,yZ=16;class $0 extends Error{}function vZ($,Z){if(!Array.isArray($))throw new $0(`connection file field '${Z}' must be a JSON array of bytes`);for(let X of $)if(typeof X!=="number"||!Number.isInteger(X)||X<0||X>255)throw new $0(`connection file field '${Z}' has invalid byte ${String(X)}`);return Uint8Array.from($)}function uz($){if($.schema!==kZ)throw new $0(`unsupported connection file schema ${$.schema}; expected ${kZ}`);if($.endpoints.length===0)throw new $0("connection file must include at least one endpoint");if($.key.length<fZ)throw new $0(`connection file key is too short: ${$.key.length} bytes, need at least ${fZ}`);if($.daemonId.length!==yZ)throw new $0(`connection file daemon_id must be ${yZ} bytes, got ${$.daemonId.length}`)}async function lz($){if(process.platform==="win32")return;let X=(await n8.stat($)).mode&511;if((X&63)!==0)throw new $0(`connection file ${$} has insecure permissions 0o${X.toString(8)}; expected owner-only 0600`)}async function z$($){await lz($);let Z=await n8.readFile($,"utf8"),X;try{X=JSON.parse(Z)}catch(Y){throw new $0(`connection file JSON read failed for ${$}: ${String(Y)}`)}let J=X.wire_version;if(J!==void 0&&J!==L0)throw new $0(`connection file wire_version ${String(J)} but this client speaks ${L0}; the client library must be upgraded`);let z=X.endpoints;if(!Array.isArray(z))throw new $0("connection file 'endpoints' must be an array");let G=z.map((Y)=>{let B=Y;if(typeof B.host!=="string"||typeof B.port!=="number")throw new $0("connection file endpoint must be { host: string, port: number }");return{host:B.host,port:B.port}}),Q={schema:X.schema,endpoints:G,key:vZ(X.key,"key"),daemonId:vZ(X.daemon_id,"daemon_id"),pid:X.pid,daemonVer:X.daemon_ver??""};return uz(Q),Q}var gZ=new WeakMap,r8=new WeakMap;class o8 extends Error{methodFamily;code="reverse_request_capability_not_declared";constructor($){super(`reverse-request capability ${JSON.stringify($)} was not registered before route.open`);this.methodFamily=$,this.name="ReverseRequestRegistrationError"}}class V1{handlers=new Map;declaredFamilies=null;onRequest($,Z){if(!dz($))throw TypeError(`reverse-request method family must be a capability identifier, got ${JSON.stringify($)}`);if(typeof Z!=="function")throw TypeError("reverse-request handler must be a function");if(this.declaredFamilies&&!this.declaredFamilies.has($))throw new o8($);this.handlers.set($,Z)}capabilities(){return[...this.handlers.keys()].sort()}handler($){return this.handlers.get($)}seal(){this.declaredFamilies??=new Set(this.handlers.keys())}}class o6{channel;epoch;constructor($,Z,X,J){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,J.seal(),gZ.set(this,X),r8.set(this,J),Object.freeze(this)}onRequest($,Z){r8.get(this).onRequest($,Z)}static create($,Z,X,J){return new o6($,Z,X,J)}}function t6($,Z,X,J=new V1){return o6.create($,Z,X,J)}function hZ($,Z){return r8.get($)?.handler(Z)}function dz($){return/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test($)}class e0 extends Error{handle;code="stale_route_handle";constructor($){super(`route handle (${$.channel}, ${$.epoch}) is not live on the current connection`);this.handle=$,this.name="StaleRouteHandleError"}}function G$(){return Object.freeze({})}function w$($,Z){return gZ.get($)===Z}function e6($,Z){return $===Z}var wZ=cz("subc-client"),sz=1e4,Q$=30000,iz=50,az=2000,mZ="request_deadline",t8="deadline_exceeded_no_drop_observed",nz=30000,rz=30000,pZ=new Uint8Array(0),oz="management_surface",J3="SUBC_MODULE_ID",z3="SUBC_LAUNCH_NONCE",G3={baseMs:100,capMs:2000,maxAttempts:6};class Z0 extends Error{kind;code;cause;constructor($,Z,X,J){super(Z);this.kind=$,this.code=X,this.cause=J,this.name="SubcCallError"}get detail(){return this.cause instanceof k?this.cause.detail:void 0}}class k extends Error{code;detail;constructor($,Z,X){super($);this.code=Z,this.detail=X}}var uZ=new WeakMap;function e8($){if($ instanceof Uint8Array)return $;let Z=$===null?"null":Array.isArray($)?"array":typeof $;throw new k(`binary request body must be a Uint8Array; got ${Z}`,"binary_body_required")}class k1{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=G$();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,X){this.sock=$,this.currentConn=Z,this.opts=X,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=$G($),X=await k1.openConnection(Z);return new k1(X.sock,X.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),X=await this.controlRpc(Z);return this.parseJson(X).modules??[]}async resolveProvider($){let Z=await this.resolveProviders($);if(Z.length===0)throw new k(`no catalog claimant for capability ${$}`,"capability_unprovided");if(Z.length>1)throw new k(`multiple catalog claimants for capability ${$}: ${Z.join(", ")}`,"capability_ambiguous");return Z[0]}async resolveProviders($){if(!sZ($))throw new k(`malformed capability identifier ${JSON.stringify($)}`,"invalid_capability_identifier");return(await this.catalogList()).filter((X)=>X.capabilities?.provides.includes($)??!1).map((X)=>X.module_id).sort()}async routeOpen($,Z,X={}){let J=$2(X),z=X.reverseRequests??new V1;z.seal();let G=z.capabilities(),Q=this.encode({op:"route.open",target:$,identity:Z,...J?{consumer_identity:J}:{},...G.length>0?{consumer_capabilities:G}:{}}),Y=null,B=(W)=>{if(W.header.ty!==T.Response)return!0;let V=this.parseJson(W);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")throw new k(`route.open returned no route handle: ${JSON.stringify(V)}`);return Y=this.installRoute(V.route_channel,V.route_epoch,z),!0},H=(W)=>{if(W.header.ty!==T.Response)return;try{let V=this.parseJson(W);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")return;let j=this.installRoute(V.route_channel,V.route_epoch);this.failHandle(j,new k("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(Q,B,H),!Y)throw new k("route.open response was not installed");return Y}async request($,Z,X={}){this.assertLiveHandle($);let J=X.binary??!1,z=J?e8(Z):Z instanceof Uint8Array?Z:this.encode(Z),G=X.priority??r.Interactive,Q=X.admissionClass??Y0.Normal,Y=await this.send($,z,G,Q,X.timeoutMs,X.onProgress,void 0,void 0,J,X.signal);return this.decodeReply(Y)}async call($,Z,X,J={}){if(J.binary)throw new k("call() builds a JSON body and cannot send a binary request; use callBinary(moduleId, body, opts) with a Uint8Array","binary_call_requires_call_binary");let z=X===void 0?{method:Z}:{method:Z,params:X};return await this.managedCall($,z,J)}async callBinary($,Z,X={}){let J=e8(Z);return this.managedCall($,J,{...X,binary:!0})}async managedCall($,Z,X){let J=!1;for(;;){let z=await this.cachedRouteHandle($,X);try{return await this.managedRequest(z,Z,X)}catch(G){if(!(G instanceof Z0))throw this.terminalCallError("managed call failed",G);let Q=Q3(G.cause instanceof k?uZ.get(G.cause)??0:0,G.code);if(Q&&!J&&!this.closeStarted){J=!0,this.evictRouteHandle(z);continue}if(Q&&J)this.evictRouteHandle(z);if(G.code==="route_closed")throw this.evictRouteHandle(z),G;if(G.kind==="not_sent"){if(!this.closedErr)throw G;try{await this.reconnectAfterDrop(G)}catch(Y){throw this.notSentRecoveryError("managed call was not sent",Y)}continue}if(G.kind==="outcome_unknown"&&G.code!==t8){if(this.closedErr)this.scheduleReconnectAfterDrop(G)}else if(G.kind==="outcome_unknown"&&G.code===t8)this.probeLivenessAfterDeadline();throw G}}}subscribe($,Z,X,J={}){this.assertLiveHandle($);let z=Z instanceof Uint8Array?Z:this.encode(Z),G=J.priority??r.Interactive,Q=J.admissionClass??Y0.Normal,Y=this.allocateCorr(),B=$3($,Y),H=null,W=null,V=new Promise((U,L)=>{if(this.closedErr){L(this.closedErr);return}W=U,H={handle:$,resolve:()=>U(),reject:L,onProgress:X,timer:null,subscription:!0},this.pending.set(B,H);let N=B0(T.Request,U0(!1,G,!1,Q),$.channel,$.epoch,Y,z);b0(this.sock,I0(N),Date.now()+Q$).catch((K)=>{let F=this.pending.get(B);if(F)this.rejectPending(B,F,K instanceof Error?K:new k(String(K)))})}),j=!1;return{unsubscribe:()=>{if(j)return;if(j=!0,H&&W)this.settle(B,H,W);if(this.isLiveHandle($))this.cancel($,Y,G)},closed:V}}attachCancelSignal($,Z,X,J,z){if(!X)return;let G=()=>{if(!this.pending.has(Z))return;try{this.cancel(X,J,z)}catch{}};if($.aborted){G();return}$.addEventListener("abort",G,{once:!0});let Q=this.pending.get(Z);if(Q){let Y=Q.onSettle;Q.onSettle=()=>{Y?.(),$.removeEventListener("abort",G)}}}cancel($,Z,X=r.Interactive){this.assertLiveHandle($);let J=B0(T.Cancel,U0(!1,X,!1),$.channel,$.epoch,Z,pZ);b0(this.sock,I0(J),Date.now()+Q$).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let X=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),J=await this.controlRpc(X,(z)=>{if(z.header.ty!==T.Response)return!0;let G=this.parseJson(z);return G.route_channel===$.channel&&G.route_epoch===$.epoch});return this.parseJson(J)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[X,J]of this.routes)if(J.handle&&e6(J.handle,$))J.closed=!0,J.handle=null,this.routes.delete(X);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new k("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,X={}){let J=lZ($,Z,$2(X),(X.reverseRequests??new V1).capabilities()),z=this.routes.get(J);if(!z)return;z.closed=!0,this.routes.delete(J);let G=z.handle;if(z.handle=null,G)await this.closeRoute(G,X)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new k("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let X of this.pending.values())if(X.handle===$&&!X.subscription)Z.push(new Promise((J)=>{let z=X.onSettle;X.onSettle=()=>{z?.(),J()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let X=B0(T.Goodbye,U0(!1,r.Interactive,!1),$.channel,$.epoch,0n,pZ),J=s8(this.sock,I0(X),Date.now()+Q$);if(!J.queued&&Z)this.closeConnectionAfterCleanupFailure();J.completed.catch(()=>{if(Z&&!J.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await z$($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??sz),J=Z.endpoints[0],z=await E1.connect(J.host,J.port,X);try{await h$(z,Z,X)}catch(G){throw z.close(),G}return{sock:z,conn:Z}}async controlRpc($,Z,X){return this.send(null,$,r.Interactive,Y0.Normal,void 0,void 0,Z,X)}send($,Z,X,J,z,G,Q,Y,B=!1,H){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let W;try{W=this.allocateCorr()}catch(L){return Promise.reject(L)}let V=$3($,W),j=$?.channel??0,q=$?.epoch??0,U=B0(T.Request,U0(B,X,!1,J),j,q,W,Z);return new Promise((L,N)=>{let K=z??Q$,F={handle:$,resolve:L,reject:N,onProgress:G,timer:null,acceptFrame:Q,onLateResponse:Y};if(F.timer=setTimeout(()=>this.arbitrateTimeout(V,F,j,W,K),K),this.pending.set(V,F),H)this.attachCancelSignal(H,V,$,W,X);b0(this.sock,I0(U),Date.now()+K).catch((C)=>{let M=this.pending.get(V);if(M)this.rejectPending(V,M,C instanceof Error?C:new k(String(C)))})})}arbitrateTimeout($,Z,X,J,z){let G=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new k(this.timeoutMessage(X,J,z),mZ))},Q=Date.now()+this.opts.timeoutArbitrationGraceMs,Y=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<Q){setImmediate(Y);return}G()};setImmediate(Y)}async managedRequest($,Z,X){let J=X.binary??!1,z=J?e8(Z):Z instanceof Uint8Array?Z:this.encode(Z),G=X.priority??r.Interactive,Q=X.admissionClass??Y0.Normal;try{let Y=await this.sendManaged($,z,G,Q,X.timeoutMs,X.onProgress,J,X.signal);return this.decodeReply(Y)}catch(Y){if(Y instanceof Z0)throw Y;throw this.terminalCallError("managed call failed",Y)}}sendManaged($,Z,X,J,z,G,Q=!1,Y){try{this.assertLiveHandle($)}catch(q){return Promise.reject(this.notSentCallError("request used a stale route handle",q))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let B;try{B=this.allocateCorr()}catch(q){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",q))}let H=$3($,B),W=B0(T.Request,U0(Q,X,!1,J),$.channel,$.epoch,B,Z),V=!1,j=(q)=>{if(!V)return this.notSentCallError("request bytes were not queued to the subc socket",q);if(q instanceof k&&q.code===mZ)return new Z0("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${m$(q)}`,t8,q);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",q)};return new Promise((q,U)=>{let L=z??Q$,N={handle:$,resolve:q,reject:U,onProgress:G,timer:null,classifyFailure:j};if(N.timer=setTimeout(()=>this.arbitrateTimeout(H,N,$.channel,B,L),L),this.pending.set(H,N),Y)this.attachCancelSignal(Y,H,$,B,X);let K=s8(this.sock,I0(W),Date.now()+L);V=K.queued,K.completed.catch((F)=>{let C=this.pending.get(H);if(C)this.rejectPending(H,C,F instanceof Error?F:new k(String(F)))})})}async cachedRouteHandle($,Z){let X=Z.identity??this.opts.identity;if(!X)throw new Z0("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let J={kind:Z.targetKind??this.opts.targetKind,module_id:$},z=$2(Z),G=Z.reverseRequests??new V1;G.seal();let Q=lZ(J,X,z,G.capabilities()),Y=this.routes.get(Q);if(!Y)Y={key:Q,moduleId:$,target:J,identity:X,consumerIdentity:z,reverseRequests:G,handle:null,opening:null},this.routes.set(Q,Y);if(Y.handle&&this.isLiveHandle(Y.handle))return Y.handle;if(!Y.opening)Y.opening=this.openCachedRoute(Y).finally(()=>{Y.opening=null});return Y.opening}async openCachedRoute($){let Z=Date.now()+this.opts.routeOpenRetryDeadlineMs,X=this.opts.reconnectBackoff.baseMs,J=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(z){throw this.notSentRecoveryError("route.open could not run because reconnect failed",z)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let z=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null,reverseRequests:$.reverseRequests});if($.closed)throw this.liveRoutes.delete(z.channel),this.sendRouteGoodbye(z),this.routeClosedDuringOpen();return $.handle=z,z}catch(z){if(z instanceof Z0&&z.code==="route_closed")throw z;if(!this.closeStarted&&Z3(z)){try{await this.reconnectAfterDrop(z)}catch(G){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",G)}continue}if(!this.closeStarted&&z instanceof k&&ez(z.code)){if(J+=1,Date.now()<Z){await this.opts.sleep(X),X=Math.min(X*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${z.code} (retry deadline exhausted after ${J} attempts)`,z)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,z)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,X;try{X=this.allocateCorr()}catch{return}let J=Date.now(),z=B0(T.Ping,U0(!1,r.Interactive,!1,Y0.Normal),0,0,X,new Uint8Array),G=(async()=>{if(await b0($,I0(z),J+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=J)return;if(this.hasControlPending())return;this.fail(new t0(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),$.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=G}async ensureConnectedForManaged(){if(this.closeStarted)throw new k("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop($){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop($).catch(()=>{})}reconnectAfterDrop($){if(this.closeStarted)return Promise.reject(new k("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,X=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new k("client closed");Z+=1;try{let J=await k1.openConnection(this.opts);if(this.closeStarted)throw J.sock.close(),new k("client closed");this.replaceConnection(J),await this.reopenCachedRoutes();return}catch(J){if(!Z3(J)||Z>=this.opts.reconnectBackoff.maxAttempts){if(J instanceof q0&&Z>1)throw new q0(`reconnect gave up after ${Z} attempts: ${J.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw J}await this.opts.sleep(X),X=Math.min(X*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.fail(new k("subc connection replaced")),this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=G$(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){let $=[...this.routes.keys()];for(let Z of $){let X=this.routes.get(Z);if(X)X.handle=null}for(let Z of $){let X=this.routes.get(Z);if(!X||X.closed)continue;try{let J=await this.routeOpen(X.target,X.identity,{consumerIdentity:X.consumerIdentity??null,reverseRequests:X.reverseRequests});if(X.closed){this.liveRoutes.delete(J.channel),this.sendRouteGoodbye(J);continue}X.handle=J}catch(J){if(tz(J)){this.routes.delete(Z);continue}throw J}}}timeoutMessage($,Z,X){let J=this.sock.localPort();return`request on ${J===null?"channel":`local_port=${J} channel`} ${$} corr ${Z} timed out after ${X}ms`}routeClosedDuringOpen(){return new Z0("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let X=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:rz},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(X)}finally{this.readerActive=!1}}}catch(X){if(this.sock===$&&this.generation===Z)this.fail(X instanceof Error?X:new k(String(X)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===T.Push){let G=this.opts.onControlPush;if(G){let Q=null;try{let Y=this.parseJson($);if(Y&&typeof Y.op==="string")Q={op:Y.op,body:Y}}catch{}if(Q)try{G(Q)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}if($.header.ty===T.Request&&Z){this.dispatchReverseRequest($,Z);return}let X=$3(Z,$.header.corr),J=this.pending.get(X);if(J){if(J.acceptFrame&&!J.acceptFrame($))return;switch($.header.ty){case T.Push:case T.StreamData:try{J.onProgress?.($.body)}catch{}return;case T.Response:case T.StreamEnd:this.settle(X,J,()=>J.resolve($));return;case T.Error:this.settle(X,J,()=>J.reject(this.errorFromFrame($)));return;default:return}}let z=this.lateResponses.get(X);if(z&&($.header.ty===T.Response||$.header.ty===T.Error)){this.lateResponses.delete(X),z($);return}if($.header.ty===T.Goodbye&&Z){if(this.failHandle(Z,new k("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===T.Response||$.header.ty===T.Error||$.header.ty===T.StreamEnd)wZ("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,X){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return X(),Z.onSettle?.(),!0}rejectPending($,Z,X){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(X)??X))}dispatchReverseRequest($,Z){let X=ZG($.body),J=X?.split("/",1)[0],z=J?hZ(Z,J):void 0,G=this.sock,Q=this.generation;(async()=>{if(!z||!X){await this.sendReverseError($,Z,"reverse_request_unhandled",J?`no reverse-request handler is registered for ${J}`:"reverse request has no valid method",G,Q);return}let B;try{if(B=await z($.body,{corr:$.header.corr,method:X}),!(B instanceof Uint8Array))throw TypeError("reverse-request handler must return a Uint8Array")}catch(H){await this.sendReverseError($,Z,"reverse_request_unhandled",H instanceof Error?H.message:String(H),G,Q);return}await this.sendReverseReply($,Z,T.Response,B,G,Q)})().catch((B)=>{if(this.sock===G&&this.generation===Q&&!this.closeStarted)wZ("failed to answer reverse request: %s",m$(B))})}async sendReverseError($,Z,X,J,z,G){await this.sendReverseReply($,Z,T.Error,this.encode({code:X,message:J}),z,G)}async sendReverseReply($,Z,X,J,z,G){if(this.sock!==z||this.generation!==G||!this.isLiveHandle(Z)||this.closeStarted||this.closedErr)return;let Q=B0(X,U0(!1,r.Interactive,!1),Z.channel,Z.epoch,$.header.corr,J);await b0(z,I0(Q),Date.now()+Q$)}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8")),X=new k(Z.message??"subc error",Z.code,Z.detail);return uZ.set(X,$.header.flags),X}catch{return new k(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&e6(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[X,J]of this.pending)if(J.handle&&e6(J.handle,$))this.rejectPending(X,J,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,X]of this.pending)this.rejectPending(Z,X,$)}notSentCallError($,Z){return new Z0("not_sent",`${$}${m$(Z)}`,X3(Z),Z)}outcomeUnknownCallError($,Z){return new Z0("outcome_unknown",`${$}${m$(Z)}`,X3(Z),Z)}terminalCallError($,Z){if(Z instanceof Z0)return Z;return new Z0("terminal",`${$}${m$(Z)}`,X3(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof Z0)return Z;if(Z3(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z,X=new V1){let J=t6($,Z,this.connectionToken,X);return this.liveRoutes.set($,J),J}isLiveHandle($){return w$($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!w$($,this.connectionToken))throw new e0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new e0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let X=new k("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(X),this.sock.close(),this.scheduleReconnectAfterDrop(X),X}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new k("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}decodeReply($){return d8($.header.flags)?$.body:this.parseJson($)}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function Z3($){if($ instanceof t0||$ instanceof x0)return!0;if($ instanceof w0||$ instanceof H1)return!0;if($ instanceof Z0)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof q0)return!0;if($ instanceof k||$ instanceof $0)return!1;let Z=X3($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function tz($){return $ instanceof k&&typeof $.code==="string"}function ez($){if($==="capability_forbidden")return!1;return $==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}var dZ="unknown_channel",cZ="stale_route_epoch";function Q3($,Z){return Z===dZ||Z===cZ}function $G($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??oz,reconnectBackoff:$.reconnectBackoff??G3,sleep:$.sleep??((Z)=>new Promise((X)=>setTimeout(X,Z))),routeOpenRetryDeadlineMs:$.routeOpenRetryDeadlineMs??nz,timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??iz,livenessProbeWindowMs:$.livenessProbeWindowMs??az,onControlPush:$.onControlPush}}function sZ($){if(/\s/u.test($))return!1;let Z=$.indexOf("/v");if(Z<=0||$.indexOf("/v",Z+1)!==-1)return!1;let X=$.slice(0,Z),J=$.slice(Z+2);if(new TextEncoder().encode(X).byteLength>64||J.length===0)return!1;if(!/^[a-z][a-z0-9-]*[a-z0-9]$/u.test(X)&&!/^[a-z]$/u.test(X))return!1;if(X.includes("--"))return!1;if(!/^\d+$/u.test(J)||J.length>1&&J.startsWith("0"))return!1;let z=Number(J);return Number.isSafeInteger(z)&&z>=1&&z<=4294967295}function lZ($,Z,X,J){let z=X?`${X.module_id}\x00${X.launch_nonce}`:"",G=[...J].sort().join("\x00");return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${z}\x00${G}`}function $2($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[J3],X=process.env[z3];if(!Z||!X)return;return{module_id:Z,launch_nonce:X}}function X3($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function m$($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function $3($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}function ZG($){try{let Z=JSON.parse(Buffer.from($).toString("utf8"));return typeof Z.method==="string"&&Z.method.length>0?Z.method:void 0}catch{return}}import{Buffer as Q2}from"node:buffer";var XG=1e4,JG=30000,aZ=30000,zG=250,Z2=64,z2="health.check",nZ=1n,GG=/^[0-9a-f]{32}$/;function G2($){let Z=$.machine_id;return typeof Z==="string"&&GG.test(Z)?Z:void 0}class B3{available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new u("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class u extends Error{code;kind;detail;constructor($,Z,X="terminal",J){super($);this.code=Z,this.kind=X,this.detail=J}}class p${sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=G$();nextCorr=1n;ingressEpochDropCount=0;requestGate=new B3(Z2);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;machineId;constructor($,Z,X,J){this.sock=$,this.currentConn=Z,this.opts=X,this.storage=J.storage,this.machineId=G2(J),this.closed=new Promise((z)=>{this.resolveClosed=z}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,X={}){this.assertLiveHandle($);let J=this.allocateCorr(),z=Y3($,J),G=X.timeoutMs??aZ,Q=B0(T.Request,U0(!1,X.priority??r.Interactive,!1,X.admissionClass??Y0.Normal),$.channel,$.epoch,J,Z);return await new Promise((Y,B)=>{let H=setTimeout(()=>{if(this.pending.delete(z))B(new u("reverse request timed out","request_timeout"))},G);this.pending.set(z,{resolve:(W)=>Y(W.body),reject:B,timer:H}),this.sendOn(this.sock,this.generation,Q).catch((W)=>{let V=this.pending.get(z);if(!V)return;this.pending.delete(z),clearTimeout(V.timer),B(W instanceof Error?W:new u(String(W)))})})}async push($,Z,X={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,B0(T.Push,U0(!1,X.priority??r.Interactive,!1,X.admissionClass??Y0.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,B0(T.Cancel,m0(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,B0(T.Goodbye,m0(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==L0)throw new u(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${L0}`,"invalid_manifest");let Z=YG($),X=await p$.openConnection(Z);return new p$(X.sock,X.conn,Z,X.ack)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await J2($,B0(T.Goodbye,m0(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let X=await z$($.connectionFile),J=Date.now()+($.handshakeTimeoutMs??XG),z=X.endpoints[0],G=await E1.connect(z.host,z.port,J);try{Z?.(G),await h$(G,X,J),await J2(G,WG($));let Q=await UG(G,J);return{sock:G,conn:X,ack:Q}}catch(Q){throw G.close(),Q}}async readLoop($,Z){try{for(;;){let X=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:JG});if(!await this.dispatch(X,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(X){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,X instanceof Error?X:new u(String(X)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,X){let J=null;if($.header.channel!==0){if(J=this.liveRoutes.get($.header.channel)??null,!J||J.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(J){let z=Y3(J,$.header.corr),G=this.pending.get(z);if(G){if($.header.ty===T.Push||$.header.ty===T.StreamData)return!0;if($.header.ty===T.Response||$.header.ty===T.StreamEnd)return this.pending.delete(z),clearTimeout(G.timer),G.resolve($),!0;if($.header.ty===T.Error)return this.pending.delete(z),clearTimeout(G.timer),G.reject(QG($)),!0}}switch($.header.ty){case T.Ping:if($.header.channel===0)await this.sendOn(Z,X,h0($.header.ver,T.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case T.Goodbye:if(!J)return!1;return this.liveRoutes.delete(J.channel),this.abortHandle(J),await this.reportRouteGone(J),!0;case T.Cancel:if(J)this.inflight.get(Y3(J,$.header.corr))?.abort();return!0;case T.Request:if($.header.channel===0)await this.handleControlRequest($,Z,X);else if(J)this.handleDataRequest($,J,Z,X).catch((z)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===X)console.warn("SubcProvider handler failed after its request was dispatched",z)});return!0;default:return!0}}async reportRouteBound($){if(!this.opts.onBound)return;try{await this.opts.onBound($)}catch(Z){console.warn("SubcProvider bound callback failed",Z)}}async reportRouteGone($){if(!this.opts.onRouteGone)return;try{await this.opts.onRouteGone($)}catch(Z){console.warn("SubcProvider route-gone callback failed",Z)}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[X,J]of this.inflight)if(X.startsWith(Z))J.abort();for(let[X,J]of this.pending){if(!X.startsWith(Z))continue;this.pending.delete(X),clearTimeout(J.timer),J.reject(new e0($))}}abortGeneration($){this.abortAllInflight();for(let[Z,X]of this.pending)this.pending.delete(Z),clearTimeout(X.timer),X.reject(new u("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,X){let J=H3($.body);if(J.op===z2){this.handleHealthRequest($,Z,X).catch((V)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===X)console.warn("SubcProvider health handler failed after its request was dispatched",V)});return}if(J.op!=="route.bind")throw new u(`unsupported module control request ${J.op??"<missing op>"}`);let z=iZ(J.route_channel,"route_channel"),G=iZ(J.epoch,"epoch"),Q=this.liveRoutes.get(z);if(Q){if(G<=Q.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${G} does not supersede installed epoch ${Q.epoch} on channel ${z}`,m0(),Z,X);return}this.liveRoutes.delete(Q.channel),this.abortHandle(Q),await this.reportRouteGone(Q)}let Y=t6(z,G,this.connectionToken),B={handle:Y,target:J.target,identity:J.identity,principal:J.principal,consumer_capabilities:J.consumer_capabilities},H;try{H=await this.opts.onBind?.(B)}catch(V){try{await this.sendError($,"route_rejected",V instanceof Error?V.message:String(V),m0(),Z,X)}finally{await this.reportRouteGone(Y)}return}let W=qG(H);if(W){try{await this.sendError($,W.code,W.message,m0(),Z,X)}finally{await this.reportRouteGone(Y)}return}try{await this.sendOn(Z,X,h0($.header.ver,T.Response,m0(),0,0,$.header.corr,W3({op:"route.bind"})))}catch(V){throw await this.reportRouteGone(Y),V}if(this.sock!==Z||this.generation!==X||this.closeStarted||this.closedErr){await this.reportRouteGone(Y);return}this.liveRoutes.set(Y.channel,Y),await this.reportRouteBound(Y)}async handleDataRequest($,Z,X,J){let{corr:z,ver:G}=$.header,Q=Y3(Z,z),Y=new AbortController;this.inflight.set(Q,Y);let B={handle:Z,signal:Y.signal,currentEpoch:()=>this.connectionEpoch,emit:async(V,j={})=>{if(this.assertLiveHandle(Z),Y.signal.aborted)return;await this.sendOn(X,J,h0(G,T.StreamData,U0(!1,j.priority??r.Interactive,!1,j.admissionClass??Y0.Normal),Z.channel,Z.epoch,z,V))}},H=await(this.requestGate??new B3(Z2)).acquire(),W=U0(!1,r.Interactive,!1);try{if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",W,X,J);return}let V=await this.opts.handler(Z,$.body,B);if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",W,X,J);return}if(this.assertLiveHandle(Z),V===void 0)await this.sendOn(X,J,h0(G,T.StreamEnd,W,Z.channel,Z.epoch,z,new Uint8Array(0)));else if(V instanceof Uint8Array)await this.sendOn(X,J,h0(G,T.Response,W,Z.channel,Z.epoch,z,V));else throw new u("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(V){if(V instanceof e0)return;if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",W,X,J);return}await this.sendError($,V instanceof u&&V.code?V.code:"handler_error",V instanceof Error?V.message:String(V),W,X,J)}finally{if(H(),this.inflight.get(Q)===Y)this.inflight.delete(Q)}}async handleHealthRequest($,Z,X){let{corr:J,ver:z}=$.header,G=`control:${X}:${J}`,Q=new AbortController;this.inflight.set(G,Q);let Y=await(this.requestGate??new B3(Z2)).acquire();try{if(Q.signal.aborted)return;let B=await this.opts.health();await this.sendOn(Z,X,h0(z,T.Response,m0(),0,0,J,W3({op:z2,status:B.status,...B.detail===void 0?{}:{detail:B.detail},...B.metrics===void 0?{}:{metrics:B.metrics}})))}catch(B){await this.sendError($,B instanceof u&&B.code?B.code:"health_error",B instanceof Error?B.message:String(B),m0(),Z,X)}finally{if(Y(),this.inflight.get(G)===Q)this.inflight.delete(G)}}async sendError($,Z,X,J,z,G){if($.header.channel!==0){let Q=this.liveRoutes.get($.header.channel);if(!Q||Q.epoch!==$.header.epoch||!this.isLiveHandle(Q))return}await this.sendOn(z,G,h0($.header.ver,T.Error,J,$.header.channel,$.header.epoch,$.header.corr,W3({code:Z,message:X})))}async sendOn($,Z,X){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await J2($,X)}handleUnexpectedDrop($,Z,X){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;if(!this.opts.reconnectOnDrop){this.failFatal(X);return}this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(X,this.generation,$)}scheduleReconnectAfterDrop($,Z,X){if(this.closeStarted)return;let J=this.reconnecting;if(J){if(!this.shouldSupersedeReconnect(J,Z,X))return;J.superseded=!0,J.socket?.close()}let z={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=z,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(z).catch((G)=>{if(this.isCurrentReconnect(z)&&!this.closeStarted)this.failFatal(G instanceof Error?G:new u(String(G)))}).finally(()=>{if(this.isCurrentReconnect(z))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,X=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new u("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let J=await p$.openConnection(this.opts,(G)=>{if(!this.isCurrentReconnect($)){G.close();return}$.socket=G});if(!this.isCurrentReconnect($)||this.closeStarted){if(J.sock.close(),this.closeStarted)throw new u("provider closed");return}let z=this.replaceConnection(J,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new u("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,z);return}catch(J){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw J;if(!HG(J))throw J;await this.opts.sleep(X),X=Math.min(X*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,X){return $.generation<Z||$.socketDied||$.socket===X}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.machineId=G2($.ack),this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=G$(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){if(!this.opts.onConnectionState)return;let X=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(X===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((J)=>{if(X===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",J)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,X){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,reconnect:X}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let $=this.stateQueue[0];if(this.closeStarted||$.generation!==void 0&&$.generation!==this.generation||$.reconnect?.superseded){this.stateQueue.shift();continue}let{event:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(X){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",X),await jG();continue}console.warn("SubcProvider connection-state callback failed",X),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return w$($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new e0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let X=new u("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,X),X}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function Y3($,Z){return`${$.channel}:${$.epoch}:${Z}`}function QG($){try{let Z=H3($.body);return new u(Z.message??"subc error",Z.code,Q3($.header.flags,Z.code)?"not_sent":"terminal",Z.detail)}catch{return new u(Q2.from($.body).toString("utf8")||"subc error")}}function X2($){return $&&$.length>0?$:void 0}function YG($){let Z=X2(process.env[J3]),X=X2(process.env[z3]),J=Z!==void 0&&X!==void 0;return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??G3,sleep:$.sleep??((z)=>new Promise((G)=>setTimeout(G,z))),restoredDebounceMs:$.restoredDebounceMs??zG,onConnectionState:$.onConnectionState,launchNonce:X2($.launchNonce??X),reconnectOnDrop:$.reconnectOnDrop??!J}}function BG($){if($===null)return null;let Z=new Set($??[]);return Z.add(z2),[...Z]}function WG($){let Z=$.launchNonce;return B0(T.Hello,m0(),0,0,nZ,W3({manifest:KG($.manifest),protocol_ver:L0,control_ops:BG($.controlOps),...Z?{launch_nonce:Z}:{}}))}function HG($){if($ instanceof u)return $.code==="duplicate_module_id";if($ instanceof t0||$ instanceof x0)return!0;if($ instanceof w0||$ instanceof H1)return!0;if($ instanceof q0)return!0;if($ instanceof $0)return!1;let Z=VG($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function VG($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function jG(){await new Promise(($)=>setTimeout($,0))}function m0(){return U0(!1,r.Passive,!1)}async function J2($,Z){await b0($,I0(Z),Date.now()+aZ)}async function UG($,Z){let X=await $.readFrame(Z,Z);switch(X.header.ty){case T.HelloAck:{let J=H3(X.body);if(J.negotiated_ver!==L0)throw new u(`subc negotiated protocol ${J.negotiated_ver}; expected exactly ${L0}`,"unsupported_version");return J}case T.Error:{let J=H3(X.body);throw new u(`subc rejected HELLO: ${J.code??"unknown"} — ${J.message??"subc error"}`,J.code)}default:throw new u(`unexpected frame ${T[X.header.ty]} awaiting HELLO_ACK`)}}function W3($){return new Uint8Array(Q2.from(JSON.stringify($),"utf8"))}function H3($){return JSON.parse(Q2.from($).toString("utf8"))}function iZ($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new u(`route.bind ${Z} must be an integer`);return $}function qG($){if($===void 0||$===!0)return null;if($===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if($.accept)return null;return{code:$.code??"route_rejected",message:$.message??"route.bind rejected by provider"}}function KG($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(DG),consumes:$.consumes.map(NG),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function DG($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function NG($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}var j3="subc-connection.json",oZ="subc-",tZ=".connection.json";function eZ(){let $=process.env.HOME;return $?Y$($,".local","share","cortexkit","run",j3):void 0}function PG(){let $=process.env.XDG_RUNTIME_DIR;if($)return Y$($,j3);let Z=eZ();if(Z)return Z;return Y$(FG().homedir,".local","share","cortexkit","run",j3)}function OG(){if(process.env.SUBC_CONNECTION_FILE)return process.env.SUBC_CONNECTION_FILE;let $=process.env.XDG_RUNTIME_DIR;if($){let z=Y$($,j3);if(V3(z))return z}let Z=eZ();if(Z&&V3(Z))return Z;let X=Y$(rZ(),`${oZ}${_G()}${tZ}`);if(V3(X))return X;let J=CG(rZ());return J.length===1?J[0]:void 0}function _G($=process.getuid??null,Z=process.env){if($)return String($());for(let X of["USER","USERNAME","HOME","USERPROFILE"]){let J=Z[X];if(J)return Array.from(J,(z)=>/^[a-zA-Z0-9_-]$/.test(z)?z:"_").join("")}return"unknown"}function $7(){return OG()??PG()}function u$($){return $?.trim()||process.env.SUBC_CONNECTION_FILE||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||$7()}function V3($){try{return LG($).isFile()}catch{return!1}}function CG($){let Z;try{Z=MG($)}catch{return[]}let X=[];for(let J of Z){if(typeof J!=="string")continue;if(!J.startsWith(oZ)||!J.endsWith(tZ))continue;let z=Y$($,J);if(V3(z))X.push(z)}return X.sort(),X}import{createHash as TG}from"node:crypto";import{existsSync as AG,realpathSync as Z7}from"node:fs";import{dirname as RG,relative as SG,resolve as IG}from"node:path";function X7($){let Z=$,X;try{X=Z7(Z)}catch(J){if(J.code!=="ENOENT")throw J;let z=Z;while(!AG(z)){let G=RG(z);if(G===z)break;z=G}X=IG(Z7(z),SG(z,Z))}return TG("sha256").update(X).digest("hex")}function Y2($,Z){return{project_root:$,harness:"opencode",session:`store-${X7(Z)}`}}import{AsyncLocalStorage as xG}from"node:async_hooks";import{readFile as J7}from"node:fs/promises";var bG=new xG;function z7($,Z){return $.split(`
96
+ `).filter((X)=>X.trim()!==""&&!X.trimStart().startsWith("#")).map((X)=>{let J=X.split(":");if(J.length!==Z||!J[0]||/\s/.test(J[0])||!/^\d+$/.test(J[2])||!Number.isSafeInteger(Number(J[2]))||Number(J[2])>4294967295||Z===7&&(!/^\d+$/.test(J[3])||!Number.isSafeInteger(Number(J[3]))||Number(J[3])>4294967295))throw Error("malformed account record");if(Z===4&&J[3]!==""&&J[3].split(",").some((z)=>z===""||/\s/.test(z)))throw Error("malformed group members");return J})}async function U3($,Z=bG.getStore()??{euid:process.geteuid?.(),egid:process.getegid?.(),passwdPath:"/etc/passwd",groupPath:"/etc/group"}){if(($.mode&18)===0||($.mode&512)!==0)return!0;if(($.mode&2)!==0||Z.euid===void 0||Z.egid===void 0||$.uid!==Z.euid||$.gid!==Z.egid)return!1;try{let X=z7(new TextDecoder("utf-8",{fatal:!0}).decode(await J7(Z.passwdPath)),7),J=z7(new TextDecoder("utf-8",{fatal:!0}).decode(await J7(Z.groupPath)),4),z=X.filter((Y)=>Number(Y[2])===Z.euid),G=J.filter((Y)=>Number(Y[2])===Z.egid);if(z.length!==1||G.length!==1)return!1;let Q=z[0][0];return(G[0][3]===""||G[0][3].split(",").every((Y)=>Y===Q))&&!X.some((Y)=>Number(Y[2])!==Z.euid&&Number(Y[3])===Z.egid)}catch{return!1}}import{randomBytes as EG}from"node:crypto";import{chmod as kG,mkdir as fG,open as yG,realpath as vG,rename as gG,stat as hG,unlink as wG}from"node:fs/promises";import{basename as mG,dirname as G7,join as pG}from"node:path";var uG=/^[0-9a-f]{64}$/;function lG($){if(!uG.test($.token))throw Error("enrollment token must be exactly 64 lowercase hex characters");if(!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw Error("enrollment token generation must be a positive safe integer")}async function dG($){let Z;try{Z=await vG($)}catch{return}for(;;){let X=await hG(Z).catch(()=>{return});if(X&&!await U3(X))throw Error(`enrollment token ancestor ${Z} is group- or world-writable without sticky bit`);let J=G7(Z);if(J===Z)return;Z=J}}async function B2($,Z){lG(Z);let X=G7($);await fG(X,{recursive:!0,mode:448}),await dG(X);let J=pG(X,`.${mG($)}.${process.pid}.${EG(12).toString("hex")}.tmp`),z=!1;try{let G=await yG(J,"wx",384);z=!0;try{await G.writeFile(`${JSON.stringify(Z)}
97
+ `,"utf8"),await G.sync(),await kG(J,384)}finally{await G.close()}await gG(J,$),z=!1}finally{if(z)await wG(J).catch(()=>{return})}}var Q7=["transient","permanent","auth_required","context_overflow"];class E0 extends Error{code;action;["class"];constructor($,Z,X){super(`Claustrum credential request failed: ${$}`);this.code=$,this.action=X,this.name="ClaustrumCredentialError",this.class=Z}}function B$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y7($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function y($,Z="invalid_response",X=(J)=>console.warn(J)){let J=B$($)&&B$($.result)?$.result:void 0,z=J&&B$(J.error)?J.error:void 0,G=z?.class,Q=z?.code,Y=typeof G==="string"&&Q7.includes(G),B=typeof Q==="string",W=Y&&B?G:"transient";if(typeof G!=="string")X("unknown");else if(!Y)X(G);return new E0(B?Q:Z,W,Y7(W))}function f1($){return B$($)&&B$($.result)&&B$($.result.error)}var B7="claustrum",iG=60000;function F0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0?$:void 0}function p0($){return $===void 0||typeof $==="string"}function W7($,Z){if(f1($))throw y($,"invalid_response",Z);let X=F0($)&&F0($.result)?$.result:void 0,J=X?.payload;if(!Array.isArray(J)||J.length===0||!J.every((q)=>typeof q==="number"&&Number.isInteger(q)&&q>=0&&q<=255))throw y($,"invalid_response",Z);let z=H2(X?.record_version);if(z===void 0)throw y($,"invalid_record_version",Z);let G=X?.expires_at_ms,Q=G===void 0||G===null?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(Q===void 0)throw y($,"invalid_expiry",Z);let Y=X?.credential_id,B=X?.project_id,H=X?.account_id,W=X?.email,V=X?.org_name;if(!p0(Y)||!p0(B)||!p0(H)||!p0(W)||!p0(V))throw y($,"invalid_response",Z);let j;try{j=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(J))}catch{throw y($,"invalid_response",Z)}return{material:j,recordVersion:z,expiresAtMs:Q,credentialId:Y,projectId:B,accountId:H,email:W,orgName:V}}function aG($,Z){if(f1($))throw y($,"invalid_response",Z);let X=F0($)&&F0($.result)?$.result:void 0,J=X?.record_version,z=J===void 0?void 0:H2(J),G=X?.credential_id;if(typeof X?.ready!=="boolean"||X?.last_error_code!==void 0&&X?.last_error_code!==null&&typeof X?.last_error_code!=="string"||typeof X?.lease_held!=="boolean"||J!==void 0&&z===void 0||!p0(G)||X?.stale_pending!==void 0&&typeof X.stale_pending!=="boolean")throw y($,"invalid_status",Z);return{ready:X.ready,lastErrorCode:X.last_error_code??null,leaseHeld:X.lease_held,...G===void 0?{}:{credentialId:G},...z===void 0?{}:{recordVersion:z},...X.stale_pending===void 0?{}:{stalePending:X.stale_pending}}}class y1{#$;#Z;#Q;#X;#B;#z;#J=null;#Y=0;#H=!1;constructor($,Z,X,J,z,G){this.#$=$,this.#Z=Z,this.#Q=X,this.#X=J,this.#B=z,this.#z=G}static async connect($={}){let Z=u$($.connectionFile),X=$.connector??((G)=>k1.connect(G)),J=$.identity??Y2($.projectRoot??process.cwd(),$.storagePath??process.cwd()),z=await X({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new y1(z,X,Z,$.handshakeTimeoutMs,J,$.logger??((G)=>console.warn(G)))}async getCredential($,Z){let X=await this.#G("credential.get",{handle:$,min_ttl_ms:Z,force_refresh:!1});return W7(X,this.#z)}async statusCredential($){let Z=await this.#G("credential.status",{handle:$});return aG(Z,this.#z)}async reportAuthFailure($){let Z=await this.#G("credential.report_auth_failure",{handle:$.handle,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(f1(Z))throw y(Z,"invalid_response",this.#z);if((F0(Z)&&F0(Z.result)?Z.result:void 0)?.accepted!==!0)throw y(Z,"invalid_response",this.#z)}async listScoped($){let Z=await this.#G("credential.list_scoped",$===void 0?{}:{enrollment_token:$});return nG(Z,this.#z)}async getScoped($){let Z=await this.#G("credential.get_scoped",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,min_ttl_ms:$.minTtlMs});return W7(Z,this.#z)}async reportAuthFailureScoped($){let Z=await this.#G("credential.report_auth_failure",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(f1(Z))throw y(Z,"invalid_response",this.#z);if((F0(Z)&&F0(Z.result)?Z.result:void 0)?.accepted!==!0)throw y(Z,"invalid_response",this.#z)}async enrollPropose($){let Z=await this.#G("auth.enroll_propose",{proposed_name:$.name,request_secret_hash:$.requestSecretHash}),J=W2(Z,this.#z).request_id;if(typeof J!=="string"||J.length===0)throw y(Z,"invalid_response",this.#z);return{requestId:J}}async enrollPoll($){let Z=await this.#G("auth.enroll_poll",{request_id:$.requestId,request_secret:$.requestSecret});return rG(Z,this.#z)}async enrollRotate($){let Z=await this.#G("auth.enroll_rotate",{token:$.token,expected_token_generation:$.expectedTokenGeneration}),X=W2(Z,this.#z),J=X.token,z=X.token_generation;if(typeof J!=="string"||J.length===0||typeof z!=="number"||!Number.isInteger(z)||z<0)throw y(Z,"invalid_response",this.#z);return{token:J,tokenGeneration:z}}close(){this.#H=!0,this.#$.close()}async#G($,Z){let X=this.#$;try{return await X.call(B7,$,Z,{identity:this.#B,consumerIdentity:null})}catch(J){if(this.#V(J)){try{if(this.#$===X)await this.#j()}catch(z){throw this.#W(z)}try{return await this.#$.call(B7,$,Z,{identity:this.#B,consumerIdentity:null})}catch(z){throw this.#W(z)}}throw this.#W(J)}}#W($){if($ instanceof E0)return $;let Z=$ instanceof Z0&&$.code?$.code:"transport_error";return new E0(Z,"transient","retry")}#V($){return!this.#H&&$ instanceof Z0&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"&&$.code!=="unknown_module"}async#j(){if(this.#H)throw Error("Claustrum client is closed");if(this.#J){await this.#J;return}let $=Date.now();if($<this.#Y)throw Error("Claustrum client reconnect is backed off");this.#Y=$+iG,this.#J=this.#Z({connectionFile:this.#Q,handshakeTimeoutMs:this.#X}).then((Z)=>{if(this.#H)throw Z.close(),Error("Claustrum client is closed");let X=this.#$;this.#$=Z,X.close()}).finally(()=>{this.#J=null}),await this.#J}}function nG($,Z){if(f1($))throw y($,"invalid_response",Z);let X=F0($)&&F0($.result)?$.result:void 0,J=X?.credentials;if(!Array.isArray(J))throw y($,"invalid_response",Z);let z=X?.view;if(typeof z!=="string"||z.length===0)throw y($,"invalid_response",Z);return{rows:J.map((Q)=>{if(!F0(Q))throw y($,"invalid_response",Z);let Y=H2(Q.record_version);if(Y===void 0)throw y($,"invalid_record_version",Z);let B=(V)=>{if(!Array.isArray(V)||!V.every((j)=>typeof j==="string"))throw y($,"invalid_response",Z);return V};if(typeof Q.id!=="string"||typeof Q.type!=="string"||typeof Q.state!=="string")throw y($,"invalid_response",Z);let H=Q.created_at_ms===void 0||Q.created_at_ms===null?null:typeof Q.created_at_ms==="number"&&Number.isFinite(Q.created_at_ms)?Q.created_at_ms:void 0;if(H===void 0)throw y($,"invalid_response",Z);let W=Q.auth_method;if(W!==void 0&&W!=="apikey"&&W!=="chatgpt"&&W!=="antigravity"&&W!=="oauth")throw y($,"invalid_response",Z);if(!p0(Q.refresh_adapter))throw y($,"invalid_response",Z);if(!p0(Q.account_id)||!p0(Q.email)||!p0(Q.org_name))throw y($,"invalid_response",Z);return{id:Q.id,categories:B(Q.categories),credentialType:Q.type,serves:B(Q.serves),providerIds:Q.provider_ids===void 0?[]:B(Q.provider_ids),authMethod:W,state:Q.state,refreshAdapter:Q.refresh_adapter,recordVersion:Y,operations:B(Q.operations),createdAtMs:H,accountId:Q.account_id,email:Q.email,orgName:Q.org_name}}),view:z}}function W2($,Z){if(f1($))throw y($,"invalid_response",Z);let X=F0($)&&F0($.result)?$.result:void 0;if(X===void 0)throw y($,"invalid_response",Z);return X}function rG($,Z){let X=W2($,Z),J=X.status;if(J==="pending")return{status:"pending"};if(J==="denied")return{status:"denied"};if(J!=="approved")throw y($,"invalid_response",Z);let{name:z,token:G,token_generation:Q}=X;if(typeof z!=="string"||typeof G!=="string"||G.length===0||typeof Q!=="number"||!Number.isInteger(Q))throw y($,"invalid_response",Z);return{status:"approved",name:z,token:G,tokenGeneration:Q}}function V2($){let Z=new AbortController,X=[],J=!1,z=()=>{if(J)return;J=!0;for(let{source:Y,listener:B}of X)Y.removeEventListener("abort",B);X.length=0},G=(Y)=>{if(J||Z.signal.aborted)return;Z.abort(Y),z()},Q=$.find((Y)=>Y.aborted);if(Q)return Z.abort(Q.reason),{signal:Z.signal,dispose:z};for(let Y of $){if(Z.signal.aborted)break;let B=()=>G(Y.reason);if(X.push({source:Y,listener:B}),Y.addEventListener("abort",B,{once:!0}),Y.aborted)G(Y.reason)}return{signal:Z.signal,dispose:z}}import{createHash as oG,randomBytes as tG,randomUUID as eG}from"node:crypto";import{constants as H7}from"node:fs";import{chmod as $Q,mkdir as ZQ,open as K7,readFile as V7,realpath as XQ,rename as JQ,stat as D7,unlink as N7}from"node:fs/promises";import{basename as M7,dirname as g1,extname as j7,isAbsolute as U7,join as q2,resolve as zQ}from"node:path";class R extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var GQ=1,j2=16384,L7=30000,K2=/^[0-9a-f]{64}$/,F7=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),P7=new Set(["pending_queue_full"]);function U2($){if(!($ instanceof E0))return;if(F7.has($.code))return{code:$.code,disposition:"terminal"};if(P7.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function D2($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new R("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function N2($){return y1.connect($)}function O7($){let Z=j7($)||".json",X=M7($,j7($));return{statePath:q2(g1($),`${X}-state${Z}`),tokenPath:$}}function M2($){let Z=$.override?.trim();if(Z&&!U7(Z)&&!$.cwd)throw new R("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?U7(Z)?Z:zQ($.cwd,Z):q2($.stateDir,`${$.host}-enrollment.json`);return O7(X)}function _7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function q3($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function C7($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function l$(){return new R("invalid-state","invalid Claustrum enrollment state")}function D3($){if(!_7($)||$.version!==GQ||typeof $.proposedName!=="string"||$.proposedName.length===0)throw l$();if($.phase==="pending"){if(!K2.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!q3($.createdAt)||!q3($.updatedAt))throw l$();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!C7($.tokenGeneration)||!q3($.updatedAt))throw l$();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!q3($.updatedAt))throw l$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw l$()}function L2($){if(!_7($)||!K2.test(String($.token??""))||!C7($.token_generation))throw new R("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function QQ($){if(!$.isFile())throw new R("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new R("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new R("unsafe-file","Claustrum enrollment file must be owned by the current user")}function YQ($){try{return JSON.parse($)}catch{throw new R("invalid-state","Claustrum enrollment file is not valid JSON")}}async function U1($){let Z;try{Z=await K7($,H7.O_RDONLY|H7.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new R("unsafe-file","Claustrum enrollment file could not be opened safely")}try{QQ(await Z.stat());let X=Buffer.alloc(j2+1),{bytesRead:J}=await Z.read(X,0,X.byteLength,0);if(J>j2)throw new R("unsafe-file","Claustrum enrollment file is too large");return YQ(X.subarray(0,J).toString("utf8"))}finally{await Z.close()}}function q7($,Z){let X=[];for(let J of $.split(`
98
+ `)){if(J.trim()===""||J.startsWith("#"))continue;let z=J.split(":");if(z.length!==Z||!/^[^\s:,]+$/.test(z[0]??"")||!/^\d+$/.test(z[2]??"")||!Number.isSafeInteger(Number(z[2]))||Z===7&&(!/^\d+$/.test(z[3]??"")||!Number.isSafeInteger(Number(z[3])))||Z===4&&z[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(z[3]??""))return;X.push(z)}return X}async function BQ($,Z,X){try{let[J,z]=await Promise.all([V7(X.passwdPath??"/etc/passwd","utf8"),V7(X.groupPath??"/etc/group","utf8")]),G=q7(J,7),Q=q7(z,4);if(!G||!Q)return!1;let Y=G.filter((V)=>Number(V[2])===$),B=Q.filter((V)=>Number(V[2])===Z);if(Y.length!==1||B.length!==1)return!1;let H=Y[0]?.[0],W=B[0]?.[3]??"";return(W===""||W.split(",").every((V)=>V===H))&&!G.some((V)=>Number(V[2])!==$&&Number(V[3])===Z)}catch{return!1}}async function T7($,Z={}){let X=process.geteuid?.();if(X===void 0)return;let J=process.getegid?.(),z;try{z=await XQ($)}catch{return}let G;for(;;){let Q=await D7(z).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=J!==void 0&&await BQ(X,J,Z);if((Q.mode&2)!==0||Q.uid!==X||Q.gid!==J||!G)throw new R("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${z}. Another user could replace it. Run: chmod g-w,o-w ${z}`)}let Y=g1(z);if(Y===z)return;z=Y}}async function K3($){await ZQ($,{recursive:!0,mode:448});let Z=await D7($),X=process.geteuid?.();if(X!==void 0&&Z.uid!==X)throw new R("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((Z.mode&63)!==0)await $Q($,448)}async function v1($,Z,X={}){let J=g1($);await K3(J),await T7(J,X);let z=`${JSON.stringify(Z)}
99
+ `;if(Buffer.byteLength(z)>j2)throw new R("invalid-state","Claustrum enrollment state is too large");let G=q2(J,`.${M7($)}.${process.pid}.${eG()}.tmp`),Q,Y=!1;try{Q=await K7(G,"wx",384),Y=!0,await Q.writeFile(z,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await JQ(G,$),Y=!1}finally{if(await Q?.close().catch(()=>{}),Y)await N7(G).catch(()=>{})}}async function d$($,Z){let X=await U1($.tokenPath),J=X===void 0?void 0:L2(X),z=await U1($.statePath),G=z===void 0?void 0:D3(z);if(J)return{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:J.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return j1(G)}async function F2($,Z){let X;try{X=await d$($,Z)}catch(J){if(!(J instanceof R)||J.kind!=="invalid-state"&&J.kind!=="invalid-token")return"unreadable";try{let z=await U1($.statePath);if(z===void 0)return"unreadable";let G=D3(z);return G.phase==="approved"&&G.proposedName===Z?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in X&&X.proposedName!==Z)return"unreadable";if(X.state==="approved"||X.state==="blocked"&&X.code==="missing_token")return"vault";return"local"}async function P2($){let Z=await U1($);if(Z===void 0)throw new R("not-enrolled","Claustrum enrollment is not configured");return L2(Z)}function j1($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function A7(){return new R("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class N3{#$;#Z;#Q;#X;#B;#z;#J;constructor($){this.#J=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#Q=$.proposedName,this.#X=$.now??Date.now,this.#B=$.mintSecret??(()=>tG(32).toString("hex")),this.#z=$.writeTokenFile??B2}async status(){return d$(this.#Z,this.#Q)}async resetTerminal(){return R7(this.#Z,this.#Q)}async#Y($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#X()};return await v1(this.#Z.statePath,X,this.#J),j1(X)}async reconcile(){await K3(g1(this.#Z.statePath));let $=await t({name:"ceremony",path:this.#Z.statePath,ttlMs:L7,renew:!0});if(!$)return{state:"busy"};try{let Z=await U1(this.#Z.tokenPath),X=Z===void 0?void 0:L2(Z),J=await U1(this.#Z.statePath),z=J===void 0?void 0:D3(J);if(z&&z.proposedName!==this.#Q)throw A7();if(X){if(!z||z.phase==="pending"){let Q={version:1,phase:"approved",proposedName:z?.proposedName??this.#Q,tokenGeneration:X.token_generation,updatedAt:this.#X()};await v1(this.#Z.statePath,Q,this.#J),z=Q}return{state:"approved",proposedName:z.proposedName,...z.phase==="approved"&&z.approvedName!==void 0&&{approvedName:z.approvedName},tokenGeneration:X.token_generation}}if(z?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:z.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await v1(this.#Z.statePath,Q,this.#J),j1(Q)}if(z&&z.phase!=="pending")return j1(z);if(!z){let Q=this.#X();if(z={version:1,phase:"pending",proposedName:this.#Q,requestSecret:this.#B(),createdAt:Q,updatedAt:Q},!K2.test(z.requestSecret))throw new R("invalid-state","invalid minted Claustrum enrollment secret");await v1(this.#Z.statePath,z,this.#J)}if(!z.requestId)try{let Q=oG("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),Y=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:Q});z={...z,requestId:Y.requestId,updatedAt:this.#X()},await v1(this.#Z.statePath,z,this.#J)}catch(Q){let Y=U2(Q);if(!Y)throw Q;if(Y.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:Y.code};return this.#Y(z,Y.code)}let G=z.requestId;if(!G)return j1(z);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:z.requestSecret});if(Q.status==="pending")return j1(z);if(Q.status==="denied"){let B={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#X()};return await v1(this.#Z.statePath,B,this.#J),j1(B)}await K3(g1(this.#Z.tokenPath)),await T7(g1(this.#Z.tokenPath),this.#J),await this.#z(this.#Z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let Y={version:1,phase:"approved",proposedName:z.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#X()};return await v1(this.#Z.statePath,Y,this.#J),j1(Y)}catch(Q){let Y=U2(Q);if(!Y)throw Q;if(Y.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:G,retryCode:Y.code};return this.#Y(z,Y.code)}}finally{await $.release()}}}async function R7($,Z){await K3(g1($.statePath));let X=await t({name:"ceremony",path:$.statePath,ttlMs:L7,renew:!0});if(!X)return"busy";try{if(await U1($.tokenPath)!==void 0)return"refused-approved";let J=await U1($.statePath);if(J===void 0)return"idle";let z=D3(J);if(z.proposedName!==Z)throw A7();if(z.phase==="pending")return"refused-pending";return await X.assertOwned(),await N7($.statePath),"reset"}finally{await X.release()}}var c$="claustrum-tombstone:v1:";function M3($){return`${c$}${$}`}function O2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function L3($){return typeof $==="string"&&$.startsWith(c$)}function S7($,Z){if(!O2($)||$.type!=="oauth")return!1;return $.refresh===M3(Z)}function I7($,Z){if(S7($,Z))return"placeholder";if(O2($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!L3($.refresh))return"login";if(O2($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function _2($){let Z=I7($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new R("host-slot-login",`${$.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if($.mode==="local"&&Z==="placeholder")throw new R("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function x7($,Z){return Z!==void 0&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function WQ($,Z){if(Z===void 0)return"reauthorize-failed";if(Z.credentialId!==$.credentialId)return"credential-changed";if(Z.accountIdentity!==$.accountIdentity)return"account-changed";if(Z.recordVersion===$.recordVersion)return"version-unchanged";return"rotated"}var b7=s("claustrum");function A2($,Z,X,J=b7){let z=x7(Z,X);return J.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:z,reason:WQ(Z,X)}),z}var T2=300000;function C2(){return new R("invalid-material","Claustrum returned invalid credential material")}function HQ($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw C2()}if(!X||typeof X!=="object")throw C2();let J=X,z=J.access_token??J.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(c$))throw C2();return Z}function VQ($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}class F3{#$;#Z;#Q;#X;#B;#z;#J;#Y=new WeakMap;#H=new WeakMap;#G=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>P2(Z);else throw new R("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#X=$.family,this.#B=$.parseIdentity,this.#z=$.requireAssertion??!1,this.#Q=$.now??Date.now,this.#J=$.logger??b7}#W($){if(this.#G)throw new R("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#V($){this.#W($);let Z=await this.#Z();if(this.#W($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new R("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#j($,Z){this.#W(Z);let X,J;try{let z=$();X=Z?await Promise.race([z,new Promise((G,Q)=>{let Y=()=>Q(Z.reason);if(Z.addEventListener("abort",Y,{once:!0}),J=()=>Z.removeEventListener("abort",Y),Z.aborted)Y()})]):await z}catch(z){if(this.#W(Z),z instanceof E0)throw z;throw new R("unavailable","Claustrum scoped operation unavailable")}finally{J?.()}return this.#W(Z),X}async discover($){let Z=await this.#V($),X=await this.#j(()=>this.#$.listScoped(Z),$),J=[],z=[],G=new Map;for(let Y of X.rows){let B=VQ(Y,this.#X);if(!B)continue;z.push({row:Y,type:B}),G.set(Y.id,(G.get(Y.id)??0)+1)}let Q=[];for(let{row:Y,type:B}of z){let H;if(!Y.id.trim())H="empty credential id";else if((G.get(Y.id)??0)>1)H="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())H="blank account identity";else if(!Y.state.trim())H="empty state";if(H){J.push({...Y.id.trim()&&{credentialId:Y.id},reason:H});continue}Q.push(Object.freeze({credentialId:Y.id,credentialType:B,...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of J)this.#J.warn("skipped malformed vault record",Y);return{view:X.view,credentials:Object.freeze(Q),skipped:Object.freeze(J)}}async authorize($,Z){if(!$.credentialId)throw new R("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:J,accountIdentity:z}=$;if(this.#z&&z===void 0)throw new R("identity-unasserted","Claustrum dispatch requires a known account identity");let G=await this.#V(Z),Q=await this.#j(()=>this.#$.getScoped({credentialId:X,enrollmentToken:G,...J==="oauth"&&{minTtlMs:T2}}),Z);if(Q.credentialId!==void 0&&Q.credentialId!==X)throw new R("identity-changed","Claustrum served credential identity changed");let Y=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||Y===null&&J==="oauth"||Y!==null&&(!Number.isFinite(Y)||Y-this.#Q()<T2))throw new R("insufficient-validity","Claustrum served credential has insufficient validity");let B=HQ(Q.material),H=Q.accountId?.trim()?Q.accountId:void 0;if(this.#z&&(Q.credentialId===void 0||H===void 0))throw new R("identity-unasserted","Claustrum served credential did not assert its identity");let W=H===void 0?this.#B?.(B):void 0,V=H??W;if(z!==void 0&&V!==void 0&&V!==z)throw new R("identity-changed","Claustrum served credential identity changed");let j=V??z,U=Object.freeze(Object.defineProperty({credentialId:X,credentialType:J,...j!==void 0&&{accountIdentity:j},accountIdentitySource:H!==void 0?"asserted":W!==void 0?"parsed":z!==void 0?"expected":"none",...z!==void 0&&{expectedAccountIdentity:z},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...H!==void 0&&{assertedAccountIdentity:H},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:Y},"accessToken",{value:B,enumerable:!1}));return this.#Y.set(U,G),U}async reportFailure($,Z,X){if(Z!==401)return;this.#W();let J=this.#Y.get($);if(!J)throw new R("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#H.get($);if(z)return z;let G=this.#j(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:J,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#H.set($,G);try{await G,this.#J.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(Q){throw this.#H.delete($),Q}}close(){if(this.#G)return;this.#G=!0,this.#$.close()}}import{createHash as jQ}from"node:crypto";import{readFile as UQ}from"node:fs/promises";function E7($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function R2($,Z,X){return $.some((J)=>E7(J,Z,X))}function S2($,Z,X){let J={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==X),J]}function I2($,Z,X){return $.filter((J)=>!Z.some((z)=>E7(J,z,X)))}var f7="vault:";function qQ($){return jQ("sha256").update($).digest("hex")}function KQ($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function DQ($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function q1($){return[$.credentialId,...$.aliases??[]]}function y7($,Z,X={}){let J=X.now??Date.now(),z=X.routePrefix??f7,G=X.reservedRouteIds??new Set,Q=$?.rows??[],Y=[...$?.declined??[]],B=Z.skipped.length===0,H=new Set(Z.credentials.map((M)=>M.credentialId)),W=new Set(Z.skipped.flatMap((M)=>M.credentialId===void 0?[]:[M.credentialId])),V=Z.skipped.some((M)=>M.credentialId===void 0),j=(M)=>!H.has(M)&&(W.has(M)||V),q=new Map;for(let M of Q){if(M.accountIdentity===void 0)continue;for(let D of q1(M))if(!q.has(D))q.set(D,M.accountIdentity)}let U=new Map;for(let M of Z.credentials){let D=M.accountIdentity!==void 0?{credential:M,identity:M.accountIdentity,claimed:!0}:{credential:M,identity:q.get(M.credentialId),claimed:!1},P=DQ(D),S=U.get(P)??[];S.push(D),U.set(P,S)}let L=new Set,N=new Set(G),K=[],F=(M,D)=>M.credential.credentialId.localeCompare(D.credential.credentialId),C=[...U.values()].map((M)=>M.toSorted(F)).sort((M,D)=>M[0]&&D[0]?F(M[0],D[0]):0);for(let M of C){let D=M[0]?.identity,P=M.filter((I)=>I.credential.state==="active"),S=P.length?P:M,f=S.filter((I)=>I.claimed),n=f.length?f:S,_0=new Set(M.map((I)=>I.credential.credentialId)),h=Q.find((I)=>!L.has(I)&&q1(I).some((J0)=>_0.has(J0))&&(I.accountIdentity===void 0||I.accountIdentity===D)),g=n.find((I)=>I.credential.credentialId===h?.credentialId)??n[0];if(!g)continue;let l=g.credential,X0=h??(D===void 0?void 0:Q.find((I)=>!L.has(I)&&I.accountIdentity===D));if(X0)L.add(X0);let d=X0?.routeId;if(!d||G.has(d)){let I=`${z}${l.credentialId}${D===void 0?"":`~${qQ(D).slice(0,10)}`}`;d=I;for(let J0=2;N.has(d);J0++)d=`${I}~${J0}`}N.add(d);let c0=X0?q1(X0).filter(j):[],A=[...new Set([...M.map((I)=>I.credential.credentialId),...c0])].filter((I)=>I!==l.credentialId).sort((I,J0)=>I.localeCompare(J0)),x=X.mapAccount?.(l)??{};K.push({previousIndex:X0?Q.indexOf(X0):1/0,row:{routeId:d,credentialId:l.credentialId,credentialType:l.credentialType,...D!==void 0&&{accountIdentity:D},...A.length&&{aliases:A},state:l.state,label:x.label?.trim()||KQ(l),...l.email!==void 0&&{email:l.email},...l.orgName!==void 0&&{orgName:l.orgName},enabled:![l.credentialId,...A].some((I)=>R2(Y,I,D)),addedAt:X0?.addedAt??J,...X0?.quota!==void 0&&{quota:X0.quota},...!g.claimed&&D!==void 0&&{unclaimed:!0}}})}return Q.forEach((M,D)=>{if(L.has(M)||!q1(M).some(j))return;if(N.has(M.routeId))return;let[P,...S]=q1(M).filter((_0)=>!H.has(_0));if(P===void 0)return;N.add(M.routeId);let{aliases:f,...n}=M;K.push({previousIndex:D,row:{...n,credentialId:P,...S.length&&{aliases:S},stale:!0}})}),K.sort((M,D)=>M.previousIndex===D.previousIndex?M.row.credentialId.localeCompare(D.row.credentialId):M.previousIndex-D.previousIndex),{version:1,view:Z.view,complete:B,...!B&&{rejected:Z.skipped.map((M)=>({...M.credentialId!==void 0&&{credentialId:M.credentialId},reason:M.reason}))},rows:K.map((M)=>M.row),declined:Y}}function x2($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function P3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function W$($){return $===void 0||typeof $==="string"}function NQ($){if(!P3($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!W$($.accountIdentity)||!W$($.email)||!W$($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((Z)=>typeof Z==="string"))||$.quota!==void 0&&!o($.quota)||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return $}var MQ=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function k7($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!P3(X)||!W$(X.credentialId)||typeof X.reason!=="string"||!MQ.has(X.reason))return;Z.push(X)}return Z}function LQ($){if(!P3($)||$.version!==1||!W$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!k7($.rejected))throw new R("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let G=NQ(z);if(!G)throw new R("invalid-state","Claustrum roster file is not valid");Z.push(G)}let X=[];for(let z of $.declined){if(!P3(z)||typeof z.credentialId!=="string"||!W$(z.accountIdentity))throw new R("invalid-state","Claustrum roster file is not valid");X.push(z)}let J=k7($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...J&&{rejected:J},rows:Z,declined:X}}async function K1($){let Z;try{Z=await UQ($,"utf8")}catch(J){if(J.code==="ENOENT")return;throw J}let X;try{X=JSON.parse(Z)}catch{throw new R("invalid-state","Claustrum roster file is not valid")}return LQ(X)}var FQ={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},PQ={name:"claustrum-roster",ttlMs:30000};async function s$($,Z,X={}){return H8($,FQ,async(J)=>{let z=await K1($),{next:G,result:Q}=await Z(z,{assertOwned:()=>J.assertOwned()});if(G)await J.assertOwned(),await P0($,G,{beforeRename:async()=>{await X.beforePublish?.(),await J.assertOwned()}});return Q})}function b2($,Z){return s$($,(X)=>{let J=X?.rows.find((G)=>G.routeId===Z);if(!X||!J)throw new R("route-unavailable","Claustrum route is not in the roster");let z=S2(X.declined,J.credentialId,J.accountIdentity);return{next:{...X,declined:z,rows:X.rows.map((G)=>G===J?{...G,enabled:!1}:G)},result:void 0}})}function E2($,Z){return s$($,(X)=>{let J=X?.rows.find((z)=>z.routeId===Z);if(!X||!J)throw new R("route-unavailable","Claustrum route is not in the roster");return{next:{...X,declined:I2(X.declined,q1(J),J.accountIdentity),rows:X.rows.map((z)=>z===J?{...z,enabled:!0}:z)},result:void 0}})}function OQ($,Z){if(!q1($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&q1($).length===1)return"bind";return"refuse"}function k2($,Z){return s$($,(X)=>{let J=X?.rows.find((Y)=>Y.routeId===Z.routeId),z=!X||!J?"refuse":OQ(J,Z);if(!X||!J||z==="refuse")return{result:!1};let G=s0(J.quota,Z.observation),Q=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...X,rows:X.rows.map((Y)=>Y===J?{...Y,...Q,quota:G}:Y)},result:!0}})}async function f2($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let X=await t({...PQ,path:$.path,renew:!0});if(!X){let J=await K1($.path);if($.signal?.throwIfAborted(),!J?.view)throw new R("roster-busy","Claustrum account discovery is already in progress");return J}try{let J=await $.custody.discover($.signal);return $.signal?.throwIfAborted(),await s$($.path,async(z)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await X.assertOwned();let G=typeof $.projection==="function"?$.projection():$.projection,Q=y7(z,J,G);return{...JSON.stringify(z)!==JSON.stringify(Q)&&{next:Q},result:Q}})}finally{await X.release()}}class O3{#$;#Z=new AbortController;#Q;#X;#B;#z;#J;#Y;#H=!1;constructor($){this.#$=$,this.#Q=$.logger??s("claustrum")}#G($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}async#W(){return await this.#$.isCustodyActive?.()??!0}#V($,Z){let X=V2([this.#Z.signal,...Z?[Z]:[]]);return new Promise((J,z)=>{let G=()=>{X.signal.removeEventListener("abort",Q),X.dispose()},Q=()=>{G(),z(X.signal.reason)};if(X.signal.addEventListener("abort",Q,{once:!0}),$.then((Y)=>{if(G(),X.signal.aborted)z(X.signal.reason);else J(Y)},(Y)=>{G(),z(Y)}),X.signal.aborted)Q()})}async#j(){if(this.#G(),this.#X)return this.#X;if(!this.#B)this.#B=this.#$.connect().then(($)=>{if(this.#Z.signal.aborted)$.close(),this.#G();return this.#X=new F3({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Q}),this.#X}).finally(()=>{this.#B=void 0});return this.#V(this.#B)}snapshot(){return this.#J}routingRows(){return x2(this.#J)}refresh(){if(this.#G(),this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#W()){this.#J=void 0,this.#X?.close(),this.#X=void 0;return}let $=await this.#j(),Z=await f2({path:this.#$.rosterPath,custody:$,isActive:()=>this.#W(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#G();let X=Z?.view!==this.#J?.view;if(this.#J=Z,Z&&X)this.#$.onRoster?.(Z);return Z})().finally(()=>{this.#z=void 0}),this.#z}start(){if(this.#H)return;this.#G(),this.#H=!0;let $=async()=>{try{await this.refresh()}catch(X){if(!this.#Z.signal.aborted)this.#$.onError?.(X)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#Y=void 0,$()},Z),this.#Y.unref?.()};$()}async authorize($,Z){this.#G(Z);let X=this.#J??await this.#V(this.refresh(),Z);if(!X||!await this.#W())throw new R("not-active","Claustrum scoped custody is not active");let J=await K1(this.#$.rosterPath);this.#G(Z);let z=X.rows.find((B)=>B.routeId===$),G=J?.rows.find((B)=>B.routeId===$);if(G&&!G.enabled)throw new R("route-declined","Claustrum route is disabled");if(!z||!G||G.state!=="active"||G.credentialId!==z.credentialId||G.accountIdentity!==z.accountIdentity)throw new R("route-unavailable","Claustrum route is disabled, removed or changed");let Q=await this.#V(this.#j(),Z),Y=V2([this.#Z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},Y.signal)}finally{Y.dispose()}}async reportFailure($,Z,X){if(this.#G(),!this.#X)throw new R("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.reportFailure($,Z,X)}async send($,Z,X){let J=X.signal,z=await this.authorize($,J),G=await Z(z,J);if(G.status===401&&!J?.aborted){let Q;try{Q=await this.authorize($,J)}catch{}if(A2(X.site,z,Q,this.#Q))await G.body?.cancel().catch(()=>{}),z=Q,G=await Z(Q,J)}if(G.status===401)await this.reportFailure(z,401,X.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){this.#G(),await b2(this.#$.rosterPath,$),this.#J=await K1(this.#$.rosterPath)}async accept($){this.#G(),await E2(this.#$.rosterPath,$),this.#J=await K1(this.#$.rosterPath)}async recordQuota($,Z,X){this.#G();let J=await k2(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:X.credentialId,accountIdentitySource:X.accountIdentitySource,...X.accountIdentity!==void 0&&{accountIdentity:X.accountIdentity},...X.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:X.expectedAccountIdentity}});if(J)this.#J=await K1(this.#$.rosterPath);return J}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new R("closed","Claustrum consumer is closed")),this.#Y)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Y);this.#Y=void 0,this.#X?.close(),this.#J=void 0}}function v7($){return y1.connect($)}var _Q=M3("openai");function g7($){return L3($)}function u0($){if(!$||$.corrupt===!0)return!1;return g7($.refresh)}class i$ extends Error{code="tombstone-refresh";constructor(){super("This OpenAI account was moved into the Claustrum vault by an older version of OpenAI auth and holds no local credential. Connect the vault, or sign in to the account again.");this.name="TombstoneRefreshError"}}function _3($){if(g7($))throw new i$}function l0($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var CQ=s("quota");var TQ="app_EMoamEEZ73f0CkXaXp7hrann",AQ="https://auth.openai.com";async function h7($){_3($.refreshToken);let Z=await $.fetchImpl(`${AQ}/oauth/token`,{method:"POST",signal:AbortSignal.timeout(15000),headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refreshToken,client_id:TQ}).toString()});if(!Z.ok){let z=g8(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:z,isRefreshError:!0})}let X=await Z.json();if(!X||typeof X.access_token!=="string"||!X.access_token||typeof X.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});if(X.refresh_token!==void 0&&typeof X.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});let J=typeof X.refresh_token==="string"&&X.refresh_token?X.refresh_token:$.refreshToken;return{access:X.access_token,refresh:J,expires:$.now()+X.expires_in*1000,expiresIn:X.expires_in}}var RQ="https://chatgpt.com/backend-api/wham/usage";async function H$($){let Z=$.logger??CQ,X=$.accountKey??"unknown",J=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let z=await $.fetchImpl(RQ,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!z.ok){let Q=g8(z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${z.status}`),{status:z.status,retryAfter:Q})}let G=NZ(await z.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:X,status:z.status,elapsedMs:Date.now()-J}),G}catch(z){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:X,status:typeof z?.status==="number"?z.status:"error",elapsedMs:Date.now()-J,error:l0(z)}),z}}import{createHash as xQ}from"node:crypto";var bQ=globalThis.setTimeout,EQ=5;function a$($){let Z=$?.quota?.checkIntervalMinutes??EQ;return Math.max(1,Z)*60000}function kQ($){return $?.quota?.enabled!==!1}function v2($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function fQ($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function w7($,Z,X){if(!kQ(Z))return X+a$(Z);let J=fQ(Z),z=[];for(let G of["primary","secondary"]){let Q=$?.[G];if(!Q)continue;if(Q.remainingPercent>=J[G])continue;let Y=Q.resetsAt?Date.parse(Q.resetsAt):Number.NaN;if(!Number.isFinite(Y)||Y<=X)return X+a$(Z);z.push(Y)}if(!z.length)return X+a$(Z);return Math.min(...z)+60000}function yQ($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function vQ($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function O0($){return xQ("sha256").update($).digest("hex").slice(0,16)}class D1{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;configPath;constructor($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath,this.now=$.now??Date.now,this.fetchQuotaFn=$.fetchQuotaFn,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.seedMainFromStorage($.storage),this.seedMainBackoffFromStorage($.storage)}getMain($){if($&&this.main&&this.mainTokenFp&&this.mainTokenFp!==O0($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let X=this.fallbacks.get($)??null;if(!Z||!X)return X;if(this.fallbackTokenFps.get($)!==O0(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return X}getAllFallbacks(){return this.fallbacks}setMain($,Z,X,J=!1){if(!J&&!m7(Z.quota))return;if(this.mainTokenFp=O0($),X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)this.clearRateLimited("main");if(X)this.mainQuotaAccountId=X;if(this.main=Z,y2(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let X=this.fallbacks.get($)??null;if(Z&&X?.accountId&&X.accountId!==Z)return null;return X}setFallback($,Z,X,J=!1,z){if(!J&&!m7(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(z&&G&&z!==G)this.clearRateLimited($);let Q=z??G;if(this.fallbacks.set($,{...Z,accountId:Q}),X)this.fallbackTokenFps.set($,O0(X));else this.fallbackTokenFps.delete($);if(y2(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let X=this.rateLimitedUntilMap.get($);if(X!==void 0&&X>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=O0($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let X=D1.fallbackInflightKey($,Z),J=this.inflightFallbacks.get(X);if(J)return J;if(this.isFallbackBackedOff($,Z)){let G=this.getFallback($,Z);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let z=this._fetchFallback($,Z);return this.inflightFallbacks.set(X,z),z}async refreshAllFallbacks($){let Z=this.now();for(let X of $){if(X.enabled===!1)continue;if(u0(X)||!X.access)continue;let J=this.getFallback(X.id,X.access);if(J&&Z<J.refreshAfter)continue;try{await this.refreshFallback(X.id,X.access)}catch{}}}refreshMainInBackground($){let Z=O0($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale($,Z){let X=this.getFallback($,Z);if(!X)return!0;return this.now()>=X.refreshAfter}shouldRefreshOnRequestCount($){let Z=vQ(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($){return this.isMainStale()||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let X=yQ($);if(!X)return;let J=Z?O0(Z):null;if(J&&X.tokenFingerprint&&X.tokenFingerprint!==J)return;let z={quota:X.quota,refreshAfter:w7(X.quota,$,X.checkedAt),checkedAt:X.checkedAt};if(this.main&&this.main.checkedAt>=z.checkedAt&&(!J||!this.mainTokenFp||this.mainTokenFp===J))return;if(this.main=z,this.mainTokenFp=X.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&$$(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=a$(this.storage);for(let X of $){if(X.enabled===!1)continue;if(!X.quota)continue;let J=Math.max(X.quota.primary?.checkedAt??0,X.quota.secondary?.checkedAt??0);if(J<=0)continue;let z=this.getFallback(X.id,X.access);if(z&&z.checkedAt>=J)continue;this.setFallback(X.id,{quota:X.quota,refreshAfter:J+Z,checkedAt:J},X.access,!1,X.accountId)}}isBackedOff(){return $$(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==O0(Z))return!1}return $$(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,O0(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let J=this.now()-this.lastApiCallAt;if(J<D1.API_CALL_GAP_MS)await new Promise((z)=>{let G=bQ(z,D1.API_CALL_GAP_MS-J);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},X=this.apiGate.then(Z,Z);return this.apiGate=X.catch(()=>{}),X}async _fetchMain($){let Z=O0($);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let X=await t({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!X){let J=this.main;if(J&&this.now()<J.refreshAfter)return J.quota;throw Error("Quota refresh is already in progress")}try{let J=this.now(),z=await this._fetchQuota($),G=this.now();if(this.mainTokenFp=O0($),this.main={quota:z,refreshAfter:w7(z,this.storage,G),checkedAt:G},y2(z))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(z,G,this.mainTokenFp,J),z}catch(J){throw this._handleMainFetchError(J),J}finally{await X.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback($,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff($,Z)){let J=this.getFallback($,Z);if(J)return J.quota;throw Error("Quota API rate-limited — try again later")}let X=await t({name:D1.quotaLockName($),ttlMs:30000,path:this.configPath});if(!X){let J=this.getFallback($,Z);if(J&&this.now()<J.refreshAfter)return J.quota;throw Error("Quota refresh is already in progress")}try{let J=await this._fetchQuota(Z),z=this.now();return this.setFallback($,{quota:J,refreshAfter:z+a$(this.storage),checkedAt:z},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),J}finally{await X.release()}}catch(X){throw this._handleFallbackFetchError($,Z,X),X}finally{this.inflightFallbacks.delete(D1.fallbackInflightKey($,Z))}})}async _fetchQuota($){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:$,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError($){return $?.status===401}_handleMainFetchError($){if(D1.isAuthError($))return;this.mainLastApiError=f$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(D1.isAuthError(X))return;let J=O0(Z),z=this.fallbackErrorTokenFps.get($)===J?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,f$({error:X,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set($,J)}}function m7($){return Boolean($.primary||$.secondary)}function y2($){let{primary:Z,secondary:X}=$;if(!Z&&!X)return!1;if(Z&&Z.usedPercent>=100)return!1;if(X&&X.usedPercent>=100)return!1;return!0}import{readFile as tQ}from"node:fs/promises";var h1=s("refresh"),w2=s("accounts"),mQ=1e4,pQ=15000,g2=50;function N1($){return $.type==="oauth"&&$.corrupt!==!0}function uQ($){let Z=$?.trim();if(!Z)return!1;try{let X=new URL(Z);return(X.protocol==="http:"||X.protocol==="https:")&&!X.username&&!X.password}catch{return!1}}var j$="floors-v1";class T3 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var lQ=[401,403,429],p7={primary:0,secondary:0},dQ=!1,M1={primary:5,secondary:10};function b($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var cQ=new Set(["__proto__","constructor","prototype"]);function l2($){return $.length>0&&!cQ.has($)}function sQ($){return $ instanceof T3||b($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function C3($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():hQ(),label:typeof $.label==="string"?$.label:void 0,enabled:typeof $.enabled==="boolean"?$.enabled:void 0,addedAt:typeof $.addedAt==="number"?$.addedAt:void 0,lastUsed:typeof $.lastUsed==="number"?$.lastUsed:void 0,accountId:typeof $.accountId==="string"?$.accountId:void 0}}function u7($){if(!b($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let X=Number($.nextRetryAt),J=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(X)?X:void 0,retryCount:Number.isFinite(J)?J:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function iQ($){if(!b($))return;let Z={};for(let z of["primary","secondary"]){let G=$[z];if(!b(G))continue;let Q=Number(G.usedPercent),Y=Number(G.remainingPercent),B=Number(G.checkedAt);if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(B))continue;let H=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[z]={usedPercent:Q,remainingPercent:Y,checkedAt:B,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(H)&&H>0?{windowMinutes:H}:{}}}for(let z of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[z]==="number"?$[z]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[z]=G}let X=$.spendControl;if(b(X)){let z=Number(X.limit),G=Number(X.used),Q=Number(X.remaining),Y=Number(X.usedPercent),B=Number(X.remainingPercent);if(Number.isFinite(z)&&Number.isFinite(G)&&Number.isFinite(Q)&&Number.isFinite(Y)&&Number.isFinite(B)&&typeof X.reached==="boolean")Z.spendControl={limit:z,used:G,remaining:Q,usedPercent:Y,remainingPercent:B,resetsAt:typeof X.resetsAt==="string"?X.resetsAt:void 0,unit:typeof X.unit==="string"?X.unit:void 0,source:typeof X.source==="string"?X.source:void 0,reached:X.reached}}let J=$.credits;if(b(J)&&typeof J.hasCredits==="boolean"&&typeof J.unlimited==="boolean"&&typeof J.overageLimitReached==="boolean"){let z=Number(J.balance);Z.credits={hasCredits:J.hasCredits,unlimited:J.unlimited,overageLimitReached:J.overageLimitReached,...Number.isFinite(z)?{balance:z}:{}}}return Object.keys(Z).length?Z:void 0}function aQ($){if(!b($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!uQ(Z))return null;let J=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...C3($),type:"api",apiKey:X||void 0,baseURL:Z,authHeader:J}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...C3($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...C3($),type:"oauth",corrupt:!0}}return{...C3($),type:"oauth",access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:u7($.lastRefreshError),lastQuotaRefreshError:u7($.lastQuotaRefreshError),quota:iQ($.quota)}}function nQ($){if(!b($))return;let Z=Object.create(null);for(let[X,J]of Object.entries($)){if(!l2(X)||!b(J))continue;let z={};if(b(J.inFlight))z.inFlight={...J.inFlight};if(b(J.lastOutcome)&&typeof J.lastOutcome.code==="string"&&J.lastOutcome.code.length>0&&typeof J.lastOutcome.at==="number"&&Number.isFinite(J.lastOutcome.at))z.lastOutcome={code:J.lastOutcome.code,at:J.lastOutcome.at,...b(J.lastOutcome.previousOutcome)&&typeof J.lastOutcome.previousOutcome.code==="string"&&J.lastOutcome.previousOutcome.code.length>0&&typeof J.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(J.lastOutcome.previousOutcome.at)?{previousOutcome:{code:J.lastOutcome.previousOutcome.code,at:J.lastOutcome.previousOutcome.at}}:{}};if(typeof J.cooldownUntil==="number"&&Number.isFinite(J.cooldownUntil))z.cooldownUntil=J.cooldownUntil;if(Object.keys(z).length>0)Z[X]=z}return Object.keys(Z).length>0?Z:void 0}var l7=new Set;function rQ($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(l7.has(Z))return;l7.add(Z),w2.warn("account load-dropped, preserved on disk",{droppedIds:$})}function oQ($){if(!b($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(aQ).filter((J)=>J!=null);if(X.length<Z.length){let J=new Set;for(let Q of Z)if(b(Q)&&typeof Q.id==="string"&&Q.id.trim())J.add(Q.id.trim());let z=new Set(X.map((Q)=>Q.id)),G=[];for(let Q of J)if(!z.has(Q))G.push(Q);rQ(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:b($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:b($.refresh)?$.refresh:void 0,quota:b($.quota)?$.quota:void 0,reset:nQ($.reset),dump:b($.dump)?$.dump:void 0,costZeroing:b($.costZeroing)?$.costZeroing:void 0,killswitch:b($.killswitch)?$.killswitch:void 0,logging:b($.logging)?$.logging:void 0,cachekeep:b($.cachekeep)?$.cachekeep:void 0,cacheKeep:b($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:X}}async function A3($){try{return{exists:!0,value:JSON.parse(await tQ($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function R3($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function eQ($){let Z;try{Z=(await A3($)).value}catch{return null}return WY(Z)}function $Y($,Z){if(!b($))return $;let X=b(Z)?Z:{},J=b(X.main)?X.main:void 0,z=b(X.accounts)?X.accounts:{},G=b($.quota)?$.quota:{},Q=b($.refresh)?$.refresh:{},Y=J??G,B=J??Q,W=Q.mainRefreshLeaseId!==void 0?{id:Q.mainRefreshLeaseId,until:Q.mainRefreshLeaseUntil,tokenHash:Q.mainRefreshLeaseTokenHash}:{id:B.refreshLeaseId,until:B.refreshLeaseUntil,tokenHash:B.refreshLeaseTokenHash},j=Array.isArray($.accounts)?$.accounts.map((q)=>{if(!b(q))return q;let U=typeof q.id==="string"&&b(z[q.id])?z[q.id]:{};return{...q,...U}}):void 0;return ZY({...$,refresh:R3({...Q,mainLastRefreshError:Q.mainLastRefreshError??B.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:R3({...G,mainQuota:Y.quota,mainQuotaCheckedAt:Y.quotaCheckedAt,mainQuotaToken:Y.quotaToken,mainLastQuotaApiError:Y.lastQuotaApiError}),accounts:j})}async function d2($){let Z=await A3($.configPath);if(!Z.exists)return null;let X=await A3($.statePath);return oQ($Y(Z.value,X.value))}function ZY($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function XY($){if($.type==="api")return R3({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return R3({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function S3($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function n$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function JY($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function zY($,Z){if(!JY($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var GY=300000;function d7($,Z){if($===void 0)return 0;return $>Z+GY?0:$}function QY($,Z,X){let J=Date.now(),z=d7(Z.lastRefreshedAt,J),G=d7(X.lastRefreshedAt,J),Q=Z.expires??0,Y=X.expires??0,B=G>z?X:z>G?Z:Y>Q?X:Q>Y?Z:zY(Z,X);n$($,B,"access"),n$($,B,"refresh"),n$($,B,"expires"),n$($,B,"lastRefreshedAt"),n$($,B,"lastRefreshError")}function YY($,Z){if(!b($))return Z;let X=$,J=S3(X.quota),z=S3(Z.quota),G=J>z,Q=G?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete Q.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete Q.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))Q.lastUsed=X.lastUsed;return QY(Q,X,Z),Q}async function BY($,Z=!1){let X=Date.now(),J=X+pQ,z=0;while(Date.now()<=J){z++;let Y=await t({name:"save",ttlMs:mQ,path:$,renew:Z});if(Y)return Y;let B=J-Date.now();if(B<=0)break;await wQ(Math.min(g2+o7(g2),B))}let G=Date.now()-X,Q=Math.round(G/Math.max(1,z));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${z} attempts, ~${Q}ms apart; retry interval is ${g2}ms). A gap near the retry interval means lock contention; a much larger one means this process's event loop was saturated and the wait expired without getting scheduled.`)}function WY($){if(!b($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let X of $.accounts){if(!b(X))continue;if(typeof X.id!=="string")continue;let J=X.id.trim();if(!J)continue;Z.add(J)}return Z}function HY($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:S3($.main.quota),J=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:S3(Z.quota?.mainQuota);if(X>J)return;$.main.quota=Z.quota?.mainQuota,$.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,$.main.quotaToken=Z.quota?.mainQuotaToken,$.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function VY($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function m2($){if(Array.isArray($))return $.map(m2);if(!b($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,m2(X)]))}async function jY($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},J){let z=Z.statePath,G=await BY(z);try{let Q=(await A3(z)).value,Y=b(Q)?{...Q,version:1}:{version:1};if(X.mainQuota)HY(Y,$);if(X.mainRefresh)VY(Y,$);if(X.accounts){let B=X.accounts===!0?null:new Set(X.accounts),H=await eQ(Z.configPath);Y.accounts={...b(Y.accounts)?Y.accounts:{}};for(let W of $.accounts){if(B&&!B.has(W.id))continue;if(H&&!H.has(W.id))continue;Y.accounts[W.id]=YY(Y.accounts[W.id],XY(W))}if(B){for(let W of B)if(!$.accounts.some((V)=>V.id===W))delete Y.accounts[W]}if(H){for(let W of Object.keys(Y.accounts))if(!H.has(W))delete Y.accounts[W]}}if(J&&!J())return;await P0(z,m2(Y))}finally{await G.release()}}function n7($){return $?.fallbackOn?.length?$.fallbackOn:lQ}function UY($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??p7.primary,secondary:Z.secondary??Z["1w"]??p7.secondary}}function p2($){return $?.quota?.enabled!==!1}function o$($){return $?.quota?.failClosedOnUnknownQuota??dQ}function I3($,Z,X=Date.now()){if(!p2(Z))return!0;if(!$)return!o$(Z);let J=UY(Z),z=o$(Z);for(let G of["primary","secondary"]){let Q=$[G];if(!Q)continue;if(v2(Q,X)){if(z)return!1;continue}if(Q.remainingPercent<J[G])return!1}return!0}function c2($){return $?.killswitch?.enabled===!0}function c7($){return{primary:$?.primary??$?.["5h"]??M1.primary,secondary:$?.secondary??$?.["1w"]??M1.secondary}}function s7($){return typeof $==="number"&&Number.isFinite($)?$:0}function L1($,Z){if(!$?.killswitch)return M1;if($.killswitch.schema===j$){let{accounts:X,defaults:J}=$.killswitch,z=Z??"main",G=b(X)&&Object.hasOwn(X,z)&&b(X[z])?X[z]:b(J)?J:void 0;return{primary:s7(G?.primary),secondary:s7(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return c7($.killswitch.accounts[Z]);return c7($.killswitch.main)}function r7($,Z,X,J=Date.now()){if(!c2(Z))return!0;if(!$)return!o$(Z);let z=L1(Z,X),G=o$(Z);for(let Q of["primary","secondary"]){let Y=$[Q];if(!Y)continue;if(v2(Y,J)){if(G)return!1;continue}if(Y.remainingPercent<z[Q])return!1}return!0}function qY($){return $?.refresh?.enabled!==!1}function s2($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function o7($){return Math.floor(Math.random()*($+1))}function w1($,Z,X){return!$.access||!$.expires||$.expires-X<=s2(Z)}function KY($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function V$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class t7 extends Error{constructor($){super(`Refusing to refresh account ${$}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}function N0($,Z){let X=$.accounts.findIndex((J)=>J.id===Z.id);if(X!==-1)$.accounts[X]=Z}function r$($){return $ instanceof Error?$.message:String($)}function u2($,Z,X){if(Z instanceof i$)return;$.lastRefreshError=u6({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function h2($,Z,X){if(Z instanceof i$)return;if($.lastQuotaRefreshError=f$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)u2($,Z,X)}function i7($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function DY($,Z){if(!$)return!1;return i7($.primary,Z)||i7($.secondary,Z)}function NY($,Z,X){if(!$)return!1;let J=Z?.quota?.checkIntervalMinutes??5,z=Math.max(1,J)*60000,G=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return X-G<z}function a7($,Z,X){return!NY($.quota,Z,X)}function MY($,Z,X,J){return v8(X)&&I3($.quota,Z,J)&&DY($.quota,J)}function LY($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var FY=60000,PY=60000,OY=600000;function _Y($){return`fallback-oauth-refresh-${gQ("sha256").update($).digest("base64url").slice(0,16)}`}var CY=1e4,TY=100,SK=globalThis.setTimeout.bind(globalThis),IK=globalThis.clearTimeout.bind(globalThis);class AY{now;fetchImpl;paths;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor($){this.options=$,this.now=$.now??Date.now,this.fetchImpl=$.fetchImpl??fetch,this.paths=$.paths,this.quotaManager=$.quotaManager??null,this.onFallbackStorageChanged=$.onFallbackStorageChanged}assertNotTombstoned($){if($)_3($.refresh)}seedFallbackQuota($,Z){if(!this.quotaManager)return;if(!$.quota)return;let X=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(X<=0)return;let J=this.quotaManager.getFallback($.id,$.access);if(J&&J.checkedAt>=X)return;this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:X+LY(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return d2(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await jY($,this.paths,{accounts:Z??!0},this.options.canWrite)}startBackgroundRefresh(){let $=async()=>{if(await this.options.backgroundRefreshPaused?.())return;if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if($().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{$().catch(()=>{})},FY+o7(PY)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts($){let Z=$!==void 0?$:await this.load();if(!Z)return[];let X=[],J=!1;for(let z of Z.accounts){if(z.enabled===!1||!N1(z))continue;if(V$(Z,z))continue;if(u0(z))continue;let G=!1,Q=z;try{if(w1(Q,Z,this.now())){let Y=Q.lastRefreshError;if(Y&&W1(Y,Q.refresh,this.now()))throw G=!0,Error(k$(Y,this.now()));try{Q=await this.refreshAccount(Q,Z),J=!0}catch(B){if(sQ(B))continue;G=!0;let H=Z.accounts.find((W)=>W.id===z.id&&N1(W));if(H&&!W1(H.lastRefreshError,H.refresh,this.now()))u2(H,B,this.now()),N0(Z,H),J=!0;throw B}}if(this.seedFallbackQuota(Q,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(Q),Z))X.push(Q)}catch(Y){let B=KY(Q,this.now());if(G){if(!B)continue}else if(!B)continue;if(MY(Q,Z,Y,this.now()))h1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:Q.id,error:r$(Y)}),X.push(Q);else if(!o$(Z))X.push(Q)}}if(J){let z=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(z)).catch((G)=>{w2.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:r$(G)})})}return X}async markUsed($){try{let Z=await this.load();if(!Z)return;let X=Z.accounts.find((J)=>J.id===$.id);if(!X)return;X.lastUsed=this.now(),await this.save(Z,[X.id])}catch(Z){w2.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:r$(Z)})}}accountPassesQuotaPolicy($,Z){return I3($.quota,Z,this.now())}quotaPolicyAccount($){if(!this.quotaManager)return $;let Z=this.quotaManager.getFallback($.id,$.access)?.quota;return Z?{...$,quota:Z}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!qY($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!N1(X))continue;if(V$($,X))continue;if(u0(X))continue;if(!w1(X,$,this.now()))continue;if(W1(X.lastRefreshError,X.refresh,this.now()))continue;try{h1.debug("fallback oauth background due",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),await this.refreshAccount(X,$),Z=!0}catch(J){h1.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:r$(J)}),u2(X,J,this.now()),N0($,X),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!p2($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!N1(X))continue;if(V$($,X))continue;if(u0(X))continue;let J=X;try{if(w1(J,$,this.now())){if(W1(J.lastRefreshError,J.refresh,this.now()))continue;J=await this.refreshAccount(J,$),Z=!0}if($$(J.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(J,$),!(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access):a7(J,$,this.now())))continue;await this.refreshAccountQuota(J,$),Z=!0}catch(z){h2(X,z,this.now()),N0($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!p2(Z))return{storage:Z,errors:X};if(!this.options.fetchQuotaFn)return{storage:Z,errors:X};let J=$.force??!1,z=!1;for(let G of Z.accounts){if(G.enabled===!1||!N1(G))continue;if(V$(Z,G))continue;if(u0(G))continue;let Q=G;try{if(w1(Q,Z,this.now())){let Y=Q.lastRefreshError;if(Y&&W1(Y,Q.refresh,this.now()))throw Error(k$(Y,this.now()));Q=await this.refreshAccount(Q,Z),z=!0}if(!J&&!a7(Q,Z,this.now())){if(Q.lastQuotaRefreshError)Q.lastQuotaRefreshError=void 0,N0(Z,Q),z=!0;continue}await this.refreshAccountQuota(Q,Z),z=!0}catch(Y){h2(G,Y,this.now()),N0(Z,G),z=!0,X.push({accountId:G.id,message:r$(Y)})}}if(z)await this.save(Z);return{storage:Z,errors:X}}async refreshAccount($,Z,X={}){let J=this.refreshPromises.get($.id);if(J){let Q=await J;return N0(Z,Q),Q}let z=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,z);let G=await z;return N0(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,X,J){let z=Date.now()+CY;while(Date.now()<z){await new Promise((H)=>setTimeout(H,TY));let G=await this.load(),Q=G?.accounts.find((H)=>H.id===$.id&&N1(H));if(!Q)continue;if(this.assertNotTombstoned(Q),(Q.access!==X.access||Q.refresh!==X.refresh||(Q.expires??0)>(X.expires??0)+60000)&&(J.force||!w1(Q,G,this.now())))return N0(Z,Q),h1.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:Q.id,expiresInMs:Q.expires?Q.expires-this.now():void 0}),Q;let B=Q.lastRefreshError;if(B&&W1(B,Q.refresh,this.now()))throw N0(Z,Q),Error(k$(B,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(V$($,Z))throw new t7(Z.id)}async refreshAccountNow($,Z,X){let J=await this.load(),z=J?.accounts.find((Y)=>Y.id===$.id&&N1(Y));if(this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!w1(z,J,this.now()))return N0(Z,z),z;let G=z??$,Q=await t({name:_Y(G.id),ttlMs:OY,path:this.paths.configPath,now:this.now,renew:!0});if(!Q){h1.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let Y=await this.waitForConcurrentFallbackRefresh($,Z,G,X);if(Y)return Y;throw Error("Fallback OAuth refresh is already in progress")}try{if(J=await this.load(),z=J?.accounts.find((W)=>W.id===$.id&&N1(W)),this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!w1(z,J,this.now()))return N0(Z,z),z;if(!z)throw new T3($.id);G=z;let Y=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});h1.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:X.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let B=await Y({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=B.access,G.refresh=B.refresh,G.expires=B.expires,G.lastRefreshedAt=B.expires-B.expiresIn*1000,G.lastRefreshError=void 0,N0(Z,G),await this.save(Z),!(await this.load())?.accounts.some((W)=>W.id===$.id))throw new T3($.id);return h1.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await Q.release()}}async refreshAccountQuota($,Z){let X=$;if(this.assertNotTombstoned(X),!X.access)throw Error(`Fallback account ${$.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let J=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),z=(G)=>this.quotaManager?this.quotaManager.refreshFallback(X.id,G):J({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!X.access)throw Error(`Fallback account ${$.id} has no access token`);let G=await z(X.access);X.quota=G,X.lastQuotaRefreshError=void 0,N0(Z,X),await this.save(Z)}catch(G){throw h2($,G,this.now()),N0(Z,$),G}}}var e7="/backend-api/wham/rate-limit-reset-credits",EK=`https://chatgpt.com${e7}`,RY=`${e7}/consume`,kK=`https://chatgpt.com${RY}`;function k0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as xY}from"node:fs";import{rm as Z5}from"node:fs/promises";import{dirname as bY,join as X5}from"node:path";var $5=["primary","secondary"];function i2($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function t$($){return typeof $==="number"&&Number.isFinite($)}function SY($,Z){if(!i2(Z))return;let X=Z.usedPercent;if(!t$(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...t$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function IY($){let Z=$.spendControl;if(i2(Z)&&typeof Z.reached==="boolean"){let X=(J)=>t$(Z[J])?{[J]:Z[J]}:{};return{kind:"reading",reached:Z.reached,...X("remainingPercent"),...X("usedPercent"),...X("limit"),...X("used"),...X("remaining"),...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...typeof Z.unit==="string"?{unit:Z.unit}:{}}}if($.spendControlCleared===!0)return{kind:"cleared"};return}function $1($,Z,X){if(!i2($)||!t$(Z))return;let J=[],z=[];for(let Q of $5){let Y=SY(Q,$[Q]);if(Y)J.push(Y);else if(X)z.push({label:Q})}let G=IY($);if(J.length===0&&z.length===0&&!G)return;return{checkedAt:Z,...J.length>0?{readings:J}:{},...z.length>0?{coverage:z}:{},...G?{budget:G}:{}}}function e$($){if(!o($))return;let Z=c($),X={};for(let J of $5){let z=Z.limits.find((Q)=>Q.label===J&&Q.kind==="reading");if(!z||!t$(z.usedPercent))continue;let G={usedPercent:z.usedPercent,remainingPercent:100-z.usedPercent,checkedAt:z.checkedAt,...z.resetsAt!==void 0?{resetsAt:z.resetsAt}:{},...z.windowMinutes!==void 0?{windowMinutes:z.windowMinutes}:{}};X[J]=G}return X.primary||X.secondary?X:void 0}var Z1=s("vault"),EY="openai-auth",J5={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},kY={opencode:"OpenCode",pi:"Pi"};function fY($){return D2(EY,$)}function x3($){return X5(bY($),"openai-auth-vault")}function yY($,Z){return{...M2({stateDir:$,host:Z}),rosterPath:X5($,`${Z}-roster.json`)}}var b3=2000,z5={"vault-unreachable":"Request refused locally: this host is connected to the credential vault, which could not be reached, and local accounts are not used while it is connected. Start the vault and connect accounts in it, or disconnect this host from the vault.","vault-empty":"Request refused locally: this host is connected to the credential vault, which serves it no usable OpenAI account, and local accounts are not used while it is connected. Connect accounts in the vault, or disconnect this host from the vault.","vault-refused":"Request refused locally: the credential vault did not authorize an account, and local accounts are not used while this host is connected to it. Check the accounts in the vault, or disconnect this host from the vault."};function G5($){return $.snapshot()===void 0?"vault-unreachable":"vault-empty"}function vY($){let Z=Z$($);return Z?X$(Z):void 0}class a2{host;name;paths;#$;#Z;#Q=new Map;#X;#B;#z;#J=!1;#Y=!1;#H=Promise.withResolvers();#G;#W="unknown";#V;constructor($){this.#$=$,this.host=$.host,this.name=fY($.host),this.paths=yY($.stateDir,$.host),this.#Z=new O3({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:J5,connect:()=>this.#N(),isCustodyActive:()=>this.enrolled(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:vY,...$.now?{now:$.now}:{},onRoster:()=>{this.#X=void 0},onError:(Z)=>this.#U("vault roster refresh failed",Z),logger:Z1})}#j(){return(this.#$.connectionFile??u$)()}#K(){return{connectionFile:this.#j(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>Z1.debug("vault transport error",{errorClass:$})}}#N(){return this.#$.connectScoped?.()??v7(this.#K())}#M(){return this.#$.connectEnrollment?.()??N2(this.#K())}#U($,Z){this.#X=l0(Z),Z1.warn($,{host:this.host,error:this.#X})}#q(){return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=xY($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#q(),Z=await F2(this.paths,this.name);if($===this.#q())return this.#W=Z,this.#V=$,Z;return"unreadable"}enrolled(){return this.#V!==this.#q()||this.#W!=="local"}start(){if(this.#J||this.#Y)return;this.#J=!0;let $=async()=>{try{await this.authority(),await this.#D()}catch(X){if(!this.#Y)this.#U("vault roster refresh failed",X)}if(this.#Y)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#G=setTimeout(()=>{this.#G=void 0,$()},Z),this.#G.unref?.()};$()}#D(){return this.#z??=this.#Z.refresh().finally(()=>{this.#z=void 0,this.#H.resolve()}),this.#z}firstRoster(){return this.#H.promise}async refresh(){try{await this.authority();let $=this.#z;if($)await $.catch(()=>{return});let Z=await this.#D();return this.#X=void 0,Z}catch($){return this.#U("vault roster refresh failed",$),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap(($)=>$.accountIdentity!==void 0?[$.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let $=new Map((this.snapshot()?.rows??[]).map((Z)=>[Z.routeId,Z]));return this.#Z.routingRows().map((Z)=>{let X=$.get(Z.id)?.accountIdentity;return{id:Z.id,kind:Z.kind==="api-key"?"api-key":"oauth",...X!==void 0?{identity:X}:{},...Z.quota!==void 0?{quota:Z.quota}:{}}})}owns($){return(this.snapshot()?.rows??[]).some((Z)=>Z.routeId===$)}async send($,Z,X){let J=!1;try{return await this.#Z.send($,(z)=>{return J=!0,Z(z.accessToken,z)},{site:X.site,...X.signal?{signal:X.signal}:{}})}catch(z){if(J)throw z;this.#U("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#Z.authorize($,Z.signal)}catch(X){this.#U("vault refused to serve an account",X);return}}async reportFailure($,Z){if(Z!==401)return;try{await this.#Z.reportFailure($,401,"direct")}catch(X){this.#U("vault failure report failed",X)}await this.refresh()}recordSnapshot($,Z,X,J){let z=$1(Z,(this.#$.now??Date.now)(),X);if(!z)return Promise.resolve();return this.#Z.recordQuota($,z,J).then(()=>{},(G)=>this.#U("vault quota write failed",G))}async pollQuota($){let Z,X=this.#$.fetchImpl?.()??globalThis.fetch,J=await this.send($,async(z,G)=>{try{let Q=await H$({accessToken:z,fetchImpl:X,now:this.#$.now??Date.now,...G.accountIdentity?{accountId:G.accountIdentity}:{},accountKey:$,logger:Z1});return await this.recordSnapshot($,Q,!0,G),Z=void 0,new Response(null,{status:200})}catch(Q){Z=l0(Q);let Y=Q?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw Q}},{site:"quota"}).catch((z)=>{Z=l0(z);return});if(!J)return{ok:!1,error:Z??"vault refused"};return J.ok?{ok:!0}:{ok:!1,error:Z??`status ${J.status}`}}requestReading($){if(this.#Q.has($))return;let Z=this.pollQuota($).catch((X)=>{Z1.warn("vault quota poll failed",{routeId:$,error:l0(X)})}).finally(()=>{this.#Q.delete($)});this.#Q.set($,Z)}async pollStale($){let Z=(this.#$.now??Date.now)(),X=[];for(let J of this.routes()){let z=gY(J.quota);if(z!==void 0&&Z-z<$)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}async decline($){await this.#Z.decline($),Z1.info("vault account declined",{routeId:$})}async accept($){await this.#Z.accept($),Z1.info("vault account accepted",{routeId:$})}async status(){await this.authority();let $;try{$=await d$(this.paths,this.name)}catch(Z){this.#U("vault enrollment state unreadable",Z),$={state:"blocked",proposedName:this.name,code:Z instanceof R?Z.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:$,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#X?{lastError:this.#X}:{}}}async connectStep(){let $=await this.#M().catch((Z)=>{throw new j0("vault-unreachable",`Could not reach the Claustrum vault (${this.#j()}): ${l0(Z)}. Is the vault running?`)});try{let Z=new N3({client:$,paths:this.paths,proposedName:this.name,...this.#$.now?{now:this.#$.now}:{}}),X=await Z.status();if(X.state==="denied"||X.state==="blocked")await Z.resetTerminal();let J=await Z.reconcile();if(Z1.info("vault enrollment step",{host:this.host,state:J.state}),J.state==="approved")this.#X=void 0,await this.refresh();return J}finally{$.close()}}waitForApproval($={}){return this.#B??=(async()=>{let Z=$.sleep??((G)=>new Promise((Q)=>setTimeout(Q,G))),X=$.pollIntervalMs??2000,J=Date.now()+($.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if($.onPending?.(z),Date.now()>=J)return z;await Z(X),z=await this.connectStep()}return z})().finally(()=>{this.#B=void 0}),this.#B}async disconnect(){await Z5(this.paths.tokenPath,{force:!0}),await Z5(this.paths.statePath,{force:!0}),await this.authority(),this.#X=void 0,Z1.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())_2({mode:"custody",auth:$,provider:"openai"})}close(){if(this.#Y=!0,this.#H.resolve(),this.#G)clearTimeout(this.#G);this.#G=void 0,this.#Z.close()}}function gY($){if(!$)return;let Z=c($).limits.map((X)=>X.checkedAt);return Z.length>0?Math.max(...Z):void 0}function E3($,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}`,"and let it read your OpenAI accounts with:",` ck auth grant --principal enrolled:${$} --selector-kind category --selector ${J5.category} --operation read`]}function Q5($,Z,X){let J=`${kY[$]} (${Z})`;switch(X.state){case"approved":return`${J}: connected to the Claustrum vault.`;case"idle":return`${J}: not connected to the Claustrum vault.`;case"pending":return X.requestId?`${J}: waiting for approval of request ${X.requestId}.`:`${J}: enrollment request not taken yet${X.retryCode?` (${X.retryCode})`:""}.`;case"denied":return`${J}: the vault denied the enrollment request.`;case"blocked":return`${J}: enrollment stopped (${X.code}).`;case"unavailable":return`${J}: the vault is unavailable (${X.code}).`;case"busy":return`${J}: another process is enrolling right now.`}}function n2($,Z){switch(Z.state){case"approved":{let X=$.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${$.name}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?" (grant it the openai-native category with `ck auth grant` to add some)":""}.`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${Z.code}). Run Connect again to send a new request.`};case"pending":case"busy":return{ok:!1,text:[...E3($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
100
+ `)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var Y5=`${String.fromCharCode(27)}\\[[0-9;]*m`,eK=new RegExp(Y5,"g"),$D=new RegExp(`^${Y5}`);function U$($){return $.authority!=="local"}async function X1($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function H5($){let Z;try{return await Promise.race([Promise.resolve().then(()=>$.refresh()).then(()=>{return},(X)=>X instanceof Error?X.message:String(X)),new Promise((X)=>{Z=setTimeout(()=>X("Vault roster refresh did not finish within the roster wait budget."),b3)})])}finally{clearTimeout(Z)}}function F1($){return $.email||$.label||$.routeId}var o2="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 V5($){return k0($)?{...$}:{}}function k3($,Z,X,J){let z=X.confirm?.irreversible?{irreversible:!0,confirm:X.confirm.message}:{...X.confirm?{confirm:X.confirm.message}:{}};return{id:X.id,label:X.label,...X.description?{description:X.description}:{},...X.group?{group:X.group}:{},knobs:X.knobs,...z,run:async({values:G,invocation:Q})=>{let Y=await $.apply({command:$.command,sectionId:Z,...J?{itemId:J}:{},actionId:X.id,values:G,confirmed:!0},Q);return{ok:Y.ok,text:Y.text,...Y.code?{code:Y.code}:{}}}}}function e2($,Z){return new Proxy($,{get(X,J){if(J==="read")return async()=>{let G=await X.read();if(G.status!=="ready")return G;let Q={...G,rows:G.rows.map((H)=>({...H,label:H.label??H.id}))};if(!Z)return Q;let Y=await X1(Z);if(!U$(Y))return Q;let B=[...Y.status.accounts.map((H)=>({id:H.routeId,label:F1(H),type:"oauth",enabled:H.enabled,identity:H.accountIdentity,quota:H.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:B}};if(J==="readSettings")return async()=>{let G=await X.readSettings();if(G.status==="error"||!Z)return G;let Q=await X1(Z),Y=V5(G.settings.killswitch);if(!U$(Q)||!G.settings.killswitch)return G;let B=V5(Y.accounts);for(let H of Q.status.accounts)B[H.routeId]=L1({version:1,accounts:[],...G.settings},H.routeId);return{...G,settings:{...G.settings,killswitch:{...Y,accounts:B}}}};let z=Reflect.get(X,J);return typeof z==="function"?z.bind(X):z}})}function j5($,Z){let X=R1($),J=R1({command:$.command,title:$.title,store:e2($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:$.routing,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),z=async(B,H)=>{let W=await X1(Z),V=U$(W),j=V?J:X,U=(await j.open(H)).menu.sections.find((M)=>M.id===B);if(!U)throw new j0("unavailable","The account menu is unavailable.");if(!V)return{lines:U.lines,items:U.items.map((M)=>({...M,actions:M.actions.map((D)=>k3(j,B,D,M.id))})),actions:U.actions.map((M)=>k3(j,B,M))};let L=new Map(W.status.accounts.map((M)=>[M.routeId,M])),N=($.now??Date.now)(),K=(M)=>({id:"check",label:M?"Check this account":"Check now",group:"Actions",run:async()=>{let P=[...(await X1(Z)).routes].filter((S)=>!M||S===M);if(M&&P.length===0)throw new j0("unavailable","This vault account cannot be checked right now.");for(let S of P){let f=await Z.pollQuota(S);if(!f.ok)throw new j0("quota-check-failed",`${S}: ${f.error??"vault unavailable"}`)}return`Checked quota for ${P.length} account${P.length===1?"":"s"}.`}});if(B==="quota"){let M=(D,P)=>T0(c(D.quota,$.quota?.scope),{now:N,form:P});return{lines:W.status.accounts.filter((D)=>!W.routes.has(D.routeId)).map((D)=>`${F1(D)} (${D.enabled?D.state:"disabled"}): ${M(D,"compact")}`),items:W.status.accounts.filter((D)=>W.routes.has(D.routeId)).map((D)=>({id:D.routeId,label:F1(D),group:"Accounts",status:M(D,"compact"),detail:M(D,"full"),actions:[K(D.routeId)]})),actions:W.routes.size>0?[K()]:[]}}let F=U.items.map((M)=>{let D=L.get(M.id),P=D&&B==="accounts"?`Vault · ${D.credentialType==="oauth"?"login":"API key"} · ${D.state} · ${D.enabled?"enabled":"declined"}`:M.detail;return{id:M.id,label:M.label,detail:P,group:M.group,status:D&&B==="accounts"?D.enabled?D.state:"disabled":M.status,...M.facts?{facts:M.facts}:{},actions:D&&B!=="limits"?[]:M.actions.map((S)=>k3(j,B,S,M.id))}}),C=U.actions.filter((M)=>B==="limits"||B==="routing"&&M.id==="mode").map((M)=>k3(j,B,M));return{lines:B==="accounts"?[`${W.status.accounts.length} vault account${W.status.accounts.length===1?"":"s"}`,`${W.routes.size} can route`,o2]:U.lines,items:F,actions:C}},G=R1({...$,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(B)=>z("accounts",B)},quota:{title:"Quota",build:(B)=>z("quota",B)},routing:{title:"Routing",build:(B)=>z("routing",B)},limits:{title:"Limits",build:(B)=>z("limits",B)}},extras:$.extras?.map((B)=>B.id!=="reset"?B:{...B,build:async(H)=>{let W=await X1(Z);if(U$(W))return{lines:[o2]};return B.build(H)}})}),Q=async()=>{if(!U$(await X1(Z)))return{menu:X,error:void 0};let B=await H5(Z);return{menu:G,error:B}},Y=async(B,H)=>{let W=await B.menu.open(H);if(B.error)W.menu.sections.find((j)=>j.id==="vault")?.lines.push(`Last error: ${B.error}`);return W};return{command:$.command,open:async(B)=>Y(await Q(),B),apply:async(B,H)=>{let W=await Q(),{menu:V}=W;if(V===G&&(B.sectionId==="accounts"||B.sectionId==="routing"&&B.actionId==="order"||B.sectionId==="reset"||B.sectionId==="quota"&&(await X1(Z)).routes.size===0||B.sectionId==="limits"&&B.itemId!==void 0&&!(await X1(Z)).status.accounts.some((j)=>j.routeId===B.itemId)))return{...await Y(W,H),ok:!1,code:"vault-local-action",text:t2};return V.apply(B,H)}}}var P1="openai",X4="OpenAI accounts",q$="main",q5="that account is already your main account, so it was not added again",$6=s("commands"),K5=new Set(["__proto__","constructor","prototype"]);function D5($,Z){let X={version:1,accounts:[],killswitch:$},J=k0($.accounts)?Object.keys($.accounts):[],z={};for(let Y of new Set([q$,...Z,...J])){if(K5.has(Y))continue;let B=L1(X,Y===q$?void 0:Y);z[Y]={primary:B.primary,secondary:B.secondary}}let G=L1(X,void 0),Q={...$};return delete Q.main,Q.accounts=z,Q.defaults={primary:G.primary,secondary:G.secondary},Q.schema=j$,Q}function N5($,Z){let X=k0($.accounts)?{...$.accounts}:{};for(let z of new Set([q$,...Z])){if(K5.has(z)||Object.hasOwn(X,z))continue;X[z]={primary:M1.primary,secondary:M1.secondary}}let J=k0($.defaults)?$.defaults:{primary:M1.primary,secondary:M1.secondary};return{...$,accounts:X,defaults:J,schema:j$}}function $4($,Z){let X=!1;if(k0($.cachekeep))$.cacheKeep={...$.cachekeep,...k0($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,X=!0;let J=$.killswitch;if(k0(J)&&J.schema!==j$)$.killswitch=D5(J,Z),X=!0;return X}async function U5($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((X)=>X.id):[]}function M5($){let Z=async()=>{let J=await $.readSettings();if(J.status==="error")return J;let z=structuredClone(J.settings);return $4(z,await U5($)),{...J,settings:z}},X=async(J,z)=>{let G=await U5($);return $.updateSettings(async(Q)=>{$4(Q,G);let Y=await J(Q)??Q;if(k0(Y.killswitch)&&Y.killswitch.schema!==j$)Y.killswitch=N5(Y.killswitch,G);return Y},z)};return new Proxy($,{get(J,z){if(z==="readSettings")return Z;if(z==="updateSettings")return X;let G=Reflect.get(J,z,J);return typeof G==="function"?G.bind(J):G}})}function L5($,Z){let X=(B,H)=>Z.rowLocks?Z.rowLocks(B):H,J=(B,H)=>{let W=X(B,H?.extraLocks);return{...H??{},...W?{extraLocks:W}:{}}},z=(B,H,W,V)=>$.replace(B,H,W,J(B,V)),Y={add:async(B,H)=>{let W=await $.read(),j=(W.status==="ready"?W.rows:[]).filter((N)=>N.type==="oauth"&&!N.invalid),q=B.identity?j.find((N)=>N.identity===B.identity):void 0;if(q?.id===q$)throw new j0("main-account",q5);let U=q??j.find((N)=>N.id===B.id&&N.id!==q$);if(!U||B.credential.type!=="oauth")return $.add(B,H);let L=await z(U.id,B.credential,B.identity!==void 0?{identity:B.identity}:{},H?.extraLocks?{extraLocks:H.extraLocks}:void 0);return $6.info("account signed in again",{id:U.id}),{id:L.id,outcome:"rotated",credential:L.credential,credentialEpoch:L.credentialEpoch}},replace:z,enable:(B,H)=>$.enable(B,J(B,H)),disable:(B,H,W)=>$.disable(B,H,J(B,W)),remove:(B,H)=>$.remove(B,J(B,H))};return new Proxy($,{get(B,H){if(Object.hasOwn(Y,H))return Y[H];let W=Reflect.get(B,H,B);return typeof W==="function"?W.bind(B):W}})}var F5="migration";function Z4($){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."],X={command:P1,title:X4,sections:[{id:F5,slot:"extra",title:"Accounts are moving",lines:Z,items:$.map((J,z)=>({id:`blocker-${z}`,label:J.pid==="unknown"?"processes that could not be read":`pid ${J.pid}`,detail:`version ${J.version}`,actions:[]})),actions:[]}]};return nY(X)}var iY=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function aY($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(iY.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function f3($,Z,X){if(Array.isArray($))return $.map((z,G)=>f3(z,`${Z}[${G}]`,X));if(!k0($))return $;let J={};for(let[z,G]of Object.entries($)){if(aY(z)){X.push(`${Z}.${z}`);continue}J[z]=f3(G,`${Z}.${z}`,X)}return J}function nY($){let Z=[],X=f3($,"menu",Z);if(Z.length>0)$6.warn("credential-shaped field stripped before RPC",{fields:Z});return X}function P5($){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 O5($){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(Z)=>{let X=typeof Z.label==="string"&&Z.label.trim().length>0?Z.label.trim():void 0,J=Z.headless===!0,z=await $.begin({...X!==void 0?{label:X}:{},headless:J}),G=J?`Open this verification URL:
95
101
 
96
- The custody runtime is not ready. Try again after OpenAI auth finishes initializing.`,knobs:{accounts:J.map(h),claustrumMode:f(X)}};_.info("claustrum transition starting",{});let G;try{G=await Z.enterClaustrumMode()}catch(W){throw _.error("claustrum transition threw",{error:W instanceof Error?W.message:String(W)}),W}_.info("claustrum transition finished",{status:G.status,reason:G.reason,outcomes:G.outcomes});let Q=await Z.loadAccounts(m(Z))??{version:1,accounts:[]},Y=Object.entries(G.outcomes).map(([W,B])=>`- \`${W}\`: ${B}`);return{command:"openai-account",text:[`## Claustrum ${G.status}`,"","do not run a login in another OpenCode window during this transition","",...Y.length>0?Y:["- No enabled OAuth accounts."],...G.reason?["",`Reason: ${G.reason}`]:[]].join(`
97
- `),knobs:{accounts:Q.accounts.map(h),claustrumMode:f(Q)}}}if(z[0]==="local"){if(_.info("local mode requested",{hasLeaveFn:typeof Z.leaveClaustrumMode==="function"}),!Z.leaveClaustrumMode)return _.warn("local refused: transition fn absent from command context"),{command:"openai-account",text:`## Local Mode Unavailable
102
+ ${z.url}
98
103
 
99
- The custody runtime is not ready. Try again after OpenAI auth finishes initializing.`,knobs:{accounts:J.map(h),claustrumMode:f(X)}};await Z.leaveClaustrumMode();let G=await Z.loadAccounts(m(Z))??{version:1,accounts:[]};return{command:"openai-account",text:"## Local Mode\n\nClaustrum mode is now local. Run a fresh `/login openai` for each account, then remove its binding with `ck auth` before it can refresh locally.",knobs:{accounts:G.accounts.map(h),claustrumMode:f(G)}}}if((z[0]==="enable"||z[0]==="disable")&&z[1]){let G=z[1],Q=z[0]==="enable",Y,W=!1,j=await(Z.withFallbackAccountLock??(async(q,K)=>K()))(G,async()=>{let q=await Z.loadAccounts(m(Z)),K=q?.accounts.find((L)=>L.id===G&&L.type==="oauth");if(!K)return q??{version:1,accounts:[]};if(Q&&f(q)==="claustrum"){let L=Z.checkUsableCustodyBinding?await Z.checkUsableCustodyBinding(K):{ready:!1,reason:"unbound-under-claustrum"};if(!L.ready)return Y=L.reason,q;return G0((U)=>{let D=U.accounts.find((P)=>P.id===G&&P.type==="oauth");if(!D)return U;return W=!0,D.accountId=L.accountId,D.enabled=!0,U},m(Z))}return G0((L)=>{let U=L.accounts.find((D)=>D.id===G);if(!U)return L;return W=!0,U.enabled=Q,L},m(Z))})??{version:1,accounts:[]};if(Y)return{command:"openai-account",text:`## Cannot Enable Account
104
+ Then enter the code: ${z.instructions.match(/Enter code: (.+)/)?.[1]??z.instructions}
100
105
 
101
- \`${G}\` remains disabled: ${Y}. Resolve the custody binding, then try again.`,knobs:{accounts:j.accounts.map(h),claustrumMode:f(j)}};if(!W)return{command:"openai-account",text:`## Account Not Found
106
+ The account is added when you finish.`:`Open this URL and complete sign-in:
102
107
 
103
- No account with id \`${G}\` exists.`,knobs:{accounts:j.accounts.map(h),claustrumMode:f(j)}};return{command:"openai-account",text:`## Account ${Q?"Enabled":"Disabled"}
108
+ ${z.url}
104
109
 
105
- \`${G}\` is ${Q?"enabled":"disabled"}.`,knobs:{accounts:j.accounts.map(h),claustrumMode:f(j)}}}if(z.length===0||z.length===1&&z[0]==="list"){let G=["## OpenAI Accounts",""];if(J.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let Q=X.routing?.mode??"main-first";G.push(`Routing: \`${Q}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let Y of J){let W=Y.type??"oauth";G.push(`- \`${Y.id}\` (${W})`)}}return G.push(""),G.push(`Claustrum mode: \`${f(X)}\`
110
+ ${z.instructions}
106
111
 
107
- Commands: \`/openai-account claustrum\` | \`/openai-account local\` | \`/openai-account add [label]\` | \`/openai-account enable <id>\` | \`/openai-account disable <id>\` | \`/openai-account remove <id>\``),{command:"openai-account",text:G.join(`
108
- `),knobs:{accounts:J.map(h),claustrumMode:f(X)}}}if(z[0]==="remove"&&z[1]){let G=z[1],Q=await Y$(Z.accountStoragePath),Y=Q?Q.has(G):!1,W=!1,B=await G0((j)=>{let q=j.accounts.findIndex((K)=>K.id===G);if(q===-1)return j;return j.accounts.splice(q,1),W=!0,j},m(Z),{allowDrop:[G]});if(!(W||Y))return{command:"openai-account",text:`## Account Not Found
109
-
110
- No account with id \`${G}\` exists.`,knobs:{accounts:B.accounts.map(h)}};return _.info("account removed",{id:G}),Z.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
111
-
112
- Removed account \`${G}\`.`,knobs:{accounts:B.accounts.map(h)}}}if(z[0]==="order"&&z.length>=3){let G=!1,Q=await G0((Y)=>{let W=Y.accounts.findIndex((j)=>j.id===z[1]),B=Y.accounts.findIndex((j)=>j.id===z[2]);if(W===-1||B===-1)return Y;G=!0;let V=Y.accounts[W];return Y.accounts[W]=Y.accounts[B],Y.accounts[B]=V,Y},m(Z));if(!G)return{command:"openai-account",text:`## Invalid Order
113
-
114
- Both account IDs must exist.`,knobs:{accounts:Q.accounts.map(h)}};return _.info("accounts reordered",{a:z[1],b:z[2]}),Z.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
115
-
116
- Swapped positions of \`${z[1]}\` and \`${z[2]}\`.`,knobs:{accounts:Q.accounts.map(h)}}}if(z[0]==="add"){if(X.claustrum?.mode==="claustrum")return{command:"openai-account",text:"## Add Failed\n\nThat account cannot be added while Claustrum mode is active. Run `/openai-account local` first.",knobs:{}};let G=z.includes("--headless"),Q=z.filter((K)=>K!=="add"&&K!=="--headless"),Y=Q.length>0?Q.join(" "):void 0,{url:W,instructions:B,completion:V}=await(Z.beginAccountLogin??g1)({label:Y,headless:G,version:Z.packageVersion}),j=Z.notify,q=Z.sessionId;if(V.then(async(K)=>{let L;if(await(Z.withFallbackAccountLock??(async(D,P)=>P()))(K.id,async()=>{let D=await Z.loadAccounts(m(Z));if(f(D??{})==="claustrum"){L="claustrum mode";return}await G0((P)=>{if(K.accountId&&P.mainAccountId&&K.accountId===P.mainAccountId)return L="main identity",P;return m1(P.accounts,K),P},m(Z))}),L){let D=L==="claustrum mode"?"That account cannot be added while Claustrum mode is active. Run `/openai-account local` first.":"That account is already your main account — not added as a fallback.";_.warn(`account add rejected (${L})`,{id:K.id,sessionId:q}),j?.({command:"openai-account",text:`## Add Failed
117
-
118
- ${D}`,knobs:{}});return}_.info("account added",{id:K.id,label:K.label}),Z.refreshSidebar?.().catch(()=>{}),j?.({command:"openai-account",text:`## Account Added
119
-
120
- Added account \`${K.id}\`${K.label?` ("${K.label}")`:""}.
121
-
122
- Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((K)=>{let L=K instanceof Error?K.message:String(K??"unknown error");_.warn("account add failed",{error:L,sessionId:q}),j?.({command:"openai-account",text:`## Add Failed
123
-
124
- Account add failed: ${L}`,knobs:{}})}),G){let K=B.match(/Enter code: (.+)/)?.[1]??B;return{command:"openai-account",text:`## Device Code
125
-
126
- 1. Open this verification URL:
127
-
128
- ${W}
129
-
130
- 2. Enter the code: **${K}**
131
-
132
- ${B}
133
-
134
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:W,userCode:K,instructions:B}}}return{command:"openai-account",text:`## Add OpenAI Account
135
-
136
- Open this URL and complete sign-in:
137
-
138
- ${W}
139
-
140
- ${B}
141
-
142
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:W,instructions:B}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account claustrum` — enter Claustrum mode\n- `/openai-account local` — leave Claustrum mode\n- `/openai-account add [label]` — add a new account\n- `/openai-account enable <id>` — enable a fallback\n- `/openai-account disable <id>` — disable a fallback\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:J.map(h),claustrumMode:f(X)}}}async function b6($,Z){let z=$.trim().toLowerCase().split(/\s+/).filter(Boolean),J=(await Z.loadAccounts(m(Z))??{version:1,accounts:[]}).routing?.mode??"main-first";if(z.length===1&&z[0]==="reset"){if(!Z.sessionId)return{command:"openai-routing",text:`## OpenAI Routing Reset
143
-
144
- No current session is available, so no pin was changed.`,knobs:{mode:J}};if(!Z.clearStickyRouting)return{command:"openai-routing",text:`## OpenAI Routing Reset
145
-
146
- This runtime cannot clear the current session pin.`,knobs:{mode:J}};return await Z.clearStickyRouting(Z.sessionId),_.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
147
-
148
- This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:J}}}if(z.length===1&&(z[0]==="main-first"||z[0]==="fallback-first"||z[0]==="sticky-balanced")){let Y=z[0];return await G0((W)=>{return W.routing={...W.routing??{},mode:Y},W},m(Z)),_.info("routing mode changed",{mode:Y}),{command:"openai-routing",text:`## OpenAI Routing Updated
149
-
150
- Mode: \`${Y}\`
151
- - ${A$(Y)}
152
-
153
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:Y}}}let G=J==="sticky-balanced"&&Z.sessionId?await Z.getStickyRouting?.(Z.sessionId):void 0,Q=J==="sticky-balanced"?G?`
154
- - Session pin: \`${G}\`. Use \`/openai-routing reset\` to clear it.`:`
155
- - Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
156
-
157
- - Mode: \`${J}\`
158
- - ${A$(J)}${Q}
159
-
160
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:J}}}function k$($){let Z=[$.primary?.usedPercent,$.secondary?.usedPercent].filter((z)=>z!==void 0);return Z.length>0?Math.max(...Z):void 0}function S6($,Z){let z=[$.primary,$.secondary].filter((J)=>J!==void 0),X=z.filter((J)=>E0(J,Z));return(X.length>0?X:z).sort((J,G)=>G.usedPercent-J.usedPercent)[0]?.resetsAt}function k6($,Z){if(!$)return!1;let z=[$.primary,$.secondary].filter((X)=>X!==void 0);if(z.length===0)return!1;return z.every((X)=>!E0(X,Z))}function Z1($){if(!$)return;try{return decodeURIComponent($)}catch{return}}async function b$($,Z){let z;try{z=await Z.resolveResetTarget($);let X=z.accountKey==="main"?void 0:z.chatgptAccountId,[J,G]=await Promise.all([d8({accessToken:z.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:z.chatgptAccountId}),e8(Z.fetchImpl,z.accessToken,X)]),Q=$8(G.credits),Y=F$(G.credits),W=G.availableCount??J.resetCreditsAvailable??(Y>0?Y:void 0),B=J.resetCreditsApplicable,V=r8(J,Z.quotaManager.isRateLimited($),Z.now()),j;if(!z.chatgptAccountId)j="stable ChatGPT account identity unavailable";else if(!V.ok)j=V.reason;else if(!Q)j="no eligible credit";return{accountKey:z.accountKey,label:z.label,chatgptAccountId:z.chatgptAccountId,usedPercent:k$(J),resetTime:S6(J,Z.now()),availableCount:W,applicableAvailableCount:B,eligible:j===void 0,reason:j,selectedCreditId:Q?.id,selectedCreditExpiresAt:Q?.expiresAt}}catch(X){if(X?.status===401)await z?.onAuthFailure?.(401);return _.warn("reset preview row failed",{accountKey:$,error:X?.message??String(X)}),{accountKey:$,label:$==="main"?"Main account":$,eligible:!1,reason:X?.message??String(X)}}}function w6($){let Z=["## Reset credits","","Select an account to fetch a fresh confirmation preview:",""];for(let z of $){let X=z.usedPercent===void 0?"quota unavailable":`${z.usedPercent}% used`,J=z.availableCount===void 0?"credits unavailable":`${z.applicableAvailableCount===void 0?"?":z.applicableAvailableCount}/${z.availableCount} applicable/available`,G=z.eligible?`eligible · credit ${z.selectedCreditId} expires ${z.selectedCreditExpiresAt}`:z.reason;Z.push(`- **${z.label}** (\`${z.accountKey}\`) — ${X}; ${J}; ${G}`)}return Z.push(""),Z.push("Command: `/openai-reset select <encodedAccountKey>`"),Z.join(`
161
- `)}function S$($){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(`Confirm: \`/openai-reset confirm ${encodeURIComponent($.accountKey)} ${encodeURIComponent($.chatgptAccountId)}\``);else Z.push(`Cannot reset: **${$.reason??"not eligible"}**`);return Z.join(`
162
- `)}function g($,Z,z,X={}){return{command:y0,text:z,knobs:{stage:"result",accountKey:$,code:Z,...X}}}function f6($,Z,z){if(Z instanceof c){let J={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",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 g($,Z.kind,`## Reset credit
163
-
164
- ${J[Z.kind]}
165
-
166
- Code: \`${Z.kind}\``,{cooldownUntil:Z.cooldownUntil,...Z.kind==="expired_unreconciled"?{chatgptAccountId:z,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 g($,X,`## Reset credit
167
-
168
- ${{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]}
169
-
170
- Code: \`${X}\``);if(Z instanceof q0)return g($,Z.kind,`## Reset credit
171
-
172
- No redemption was attempted: reset credit availability could not be loaded.
173
-
174
- Code: \`${Z.kind}\``);return _.warn("reset command failed before a known result",{accountKey:$,error:Z?.message??String(Z)}),g($,"error",`## Reset credit
175
-
176
- The reset request failed before a known result: internal command failure — see plugin log.`)}async function w$($,Z,z){let{accountKey:X}=$.target,J=$.outcome.kind;if($.finalizeStateWriteFailed)return g(X,J,`## Reset credit result
177
-
178
- Account: **${$.target.label}** (\`${X}\`)
179
-
180
- The server outcome recorded as \`${J}\`, 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:z});if(J==="reset"||J==="already_redeemed"){let Q={account:X,ok:!1,error:"targeted quota refresh did not complete"};try{Q=await Z.refreshResetTargetQuota(X)}catch(K){Q.error=K?.message??String(K)}let Y=!Q.ok&&Q.error!==void 0;if(Y)_.warn("reset quota re-check failed",{accountKey:X,error:Q.error});let W=X==="main"?Z.quotaManager.getMain():Z.quotaManager.getFallback(X),B=Q.ok&&k6(W?.quota,Z.now()),V=W?.quota.resetCreditsApplicable,j=B?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${J}\`).`,q=Y?`
181
-
182
- quota re-check failed — see log.`:"";return g(X,J,`## Reset credit result
183
-
184
- Account: **${$.target.label}** (\`${X}\`)
185
-
186
- Code: \`${J}\`
187
-
188
- ${j}${q}${V===void 0?"":`
189
-
190
- Remaining applicable credits: **${V}**`}`,{verifiedFresh:B,afterUsedPercent:k$(W?.quota??{}),remainingCredits:V})}if(J==="ambiguous_local")return g(X,J,`## Reset credit result
191
-
192
- Account: **${$.target.label}** (\`${X}\`)
193
-
194
- Code: \`${J}\`
195
-
196
- ${$.retrySafety}`,{retryGuidance:$.retrySafety});if(J==="ambiguous"||J==="http_error"){let Q=z?`/openai-reset retry ${encodeURIComponent(X)} ${encodeURIComponent(z)}`:"/openai-reset";return g(X,J,`## Reset credit result
197
-
198
- Account: **${$.target.label}** (\`${X}\`)
199
-
200
- The redemption outcome is unknown (\`${J}\`).
201
-
202
- Retry with \`${Q}\`. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{retryGuidance:$.retrySafety,chatgptAccountId:z})}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 g(X,J,`## Reset credit result
203
-
204
- Account: **${$.target.label}** (\`${X}\`)
205
-
206
- Code: \`${J}\`
207
-
208
- ${G[J]??"The server returned a no-op result. No reset was confirmed."}`)}async function E6($,Z){let z=[Z.resolveResetTarget?void 0:"resolveResetTarget",Z.fetchImpl?void 0:"fetchImpl",Z.now?void 0:"now",Z.randomUUID?void 0:"randomUUID",Z.refreshResetTargetQuota?void 0:"refreshResetTargetQuota"].filter((Q)=>Q!==void 0);if(z.length>0)return _.warn("reset command dependencies unwired",{missingDeps:z}),{command:y0,text:`## Reset credit
209
-
210
- Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let X=Z,J=$.trim().split(/\s+/).filter(Boolean),G=J[0];if(!G||G==="refresh"){let Y=["main",...((await Z.loadAccounts(m(Z)))?.accounts??[]).filter((B)=>B.enabled!==!1&&B.type==="oauth").map((B)=>B.id)];_.debug("reset accounts stage requested",{accountKeys:Y});let W=await Promise.all(Y.map((B)=>b$(B,X)));return _.debug("reset accounts stage built",{rows:W.map((B)=>({accountKey:B.accountKey,eligible:B.eligible,reason:B.reason,usedPercent:B.usedPercent,availableCount:B.availableCount,applicableAvailableCount:B.applicableAvailableCount}))}),{command:y0,text:w6(W),knobs:{stage:"accounts",accounts:W}}}if(G==="select"){let Q=Z1(J[1]);if(!Q||!i(Q)||J.length!==2)return g("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let Y=await b$(Q,X);if(!Y.eligible)return g(Q,"not_eligible",S$(Y));return{command:y0,text:S$(Y),knobs:{stage:"confirm",preview:Y}}}if(G==="confirm"||G==="retry"){let Q=Z1(J[1]),Y=Z1(J[2]);if(!Q||!i(Q)||!Y||J.length!==3)return g(Q??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);_.info("reset redemption decision",{accountKey:Q,action:G}),_.debug("reset redemption identity binding",{accountKey:Q,expectedChatgptAccountId:Y});try{let W=await I$({configPath:Z.accountStoragePath,statePath:Z.accountStatePath,mutateAccountsFn:G0,loadAccountsFn:Z.loadAccounts,now:X.now,randomUUID:X.randomUUID,fetchImpl:X.fetchImpl,resolveTarget:X.resolveResetTarget,fetchUsage:(B)=>d8({accessToken:B.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:Q,expectedChatgptAccountId:Y,retry:G==="retry"});return _.info("reset redemption outcome",{accountKey:Q,code:W.outcome.kind}),w$(W,X,Y)}catch(W){let B=f6(Q,W,Y);return _.info("reset redemption outcome",{accountKey:Q,code:B.knobs.code}),B}}return g("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var y6=new Set(["access","refresh","apikey","authheader","password","secret"]);function v6($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(y6.has(Z))return!0;return Z.endsWith("token")}function Z8($,Z,z){if(Array.isArray($))return $.map((J,G)=>Z8(J,`${Z}[${G}]`,z));if(!R$($))return $;let X={};for(let[J,G]of Object.entries($)){if(v6(J)){z.push(`${Z}.${J}`);continue}X[J]=Z8(G,`${Z}.${J}`,z)}return X}async function z1($,Z,z,X={}){let J=await h6($,Z,z,X),G=[],Q=Z8(J.knobs,"knobs",G);if(G.length>0)return _.warn("credential-shaped knob stripped before RPC",{command:$,fields:G}),{...J,knobs:Q};return J}async function h6($,Z,z,X){switch($){case"openai-quota":return T6(z);case"openai-account":return C6(Z,z);case"openai-routing":return b6(Z,z);case"openai-reset":return E6(Z,z);default:{let J=X[$];if(!J)throw Error(`unhandled command: ${$}`);return J(Z,z)}}}import{readdirSync as x9,statSync as F9}from"node:fs";import{tmpdir as I9,userInfo as R9}from"node:os";import{join as p0}from"node:path";import{debuglog as t6}from"node:util";import{createHmac as l6,randomBytes as d6,timingSafeEqual as i6}from"node:crypto";import u6 from"node:net";var p=2,G8=21,Q8=5,X1=67108864,H;(function($){$[$.Request=0]="Request",$[$.Response=1]="Response",$[$.Push=2]="Push",$[$.StreamData=3]="StreamData",$[$.StreamEnd=4]="StreamEnd",$[$.Error=5]="Error",$[$.Cancel=6]="Cancel",$[$.Ping=7]="Ping",$[$.Pong=8]="Pong",$[$.Hello=9]="Hello",$[$.HelloAck=10]="HelloAck",$[$.Goodbye=11]="Goodbye"})(H||(H={}));var f$=H.Goodbye;function E$($){return $===H.Cancel||$===H.Ping||$===H.Pong||$===H.Goodbye}var C;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(C||(C={}));var w;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(w||(w={}));var m6=1,y$=6,J1=1,g6=8,v$=48,G1=4,h$=192;function v($,Z,z,X=w.Normal){let J=0;if($)J|=m6;if(J|=Z<<J1,z)J|=g6;return J|=X<<G1,J}function m$($){let Z=new Uint8Array(21),z=new DataView(Z.buffer);return z.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,z.setUint16(7,$.channel,!0),z.setUint32(9,$.epoch,!0),z.setBigUint64(13,$.corr,!0),Z}class x extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function p6($){let Z=$.len>>>0,z=$.ver>>>0&255,X=$.ty>>>0&255,J=$.flags>>>0&255,G=$.channel>>>0&65535,Q=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),z!==2)throw new x(`unsupported envelope version ${z}`,"unsupported_version");if(X>f$)throw new x(`unknown frame type byte ${X}`,"unknown_frame_type");let Y=X;if((J&h$)!==0)throw new x(`reserved flag bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((J&y$)>>J1===3)throw new x(`reserved priority bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(J&v$)>>G1;if(W===3)throw new x(`reserved admission class set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===w.Sheddable&&Y!==H.Push&&Y!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[Y]} in flags 0b${J.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(G===0&&Q!==0)throw new x(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(E$(Y)&&Z!==0)throw new x(`pure-header frame ${H[Y]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function Q1($){if($.length<5)throw new x(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new x(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new x(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let z=new DataView($.buffer,$.byteOffset,$.byteLength),X=z.getUint32(0,!0),J=$[5];if(J>f$)throw new x(`unknown frame type byte ${J}`,"unknown_frame_type");let G=J,Q=$[6];if((Q&h$)!==0)throw new x(`reserved flag bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((Q&y$)>>J1===3)throw new x(`reserved priority bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Y=(Q&v$)>>G1;if(Y===3)throw new x(`reserved admission class set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Y===w.Sheddable&&G!==H.Push&&G!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[G]} in flags 0b${Q.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=z.getUint16(7,!0),B=z.getUint32(9,!0);if(W===0&&B!==0)throw new x(`control channel carried nonzero epoch ${B}`,"nonzero_epoch_on_control_channel");if(E$(G)&&X!==0)throw new x(`pure-header frame ${H[G]} declared non-zero body length ${X}`,"pure_header_frame_with_body");return{len:X,ver:Z,ty:G,flags:Q,channel:W,epoch:B,corr:z.getBigUint64(13,!0)}}function E($,Z,z,X,J,G){return a(2,$,Z,z,X,J,G)}function a($,Z,z,X,J,G,Q){if(Q.length>67108864)throw new x(`frame body ${Q.length} exceeds max 67108864`,"frame_body_too_large");let Y={len:Q.length,ver:$,ty:Z,flags:z,channel:X,epoch:J,corr:G};return p6(Y),{header:Y,body:Q}}function t($){if($.header.len!==$.body.length)throw new x(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=m$($.header),z=new Uint8Array(Z.length+$.body.length);return z.set(Z,0),z.set($.body,Z.length),z}class Z0 extends Error{}class s extends Error{}class o extends Error{cause;constructor($,Z){super($);this.cause=Z}}class Q0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function g$($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var p$=Symbol("subc.socket.writeBorrowed"),u$=Symbol("subc.socket.writeTrackedBorrowed");function r($,Z,z){let X=$[p$];return X?X.call($,Z,z):$.write(Z,z)}function Y1($,Z,z){let X=$[u$];return X?X.call($,Z,z):$.writeTracked(Z,z)}class H0{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(z)=>{this.chunks.push(z),this.buffered+=z.length,this.tryServe()});let Z=(z)=>{if(!this.closedErr)this.closedErr=z;this.tryServe()};$.on("error",(z)=>Z(z instanceof Error?z:Error(String(z)))),$.on("end",()=>Z(new Z0("subc closed the connection"))),$.on("close",()=>Z(new Z0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,z){return new Promise((X,J)=>{let G=u6.connect({host:$,port:Z});G.setNoDelay(!0);let Q=setTimeout(()=>{G.destroy(),J(new s(`timed out connecting to ${$}:${Z}`))},Math.max(0,z-Date.now()));G.once("connect",()=>{clearTimeout(Q),X(new H0(G))}),G.once("error",(Y)=>{clearTimeout(Q),J(Y)})})}async readFrame($,Z,z){let X=await this.readExact(Q8,$),J=X[4];if(J!==p)throw new x(`unsupported envelope version ${J}`,"unsupported_version");let G=await this.readExact(G8-Q8,$),Q=new Uint8Array(G8);Q.set(X),Q.set(G,Q8);let Y=Q1(Q);if(Y.len>X1)throw new x(`frame body ${Y.len} exceeds max ${X1}`,"frame_body_too_large");z?.();let W=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,B=Y.len===0?new Uint8Array(0):await this.readExact(Y.len,W);return{header:Y,body:B}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((z,X)=>{let J=null;if(Number.isFinite(Z)){let G=Z-Date.now();if(G<=0){X(new s(`timed out waiting for ${$} bytes`));return}J=setTimeout(()=>{this.waiter=null,X(new s(`timed out waiting for ${$} bytes`))},G)}this.waiter={need:$,resolve:z,reject:X,timer:J},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[p$]($,Z){await this.writeBuffer(g$($),Z)}[u$]($,Z){return this.writeTrackedBuffer(g$($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(z){if(z instanceof o||z instanceof Q0)throw z.cause??z;throw z}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new o("subc socket was closed before bytes could be queued",this.closedErr))};let z=!1,X=!1,J=null,G=new Promise((Q,Y)=>{let W=(V)=>{if(X)return;if(X=!0,J)clearTimeout(J);V()},B=Z-Date.now();if(B<=0){W(()=>Y(new o("timed out before bytes could be queued to subc",new s("timed out writing to subc"))));return}J=setTimeout(()=>{let V=new s("timed out writing to subc");W(()=>Y(z?new Q0("timed out after bytes were handed to the subc socket",V):new o("timed out before bytes could be queued to subc",V)))},B);try{this.sock.write($,(V)=>{W(()=>{if(V)Y(new Q0("subc socket reported a write error after bytes were handed to the socket",V instanceof Error?V:Error(String(V))));else Q()})}),z=!0}catch(V){W(()=>Y(new o("subc socket write threw before bytes could be queued",V instanceof Error?V:Error(String(V)))))}});return{queued:z,completed:G}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),z=0;while(z<$){let X=this.chunks[0],J=$-z;if(X.length<=J)X.copy(Z,z),z+=X.length,this.chunks.shift();else X.copy(Z,z,0,J),this.chunks[0]=X.subarray(J),z+=J}return this.buffered-=$,Z}}var i$=32;var Y8=4096,c$="subc-server-v1",s$="subc-client-v1",c6="client";class y extends Error{}function B1($,Z,z,X,J){let G=l6("sha256",Buffer.from($));return G.update(Buffer.from(Z,"utf8")),G.update(Buffer.from(z)),G.update(Buffer.from(X)),G.update(Buffer.from(J)),new Uint8Array(G.digest())}function l$($,Z){if($.length!==Z.length)return!1;return i6(Buffer.from($),Buffer.from(Z))}async function d$($,Z,z){let X=Buffer.from(JSON.stringify(Z),"utf8");if(X.length>Y8)throw new y(`auth message too large: ${X.length} > ${Y8}`);let J=new Uint8Array(4);new DataView(J.buffer).setUint32(0,X.length,!0),await r($,J,z),await r($,X,z)}async function s6($,Z){let z=await $.readExact(4,Z),X=new DataView(z.buffer,z.byteOffset,4).getUint32(0,!0);if(X>Y8)throw new y(`auth message too large: ${X} > ${Y8}`);let J=X===0?new Uint8Array(0):await $.readExact(X,Z);try{return JSON.parse(Buffer.from(J).toString("utf8"))}catch(G){throw new y(`auth message JSON decode failed: ${String(G)}`)}}function W1($,Z){if(!Array.isArray($))throw new y(`auth field '${Z}' must be a byte array`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new y(`auth field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}async function v0($,Z,z){let X=new Uint8Array(d6(i$));await d$($,{client_nonce:Array.from(X),role:c6},z);let J=await s6($,z),G=W1(J.server_nonce,"server_nonce"),Q=W1(J.daemon_id,"daemon_id"),Y=W1(J.server_proof,"server_proof"),W=B1(Z.key,c$,X,G,Q);if(!l$(W,Y))throw new y("server proof mismatch — wrong key or impostor daemon");if(!l$(Q,Z.daemonId))throw new y("daemon id mismatch — connection file points at a different daemon");let B=B1(Z.key,s$,X,G,Q);await d$($,{client_auth:Array.from(B)},z)}import{promises as V1}from"node:fs";var n$=1,a$=32,t$=16;class b extends Error{}function o$($,Z){if(!Array.isArray($))throw new b(`connection file field '${Z}' must be a JSON array of bytes`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new b(`connection file field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}function n6($){if($.schema!==n$)throw new b(`unsupported connection file schema ${$.schema}; expected ${n$}`);if($.endpoints.length===0)throw new b("connection file must include at least one endpoint");if($.key.length<a$)throw new b(`connection file key is too short: ${$.key.length} bytes, need at least ${a$}`);if($.daemonId.length!==t$)throw new b(`connection file daemon_id must be ${t$} bytes, got ${$.daemonId.length}`)}async function a6($){if(process.platform==="win32")return;let z=(await V1.stat($)).mode&511;if((z&63)!==0)throw new b(`connection file ${$} has insecure permissions 0o${z.toString(8)}; expected owner-only 0600`)}async function P0($){await a6($);let Z=await V1.readFile($,"utf8"),z;try{z=JSON.parse(Z)}catch(Y){throw new b(`connection file JSON read failed for ${$}: ${String(Y)}`)}let X=z.wire_version;if(X!==void 0&&X!==p)throw new b(`connection file wire_version ${String(X)} but this client speaks ${p}; the client library must be upgraded`);let J=z.endpoints;if(!Array.isArray(J))throw new b("connection file 'endpoints' must be an array");let G=J.map((Y)=>{let W=Y;if(typeof W.host!=="string"||typeof W.port!=="number")throw new b("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),Q={schema:z.schema,endpoints:G,key:o$(z.key,"key"),daemonId:o$(z.daemon_id,"daemon_id"),pid:z.pid,daemonVer:z.daemon_ver??""};return n6(Q),Q}var r$=new WeakMap;class W8{channel;epoch;constructor($,Z,z){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,r$.set(this,z),Object.freeze(this)}static create($,Z,z){return new W8($,Z,z)}}function B8($,Z,z){return W8.create($,Z,z)}class z0 extends Error{handle;code="stale_route_handle";constructor($){super(`route handle (${$.channel}, ${$.epoch}) is not live on the current connection`);this.handle=$,this.name="StaleRouteHandleError"}}function O0(){return Object.freeze({})}function h0($,Z){return r$.get($)===Z}function V8($,Z){return $===Z}var o6=t6("subc-client"),r6=1e4,m0=30000,e6=50,$9=2000,e$="request_deadline",j1="deadline_exceeded_no_drop_observed",Z9=30000,z9=30000,$3=new Uint8Array(0),X9="management_surface",z3="SUBC_MODULE_ID",X3="SUBC_LAUNCH_NONCE",L8={baseMs:100,capMs:2000,maxAttempts:6};class S extends Error{kind;code;cause;constructor($,Z,z,X){super(Z);this.kind=$,this.code=z,this.cause=X,this.name="SubcCallError"}}class F extends Error{code;constructor($,Z){super($);this.code=Z}}class K0{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=O0();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,z){this.sock=$,this.currentConn=Z,this.opts=z,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=G9($),z=await K0.openConnection(Z);return new K0(z.sock,z.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),z=await this.controlRpc(Z);return this.parseJson(z).modules??[]}async routeOpen($,Z,z={}){let X=q1(z),J=z.consumerCapabilities,G=this.encode({op:"route.open",target:$,identity:Z,...X?{consumer_identity:X}:{},...J!==void 0?{consumer_capabilities:J}:{}}),Q=null,Y=(B)=>{if(B.header.ty!==H.Response)return!0;let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")throw new F(`route.open returned no route handle: ${JSON.stringify(V)}`);return Q=this.installRoute(V.route_channel,V.route_epoch),!0},W=(B)=>{if(B.header.ty!==H.Response)return;try{let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")return;let j=this.installRoute(V.route_channel,V.route_epoch);this.failHandle(j,new F("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(G,Y,W),!Q)throw new F("route.open response was not installed");return Q}async request($,Z,z={}){this.assertLiveHandle($);let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??w.Normal,Q=await this.send($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}async call($,Z,z,X={}){let J=z===void 0?{method:Z}:{method:Z,params:z},G=!1;for(;;){let Q=await this.cachedRouteHandle($,X);try{return await this.managedRequest(Q,J,X)}catch(Y){if(!(Y instanceof S))throw this.terminalCallError("managed call failed",Y);let W=Y.code==="unknown_channel"||Y.code==="stale_route_epoch";if(W&&!G&&!this.closeStarted){G=!0,this.evictRouteHandle(Q);continue}if(W&&G)this.evictRouteHandle(Q);if(Y.kind==="not_sent"){try{await this.reconnectAfterDrop(Y)}catch(B){throw this.notSentRecoveryError("managed call was not sent",B)}continue}if(Y.kind==="outcome_unknown"&&Y.code!==j1)this.scheduleReconnectAfterDrop(Y);else if(Y.kind==="outcome_unknown"&&Y.code===j1)this.probeLivenessAfterDeadline();throw Y}}}subscribe($,Z,z,X={}){this.assertLiveHandle($);let J=Z instanceof Uint8Array?Z:this.encode(Z),G=X.priority??C.Interactive,Q=X.admissionClass??w.Normal,Y=this.allocateCorr(),W=q8($,Y),B=null,V=null,j=new Promise((L,U)=>{if(this.closedErr){U(this.closedErr);return}V=L,B={handle:$,resolve:()=>L(),reject:U,onProgress:z,timer:null,subscription:!0},this.pending.set(W,B);let D=E(H.Request,v(!1,G,!1,Q),$.channel,$.epoch,Y,J);r(this.sock,t(D),Date.now()+m0).catch((P)=>{let A=this.pending.get(W);if(A)this.rejectPending(W,A,P instanceof Error?P:new F(String(P)))})}),q=!1;return{unsubscribe:()=>{if(q)return;if(q=!0,B&&V)this.settle(W,B,V);if(this.isLiveHandle($))this.cancel($,Y,G)},closed:j}}cancel($,Z,z=C.Interactive){this.assertLiveHandle($);let X=E(H.Cancel,v(!1,z,!1),$.channel,$.epoch,Z,$3);r(this.sock,t(X),Date.now()+m0).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let z=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),X=await this.controlRpc(z,(J)=>{if(J.header.ty!==H.Response)return!0;let G=this.parseJson(J);return G.route_channel===$.channel&&G.route_epoch===$.epoch});return this.parseJson(X)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[z,X]of this.routes)if(X.handle&&V8(X.handle,$))X.closed=!0,X.handle=null,this.routes.delete(z);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new F("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,z={}){let X=Z3($,Z,q1(z)),J=this.routes.get(X);if(!J)return;J.closed=!0,this.routes.delete(X);let G=J.handle;if(J.handle=null,G)await this.closeRoute(G,z)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new F("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let z of this.pending.values())if(z.handle===$&&!z.subscription)Z.push(new Promise((X)=>{let J=z.onSettle;z.onSettle=()=>{J?.(),X()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let z=E(H.Goodbye,v(!1,C.Interactive,!1),$.channel,$.epoch,0n,$3),X=Y1(this.sock,t(z),Date.now()+m0);if(!X.queued&&Z)this.closeConnectionAfterCleanupFailure();X.completed.catch(()=>{if(Z&&!X.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await P0($.connectionFile),z=Date.now()+($.handshakeTimeoutMs??r6),X=Z.endpoints[0],J=await H0.connect(X.host,X.port,z);try{await v0(J,Z,z)}catch(G){throw J.close(),G}return{sock:J,conn:Z}}async controlRpc($,Z,z){return this.send(null,$,C.Interactive,w.Normal,void 0,void 0,Z,z)}send($,Z,z,X,J,G,Q,Y){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let W;try{W=this.allocateCorr()}catch(K){return Promise.reject(K)}let B=q8($,W),V=$?.channel??0,j=$?.epoch??0,q=E(H.Request,v(!1,z,!1,X),V,j,W,Z);return new Promise((K,L)=>{let U=J??m0,D={handle:$,resolve:K,reject:L,onProgress:G,timer:null,acceptFrame:Q,onLateResponse:Y};D.timer=setTimeout(()=>this.arbitrateTimeout(B,D,V,W,U),U),this.pending.set(B,D),r(this.sock,t(q),Date.now()+U).catch((P)=>{let A=this.pending.get(B);if(A)this.rejectPending(B,A,P instanceof Error?P:new F(String(P)))})})}arbitrateTimeout($,Z,z,X,J){let G=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new F(this.timeoutMessage(z,X,J),e$))},Q=Date.now()+this.opts.timeoutArbitrationGraceMs,Y=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<Q){setImmediate(Y);return}G()};setImmediate(Y)}async managedRequest($,Z,z){let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??w.Normal;try{let Q=await this.sendManaged($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}catch(Q){if(Q instanceof S)throw Q;throw this.terminalCallError("managed call failed",Q)}}sendManaged($,Z,z,X,J,G){try{this.assertLiveHandle($)}catch(j){return Promise.reject(this.notSentCallError("request used a stale route handle",j))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let Q;try{Q=this.allocateCorr()}catch(j){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",j))}let Y=q8($,Q),W=E(H.Request,v(!1,z,!1,X),$.channel,$.epoch,Q,Z),B=!1,V=(j)=>{if(!B)return this.notSentCallError("request bytes were not queued to the subc socket",j);if(j instanceof F&&j.code===e$)return new S("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${j8(j)}`,j1,j);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",j)};return new Promise((j,q)=>{let K=J??m0,L={handle:$,resolve:j,reject:q,onProgress:G,timer:null,classifyFailure:V};L.timer=setTimeout(()=>this.arbitrateTimeout(Y,L,$.channel,Q,K),K),this.pending.set(Y,L);let U=Y1(this.sock,t(W),Date.now()+K);B=U.queued,U.completed.catch((D)=>{let P=this.pending.get(Y);if(P)this.rejectPending(Y,P,D instanceof Error?D:new F(String(D)))})})}async cachedRouteHandle($,Z){let z=Z.identity??this.opts.identity;if(!z)throw new S("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let X={kind:Z.targetKind??this.opts.targetKind,module_id:$},J=q1(Z),G=Z3(X,z,J),Q=this.routes.get(G);if(!Q)Q={key:G,moduleId:$,target:X,identity:z,consumerIdentity:J,handle:null,opening:null},this.routes.set(G,Q);if(Q.handle&&this.isLiveHandle(Q.handle))return Q.handle;if(!Q.opening)Q.opening=this.openCachedRoute(Q).finally(()=>{Q.opening=null});return Q.opening}async openCachedRoute($){let Z=Date.now()+Z9,z=this.opts.reconnectBackoff.baseMs,X=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(J){throw this.notSentRecoveryError("route.open could not run because reconnect failed",J)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let J=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed)throw this.liveRoutes.delete(J.channel),this.sendRouteGoodbye(J),this.routeClosedDuringOpen();return $.handle=J,J}catch(J){if(J instanceof S&&J.code==="route_closed")throw J;if(!this.closeStarted&&H8(J)){try{await this.reconnectAfterDrop(J)}catch(G){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",G)}continue}if(!this.closeStarted&&J instanceof F&&J9(J.code)){if(X+=1,X<this.opts.reconnectBackoff.maxAttempts&&Date.now()<Z){await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${J.code} (retry budget exhausted)`,J)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,J)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,z;try{z=this.allocateCorr()}catch{return}let X=Date.now(),J=E(H.Ping,v(!1,C.Interactive,!1,w.Normal),0,0,z,new Uint8Array),G=(async()=>{if(await r($,t(J),X+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=X)return;if(this.hasControlPending())return;this.fail(new Z0(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),$.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=G}async ensureConnectedForManaged(){if(this.closeStarted)throw new F("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop($){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop($).catch(()=>{})}reconnectAfterDrop($){if(this.closeStarted)return Promise.reject(new F("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new F("client closed");Z+=1;try{let X=await K0.openConnection(this.opts);if(this.closeStarted)throw X.sock.close(),new F("client closed");this.replaceConnection(X),await this.reopenCachedRoutes();return}catch(X){if(!H8(X)||Z>=this.opts.reconnectBackoff.maxAttempts){if(X instanceof y&&Z>1)throw new y(`reconnect gave up after ${Z} attempts: ${X.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw X}await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){for(let $ of this.routes.values())$.handle=null;for(let $ of this.routes.values()){if($.closed)continue;let Z=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed){this.liveRoutes.delete(Z.channel),this.sendRouteGoodbye(Z);continue}$.handle=Z}}timeoutMessage($,Z,z){let X=this.sock.localPort();return`request on ${X===null?"channel":`local_port=${X} channel`} ${$} corr ${Z} timed out after ${z}ms`}routeClosedDuringOpen(){return new S("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:z9},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(z)}finally{this.readerActive=!1}}}catch(z){if(this.sock===$&&this.generation===Z)this.fail(z instanceof Error?z:new F(String(z)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===H.Push){let G=this.opts.onControlPush;if(G){let Q=null;try{let Y=this.parseJson($);if(Y&&typeof Y.op==="string")Q={op:Y.op,body:Y}}catch{}if(Q)try{G(Q)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let z=q8(Z,$.header.corr),X=this.pending.get(z);if(X){if(X.acceptFrame&&!X.acceptFrame($))return;switch($.header.ty){case H.Push:case H.StreamData:try{X.onProgress?.($.body)}catch{}return;case H.Response:case H.StreamEnd:this.settle(z,X,()=>X.resolve($));return;case H.Error:this.settle(z,X,()=>X.reject(this.errorFromFrame($)));return;default:return}}let J=this.lateResponses.get(z);if(J&&($.header.ty===H.Response||$.header.ty===H.Error)){this.lateResponses.delete(z),J($);return}if($.header.ty===H.Goodbye&&Z){if(this.failHandle(Z,new F("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===H.Response||$.header.ty===H.Error||$.header.ty===H.StreamEnd)o6("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,z){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return z(),Z.onSettle?.(),!0}rejectPending($,Z,z){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(z)??z))}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8"));return new F(Z.message??"subc error",Z.code)}catch{return new F(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&V8(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[z,X]of this.pending)if(X.handle&&V8(X.handle,$))this.rejectPending(z,X,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,z]of this.pending)this.rejectPending(Z,z,$)}notSentCallError($,Z){return new S("not_sent",`${$}${j8(Z)}`,K8(Z),Z)}outcomeUnknownCallError($,Z){return new S("outcome_unknown",`${$}${j8(Z)}`,K8(Z),Z)}terminalCallError($,Z){if(Z instanceof S)return Z;return new S("terminal",`${$}${j8(Z)}`,K8(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof S)return Z;if(H8(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z){let z=B8($,Z,this.connectionToken);return this.liveRoutes.set($,z),z}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!h0($,this.connectionToken))throw new z0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new F("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(z),this.sock.close(),this.scheduleReconnectAfterDrop(z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new F("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function H8($){if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof S)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof y)return!0;if($ instanceof F||$ instanceof b)return!1;let Z=K8($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function J9($){return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function G9($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??X9,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??e6,livenessProbeWindowMs:$.livenessProbeWindowMs??$9,onControlPush:$.onControlPush}}function Z3($,Z,z){let X=z?`${z.module_id}\x00${z.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${X}`}function q1($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[z3],z=process.env[X3];if(!Z||!z)return;return{module_id:Z,launch_nonce:z}}function K8($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function j8($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function q8($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}import{Buffer as N1}from"node:buffer";var Q9=1e4,Y9=30000,G3=30000,W9=250,H1=64,L1="health.check",Q3=1n;class U8{available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new I("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class I extends Error{code;kind;constructor($,Z,z="terminal"){super($);this.code=Z,this.kind=z}}class g0{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=O0();nextCorr=1n;ingressEpochDropCount=0;requestGate=new U8(H1);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,Z,z,X){this.sock=$,this.currentConn=Z,this.opts=z,this.storage=X,this.closed=new Promise((J)=>{this.resolveClosed=J}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,z={}){this.assertLiveHandle($);let X=this.allocateCorr(),J=N8($,X),G=z.timeoutMs??G3,Q=E(H.Request,v(!1,z.priority??C.Interactive,!1,z.admissionClass??w.Normal),$.channel,$.epoch,X,Z);return await new Promise((Y,W)=>{let B=setTimeout(()=>{if(this.pending.delete(J))W(new I("reverse request timed out","request_timeout"))},G);this.pending.set(J,{resolve:(V)=>Y(V.body),reject:W,timer:B}),this.sendOn(this.sock,this.generation,Q).catch((V)=>{let j=this.pending.get(J);if(!j)return;this.pending.delete(J),clearTimeout(j.timer),W(V instanceof Error?V:new I(String(V)))})})}async push($,Z,z={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,E(H.Push,v(!1,z.priority??C.Interactive,!1,z.admissionClass??w.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,E(H.Cancel,e(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,E(H.Goodbye,e(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==p)throw new I(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${p}`,"invalid_manifest");let Z=q9($),z=await g0.openConnection(Z);return new g0(z.sock,z.conn,Z,z.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await K1($,E(H.Goodbye,e(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let z=await P0($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??Q9),J=z.endpoints[0],G=await H0.connect(J.host,J.port,X);try{Z?.(G),await v0(G,z,X),await K1(G,K9($));let Q=await D9(G,X);return{sock:G,conn:z,ack:Q}}catch(Q){throw G.close(),Q}}async readLoop($,Z){try{for(;;){let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:Y9});if(!await this.dispatch(z,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(z){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,z instanceof Error?z:new I(String(z)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,z){let X=null;if($.header.channel!==0){if(X=this.liveRoutes.get($.header.channel)??null,!X||X.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(X){let J=N8(X,$.header.corr),G=this.pending.get(J);if(G){if($.header.ty===H.Push||$.header.ty===H.StreamData)return!0;if($.header.ty===H.Response||$.header.ty===H.StreamEnd)return this.pending.delete(J),clearTimeout(G.timer),G.resolve($),!0;if($.header.ty===H.Error)return this.pending.delete(J),clearTimeout(G.timer),G.reject(B9($)),!0}}switch($.header.ty){case H.Ping:if($.header.channel===0)await this.sendOn(Z,z,a($.header.ver,H.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case H.Goodbye:if(!X)return!1;return this.liveRoutes.delete(X.channel),this.abortHandle(X),await this.opts.onRouteGone?.(X),!0;case H.Cancel:if(X)this.inflight.get(N8(X,$.header.corr))?.abort();return!0;case H.Request:if($.header.channel===0)await this.handleControlRequest($,Z,z);else if(X)this.handleDataRequest($,X,Z,z).catch((J)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider handler failed after its request was dispatched",J)});return!0;default:return!0}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[z,X]of this.inflight)if(z.startsWith(Z))X.abort();for(let[z,X]of this.pending){if(!z.startsWith(Z))continue;this.pending.delete(z),clearTimeout(X.timer),X.reject(new z0($))}}abortGeneration($){this.abortAllInflight();for(let[Z,z]of this.pending)this.pending.delete(Z),clearTimeout(z.timer),z.reject(new I("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,z){let X=P8($.body);if(X.op===L1){this.handleHealthRequest($,Z,z).catch((j)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider health handler failed after its request was dispatched",j)});return}if(X.op!=="route.bind")throw new I(`unsupported module control request ${X.op??"<missing op>"}`);let J=J3(X.route_channel,"route_channel"),G=J3(X.epoch,"epoch"),Q=this.liveRoutes.get(J);if(Q){if(G<=Q.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${G} does not supersede installed epoch ${Q.epoch} on channel ${J}`,e(),Z,z);return}this.liveRoutes.delete(Q.channel),this.abortHandle(Q),await this.opts.onRouteGone?.(Q)}let Y=B8(J,G,this.connectionToken),W={handle:Y,target:X.target,identity:X.identity,principal:X.principal,consumer_capabilities:X.consumer_capabilities},B;try{B=await this.opts.onBind?.(W)}catch(j){try{await this.sendError($,"route_rejected",j instanceof Error?j.message:String(j),e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}let V=P9(B);if(V){try{await this.sendError($,V.code,V.message,e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}try{await this.sendOn(Z,z,a($.header.ver,H.Response,e(),0,0,$.header.corr,D8({op:"route.bind"})))}catch(j){throw await this.opts.onRouteGone?.(Y),j}if(this.sock!==Z||this.generation!==z||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(Y);return}this.liveRoutes.set(Y.channel,Y),await this.opts.onBound?.(Y)}async handleDataRequest($,Z,z,X){let{corr:J,ver:G}=$.header,Q=N8(Z,J),Y=new AbortController;this.inflight.set(Q,Y);let W={handle:Z,signal:Y.signal,currentEpoch:()=>this.connectionEpoch,emit:async(j,q={})=>{if(this.assertLiveHandle(Z),Y.signal.aborted)return;await this.sendOn(z,X,a(G,H.StreamData,v(!1,q.priority??C.Interactive,!1,q.admissionClass??w.Normal),Z.channel,Z.epoch,J,j))}},B=await(this.requestGate??new U8(H1)).acquire(),V=v(!1,C.Interactive,!1);try{if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}let j=await this.opts.handler(Z,$.body,W);if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}if(this.assertLiveHandle(Z),j===void 0)await this.sendOn(z,X,a(G,H.StreamEnd,V,Z.channel,Z.epoch,J,new Uint8Array(0)));else if(j instanceof Uint8Array)await this.sendOn(z,X,a(G,H.Response,V,Z.channel,Z.epoch,J,j));else throw new I("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(j){if(j instanceof z0)return;if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}await this.sendError($,j instanceof I&&j.code?j.code:"handler_error",j instanceof Error?j.message:String(j),V,z,X)}finally{if(B(),this.inflight.get(Q)===Y)this.inflight.delete(Q)}}async handleHealthRequest($,Z,z){let{corr:X,ver:J}=$.header,G=`control:${z}:${X}`,Q=new AbortController;this.inflight.set(G,Q);let Y=await(this.requestGate??new U8(H1)).acquire();try{if(Q.signal.aborted)return;let W=await this.opts.health();await this.sendOn(Z,z,a(J,H.Response,e(),0,0,X,D8({op:L1,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError($,W instanceof I&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),e(),Z,z)}finally{if(Y(),this.inflight.get(G)===Q)this.inflight.delete(G)}}async sendError($,Z,z,X,J,G){if($.header.channel!==0){let Q=this.liveRoutes.get($.header.channel);if(!Q||Q.epoch!==$.header.epoch||!this.isLiveHandle(Q))return}await this.sendOn(J,G,a($.header.ver,H.Error,X,$.header.channel,$.header.epoch,$.header.corr,D8({code:Z,message:z})))}async sendOn($,Z,z){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await K1($,z)}handleUnexpectedDrop($,Z,z){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(z,this.generation,$)}scheduleReconnectAfterDrop($,Z,z){if(this.closeStarted)return;let X=this.reconnecting;if(X){if(!this.shouldSupersedeReconnect(X,Z,z))return;X.superseded=!0,X.socket?.close()}let J={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=J,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(J).catch((G)=>{if(this.isCurrentReconnect(J)&&!this.closeStarted)this.failFatal(G instanceof Error?G:new I(String(G)))}).finally(()=>{if(this.isCurrentReconnect(J))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new I("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let X=await g0.openConnection(this.opts,(G)=>{if(!this.isCurrentReconnect($)){G.close();return}$.socket=G});if(!this.isCurrentReconnect($)||this.closeStarted){if(X.sock.close(),this.closeStarted)throw new I("provider closed");return}let J=this.replaceConnection(X,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new I("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,J);return}catch(X){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw X;if(!L9(X))throw X;await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,z){return $.generation<Z||$.socketDied||$.socket===z}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){if(!this.opts.onConnectionState)return;let z=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(z===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((X)=>{if(z===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",X)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,z){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,reconnect:z}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let $=this.stateQueue[0];if(this.closeStarted||$.generation!==void 0&&$.generation!==this.generation||$.reconnect?.superseded){this.stateQueue.shift();continue}let{event:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(z){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",z),await U9();continue}console.warn("SubcProvider connection-state callback failed",z),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new I("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function N8($,Z){return`${$.channel}:${$.epoch}:${Z}`}function B9($){try{let Z=P8($.body);return new I(Z.message??"subc error",Z.code,Z.code==="stale_route_epoch"||Z.code==="unknown_channel"?"not_sent":"terminal")}catch{return new I(N1.from($.body).toString("utf8")||"subc error")}}function V9($){let Z=$.launchNonce??process.env[j9];return Z&&Z.length>0?Z:void 0}var j9="SUBC_LAUNCH_NONCE";function q9($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),restoredDebounceMs:$.restoredDebounceMs??W9,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function H9($){if($===null)return null;let Z=new Set($??[]);return Z.add(L1),[...Z]}function K9($){let Z=V9($);return E(H.Hello,e(),0,0,Q3,D8({manifest:O9($.manifest),protocol_ver:p,control_ops:H9($.controlOps),...Z?{launch_nonce:Z}:{}}))}function L9($){if($ instanceof I)return $.code==="duplicate_module_id";if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof y)return!0;if($ instanceof b)return!1;let Z=N9($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function N9($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function U9(){await new Promise(($)=>setTimeout($,0))}function e(){return v(!1,C.Passive,!1)}async function K1($,Z){await r($,t(Z),Date.now()+G3)}async function D9($,Z){let z=await $.readFrame(Z,Z);switch(z.header.ty){case H.HelloAck:{let X=P8(z.body);if(X.negotiated_ver!==p)throw new I(`subc negotiated protocol ${X.negotiated_ver}; expected exactly ${p}`,"unsupported_version");return X}case H.Error:{let X=P8(z.body);throw new I(`subc rejected HELLO: ${X.code??"unknown"} — ${X.message??"subc error"}`,X.code)}default:throw new I(`unexpected frame ${H[z.header.ty]} awaiting HELLO_ACK`)}}function D8($){return new Uint8Array(N1.from(JSON.stringify($),"utf8"))}function P8($){return JSON.parse(N1.from($).toString("utf8"))}function J3($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new I(`route.bind ${Z} must be an integer`);return $}function P9($){if($===void 0||$===!0)return null;if($===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if($.accept)return null;return{code:$.code??"route_rejected",message:$.message??"route.bind rejected by provider"}}function O9($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(M9),consumes:$.consumes.map(_9),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function M9($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function _9($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}var O8="subc-connection.json",A9="subc-",T9=".connection.json";function Y3(){let $=process.env.HOME;return $?p0($,".local","share","cortexkit","run",O8):void 0}function C9(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($)return p0($,O8);let Z=Y3();if(Z)return Z;return p0(R9().homedir,".local","share","cortexkit","run",O8)}function b9(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($){let X=p0($,O8);if(U1(X))return X}let Z=Y3();if(Z&&U1(Z))return Z;let z=S9(I9());return z.length===1?z[0]:void 0}function D1(){return b9()??C9()}function P1($){return $?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||D1()}function U1($){try{return F9($).isFile()}catch{return!1}}function S9($){let Z;try{Z=x9($)}catch{return[]}let z=[];for(let X of Z){if(typeof X!=="string")continue;if(!X.startsWith(A9)||!X.endsWith(T9))continue;let J=p0($,X);if(U1(J))z.push(J)}return z.sort(),z}import{createHash as k9}from"node:crypto";import{existsSync as w9,realpathSync as W3}from"node:fs";import{dirname as f9,relative as E9,resolve as y9}from"node:path";function B3($){let Z=$,z;try{z=W3(Z)}catch(X){if(X.code!=="ENOENT")throw X;let J=Z;while(!w9(J)){let G=f9(J);if(G===J)break;J=G}z=y9(W3(J),E9(J,Z))}return k9("sha256").update(z).digest("hex")}function O1($,Z){return{project_root:$,harness:"opencode",session:`store-${B3(Z)}`}}var V3=["transient","permanent","auth_required","context_overflow"];class _0 extends Error{code;action;["class"];constructor($,Z,z){super(`Claustrum credential request failed: ${$}`);this.code=$,this.action=z,this.name="ClaustrumCredentialError",this.class=Z}}function M0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j3($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function M($,Z="invalid_response",z=(X)=>console.warn(X)){let X=M0($)&&M0($.result)?$.result:void 0,J=X&&M0(X.error)?X.error:void 0,G=J?.class,Q=J?.code,Y=typeof G==="string"&&V3.includes(G),W=typeof Q==="string",V=Y&&W?G:"transient";if(typeof G!=="string")z("unknown");else if(!Y)z(G);return new _0(W?Q:Z,V,j3(V))}function L0($){return M0($)&&M0($.result)&&M0($.result.error)}var q3="claustrum",m9=60000;function u($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0?$:void 0}function X0($){return $===void 0||typeof $==="string"}function H3($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.payload;if(!Array.isArray(X)||X.length===0||!X.every((q)=>typeof q==="number"&&Number.isInteger(q)&&q>=0&&q<=255))throw M($,"invalid_response",Z);let J=_1(z?.record_version);if(J===void 0)throw M($,"invalid_record_version",Z);let G=z?.expires_at_ms,Q=G===void 0||G===null?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(Q===void 0)throw M($,"invalid_expiry",Z);let Y=z?.credential_id,W=z?.project_id,B=z?.account_id,V=z?.email,j=z?.org_name;if(!X0(Y)||!X0(W)||!X0(B)||!X0(V)||!X0(j))throw M($,"invalid_response",Z);return{material:new TextDecoder().decode(Uint8Array.from(X)),recordVersion:J,expiresAtMs:Q,credentialId:Y,projectId:W,accountId:B,email:V,orgName:j}}function g9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=_1(z?.record_version);if(typeof z?.ready!=="boolean"||z?.last_error_code!==void 0&&z?.last_error_code!==null&&typeof z?.last_error_code!=="string"||typeof z?.lease_held!=="boolean"||X===void 0||z?.stale_pending!==void 0&&typeof z.stale_pending!=="boolean")throw M($,"invalid_status",Z);return{ready:z.ready,lastErrorCode:z.last_error_code??null,leaseHeld:z.lease_held,recordVersion:X,...z.stale_pending===void 0?{}:{stalePending:z.stale_pending}}}class M8{#z;#J;#B;#Y;#G;#$;#X=null;#Q=0;#W=!1;constructor($,Z,z,X,J,G){this.#z=$,this.#J=Z,this.#B=z,this.#Y=X,this.#G=J,this.#$=G}static async connect($={}){let Z=P1($.connectionFile),z=$.connector??((G)=>K0.connect(G)),X=$.identity??O1($.projectRoot??process.cwd(),$.storagePath??process.cwd()),J=await z({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new M8(J,z,Z,$.handshakeTimeoutMs,X,$.logger??((G)=>console.warn(G)))}async getCredential($,Z){let z=await this.#Z("credential.get",{handle:$,min_ttl_ms:Z,force_refresh:!1});return H3(z,this.#$)}async statusCredential($){let Z=await this.#Z("credential.status",{handle:$});return g9(Z,this.#$)}async reportAuthFailure($){let Z=await this.#Z("credential.report_auth_failure",{handle:$.handle,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async listScoped($){let Z=await this.#Z("credential.list_scoped",$===void 0?{}:{enrollment_token:$});return p9(Z,this.#$)}async getScoped($){let Z=await this.#Z("credential.get_scoped",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,min_ttl_ms:$.minTtlMs});return H3(Z,this.#$)}async reportAuthFailureScoped($){let Z=await this.#Z("credential.report_auth_failure",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async enrollPropose($){let Z=await this.#Z("auth.enroll_propose",{proposed_name:$.name,request_secret_hash:$.requestSecretHash}),X=M1(Z,this.#$).request_id;if(typeof X!=="string"||X.length===0)throw M(Z,"invalid_response",this.#$);return{requestId:X}}async enrollPoll($){let Z=await this.#Z("auth.enroll_poll",{request_id:$.requestId,request_secret:$.requestSecret});return u9(Z,this.#$)}async enrollRotate($){let Z=await this.#Z("auth.enroll_rotate",{token:$.token,expected_token_generation:$.expectedTokenGeneration}),z=M1(Z,this.#$),X=z.token,J=z.token_generation;if(typeof X!=="string"||X.length===0||typeof J!=="number")throw M(Z,"invalid_response",this.#$);return{token:X,tokenGeneration:J}}close(){this.#W=!0,this.#z.close()}async#Z($,Z){try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(z){if(this.#j(z)){try{await this.#q()}catch(X){throw this.#V(X)}try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(X){throw this.#V(X)}}throw this.#V(z)}}#V($){if($ instanceof _0)return $;let Z=$ instanceof S&&$.code?$.code:"transport_error";return new _0(Z,"transient","retry")}#j($){return!this.#W&&$ instanceof S&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#q(){if(this.#W)throw Error("Claustrum client is closed");if(this.#X){await this.#X;return}let $=Date.now();if($<this.#Q)throw Error("Claustrum client reconnect is backed off");this.#Q=$+m9,this.#X=this.#J({connectionFile:this.#B,handshakeTimeoutMs:this.#Y}).then((Z)=>{if(this.#W)throw Z.close(),Error("Claustrum client is closed");let z=this.#z;this.#z=Z,z.close()}).finally(()=>{this.#X=null}),await this.#X}}function p9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.credentials;if(!Array.isArray(X))throw M($,"invalid_response",Z);let J=z?.view;if(typeof J!=="string"||J.length===0)throw M($,"invalid_response",Z);return{rows:X.map((Q)=>{if(!u(Q))throw M($,"invalid_response",Z);let Y=_1(Q.record_version);if(Y===void 0)throw M($,"invalid_record_version",Z);let W=(V)=>{if(!Array.isArray(V)||!V.every((j)=>typeof j==="string"))throw M($,"invalid_response",Z);return V};if(typeof Q.id!=="string"||typeof Q.type!=="string"||typeof Q.state!=="string")throw M($,"invalid_response",Z);let B=Q.created_at_ms===void 0||Q.created_at_ms===null?null:typeof Q.created_at_ms==="number"&&Number.isFinite(Q.created_at_ms)?Q.created_at_ms:void 0;if(B===void 0)throw M($,"invalid_response",Z);if(!X0(Q.refresh_adapter))throw M($,"invalid_response",Z);if(!X0(Q.account_id)||!X0(Q.email)||!X0(Q.org_name))throw M($,"invalid_response",Z);return{id:Q.id,categories:W(Q.categories),credentialType:Q.type,serves:W(Q.serves),state:Q.state,refreshAdapter:Q.refresh_adapter,recordVersion:Y,operations:W(Q.operations),createdAtMs:B,accountId:Q.account_id,email:Q.email,orgName:Q.org_name}}),view:J}}function M1($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0;if(z===void 0)throw M($,"invalid_response",Z);return z}function u9($,Z){let z=M1($,Z),X=z.status;if(X==="pending")return{status:"pending"};if(X==="denied")return{status:"denied"};if(X!=="approved")throw M($,"invalid_response",Z);let{name:J,token:G,token_generation:Q}=z;if(typeof J!=="string"||typeof G!=="string"||G.length===0||typeof Q!=="number"||!Number.isInteger(Q))throw M($,"invalid_response",Z);return{status:"approved",name:J,token:G,tokenGeneration:Q}}l8();var VZ=d("quota");var K3={name:"@cortexkit/pi-openai-auth",version:"0.11.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/openai-auth-core":"workspace:*"},peerDependencies:{"@earendil-works/pi-ai":">=0.80.10","@earendil-works/pi-coding-agent":">=0.80.10","@earendil-works/pi-tui":">=0.80.10"}};import{homedir as i9}from"node:os";import{join as L3}from"node:path";function c9(){return process.env.PI_AGENT_DIR?.trim()||L3(i9(),".pi","agent")}function N3(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||L3(c9(),n0)}function s9($=N3()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||g8($)}function U3($=N3()){return{configPath:$,statePath:s9($)}}var D3=new Map;function P3($){return D3.get($)}function O3($){return D3.delete($)}var n9={auth:{set:async()=>{}}};async function a9($,Z){let z=(Z.accountPaths??U3)(),X=Z.loadAccounts??B$,J=await X(z),G=new n({storage:null,configPath:z.configPath,fetchImpl:Z.fetchImpl,now:Z.now});return G.seedFallbacksFromAccounts((J?.accounts??[]).filter(m8)),{accountStoragePath:z.configPath,accountStatePath:z.statePath,packageVersion:Z.packageVersion??K3.version,quotaManager:G,loadAccounts:X,client:n9,sessionId:$.sessionManager.getSessionId(),notify:(Q)=>$.ui.notify(Q.text),clearStickyRouting:async(Q)=>O3(Q),getStickyRouting:async(Q)=>P3(Q),fetchImpl:Z.fetchImpl,now:Z.now,randomUUID:Z.randomUUID,beginAccountLogin:Z.beginAccountLogin}}async function t9($,Z,z,X={}){return z1($,Z,await a9(z,X))}async function x1($,Z,z,X){let J=await t9($,Z,z,X);z.ui.notify(J.text)}function M3($,Z={}){$.registerCommand(X8,{description:"List, add, remove, or reorder OpenAI fallback accounts",handler:(z,X)=>x1(X8,z,X,Z)}),$.registerCommand(z8,{description:"Show persisted OpenAI quota for fallback accounts",handler:(z,X)=>x1(z8,z,X,Z)}),$.registerCommand(J8,{description:"Show or change OpenAI account routing mode",handler:(z,X)=>x1(J8,z,X,Z)})}import{connect as o9}from"node:net";import{connect as r9}from"node:tls";var e9="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_3=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class F1{url;readyState=0;socket;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,Z){this.url=$,this.connect($,Z)}addEventListener($,Z,z){this.listeners[$]?.add(Z)}removeEventListener($,Z){this.listeners[$]?.delete(Z)}emit($,Z){for(let z of[...this.listeners[$]??[]])try{z(Z)}catch{}}async connect($,Z){let z=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),X=z.hostname,J=z.port?Number(z.port):z.protocol==="https:"?443:80,G=`${z.pathname}${z.search}`,Q=crypto.getRandomValues(new Uint8Array(16)),Y=Buffer.from(Q).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Y+e9));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[q,K]of Object.entries(Z))B[q.toLowerCase()]=K;let V=[`GET ${G} HTTP/1.1`,`Host: ${X}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Y}`];for(let q of _3)if(B[q]!==void 0)V.push(`${$2(q)}: ${B[q]}`);for(let[q,K]of Object.entries(Z))if(!_3.includes(q.toLowerCase())&&q.toLowerCase()!=="content-length")V.push(`${q}: ${K}`);let j=`${V.join(`\r
112
+ The account is added when you finish.`,Q=z.completion.then(async(Y)=>{let B=await $.mainIdentity?.();if(Y.accountId&&B&&Y.accountId===B)throw $6.warn("account add rejected (main identity)",{id:Y.id}),new j0("main-account",q5);return $6.info("account added",{id:Y.id}),P5(Y)});return{status:"pending",message:G,completion:Q}}}}function J4($){return{id:"session",title:"This session",build:async(Z)=>{let X=Z.sessionId;if(!X)return{lines:["No current session"]};let J=await $.getPin?.(X);return{lines:[J?`Pinned to ${J}`:"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),$6.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 z4($){let{vault:Z}=$;return{id:"vault",title:"Vault",build:async()=>{let X=await Z.status(),J=await Z.authority()!=="local",z=Z.routes().length;return{lines:[J?`Connected · ${X.accounts.length} account${X.accounts.length===1?"":"s"}`:X.enrollment.state==="idle"?"Not connected":`Enrollment ${X.enrollment.state}`,Q5(X.host,X.name,X.enrollment),...E3(X.name,X.enrollment),...J?[X.accounts.length===0?"The vault serves no OpenAI account to this host yet.":`The vault serves ${X.accounts.length} OpenAI account${X.accounts.length===1?"":"s"}; ${z} can route now.`]:[],...J&&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."]:[],...X.lastError?[`Last error: ${X.lastError}`]:[]],items:X.accounts.map((G)=>({id:G.routeId,label:F1(G),group:"Accounts",status:G.enabled?G.state:"disabled",detail:[G.credentialType==="api_key"?"API key":"login",G.state==="active"?"active":`vault state ${G.state}`,G.enabled?"enabled":"disabled here"].join(", "),actions:[G.enabled?{id:"disable",label:"Disable on this host",description:"It stays in the vault and in this list, and is never sent from this host until enabled again.",run:async()=>{return await Z.decline(G.routeId),await $.changed?.(),`${F1(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await Z.accept(G.routeId),await $.changed?.(),`${F1(G)} is enabled on this host.`}}]})),actions:J?[{id:"disconnect",label:"Disconnect",description:"Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",confirm:"Disconnect from the vault? Connecting again needs a new approval with `ck`.",run:async()=>{return await Z.disconnect(),await $.changed?.(),`Disconnected: ${Z.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${Z.name}\` to revoke it in the vault too.`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:G})=>{let Q=await Z.connectStep();if(Q.state!=="pending"&&Q.state!=="busy")return await $.changed?.(),n2(Z,Q);return Z.waitForApproval($.wait).then(async(Y)=>{await $.changed?.();let B=n2(Z,Y);G.notify(B.text,B.ok?"info":"warning")}).catch((Y)=>{G.notify(`Connecting to the vault failed: ${Y instanceof Error?Y.message:String(Y)}`,"error")}),{ok:!0,text:[...E3(Z.name,Q),"Waiting for the approval; you are told here when it lands."].join(`
113
+ `)}}}]}}}}var _5=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],C5=["primary","secondary"];function G4($){let Z={command:P1,title:X4,store:e2(M5(L5($.store,{...$.rowLocks?{rowLocks:$.rowLocks}:{}}))),...$.extraLocks?{extraLocks:$.extraLocks}:{},accounts:{...$.login?{login:O5($.login)}:{},...$.protect?{protect:$.protect}:{},...$.describeIdentity?{describeIdentity:$.describeIdentity}:{}},quota:$.quotaCheck?{check:$.quotaCheck}:{},routing:{orderedVariants:_5,formerMainId:q$},limits:{labels:C5},...$.cache?{cache:$.cache}:{},...$.diagnostics?{diagnostics:$.diagnostics}:{},...$.extras?{extras:$.extras}:{},...$.logger?{logger:$.logger}:{},...$.now?{now:$.now}:{}},X=$.vault?j5(Z,$.vault):R1(Z),J=(z)=>{let{sessionId:G}=z,Q=z.notify.bind(z);return{...G!==void 0?{sessionId:G}:{},notify:Q}};return{command:P1,async open(z){let G=J(z),Q=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(Q&&!Q.migrated)return{command:P1,menu:Z4(Q.blockers)};return X.open(G)},async apply(z,G){let Q=J(G),Y=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(Y&&!Y.migrated)return{command:P1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:Z4(Y.blockers)};let B=await X.apply(z,Q);if(B.ok)await $.afterApply?.();return B}}}var pN=s("quota");function Z6($,Z){let X=Z?$.split(Z).join("[credential]"):$;return e9(X).replaceAll("***REDACTED***","[credential]")}var T5={name:"@cortexkit/pi-openai-auth",version:"1.0.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/claustrum-client":"^0.6.2","@cortexkit/common-auth":"^0.14.2","@cortexkit/openai-auth-core":"workspace:*"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};var K$=new Map;function A5($){return K$.get($)?.accountId}function R5($){return K$.delete($)}function S5($){let Z=K$.get($.sessionId),X=new Set($.validPinnedAccountIds);if(Z&&!$.excludeAccountIds.includes(Z.accountId)&&L$(Z,X,$.wireAccountIdByAccount[Z.accountId])){if($.persist){let Q=$.quotaCheckedAtByAccount[Z.accountId];K$.set($.sessionId,{accountId:Z.accountId,inputBytes:$.requestBytes,...Z.wireIdentity!==void 0?{wireIdentity:Z.wireIdentity}:{},...Q!==void 0?{quotaCheckedAt:Q}:{}})}return{accountId:Z.accountId}}let J=new Map(Object.entries($.quotaCheckedAtByAccount)),z=a3(K$,J,$.sessionId),G=$.select(z);if(!G)return;if($.persist){let Q=$.wireAccountIdByAccount[G.accountId];K$.set($.sessionId,{accountId:G.accountId,inputBytes:$.requestBytes,...Q!==void 0?{wireIdentity:Q}:{},...G.quotaCheckedAt!==void 0?{quotaCheckedAt:G.quotaCheckedAt}:{}})}return{accountId:G.accountId}}import{join as w5}from"node:path";import{createHash as JB}from"node:crypto";import{constants as E5}from"node:fs";import{lstat as g5,mkdir as k5,open as h5,unlink as zB}from"node:fs/promises";import{dirname as g3,resolve as f5}from"node:path";import{setTimeout as GB}from"node:timers/promises";import{rmdirSync as oY,statSync as tY}from"node:fs";import{mkdir as eY,rmdir as $B,stat as v3,utimes as x5}from"node:fs/promises";var ZB=30000,y3=1e4,XB=3000,Q4,X6=new Map;process.once("exit",()=>{for(let[$,Z]of X6)try{if(Z.renewedAt+y3<Date.now())continue;let X=tY($);if(Y4(X,Z)&&X.mtime.getTime()===Z.mtime)oY($)}catch{}});function Y4($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function J6($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function I5(){return Object.assign(Error("Pi auth lock held"),{code:"ELOCKED"})}async function B4($){try{await $B($)}catch(Z){if(J6(Z)!=="ENOENT")throw Z}}async function W4($,Z){try{await eY($)}catch(X){if(J6(X)!=="EEXIST")throw X;if(Z<=0)throw I5();let J;try{J=(await v3($)).mtime.getTime()}catch(z){if(J6(z)==="ENOENT")return W4($,0);throw z}if(!(J<Date.now()-Z))throw I5();return await B4($),W4($,0)}try{if(!Q4){let z=new Date(Math.ceil(Date.now()/1000)*1000+5);await x5($,z,z)}let X=await v3($),J=X.mtime.getTime();return Q4??=J%1000===0?"s":"ms",{dev:X.dev,ino:X.ino,mtime:J}}catch(X){throw await B4($).catch(()=>{}),X}}async function b5($,Z,X){let J=`${$}.lock`,z=await W4(J,ZB),G=z.mtime,Q=Date.now(),Y=!1,B;X6.set(J,{...z,renewedAt:Q});function H(){if(Y=!0,B)clearTimeout(B);X6.delete(J),Z()}function W(){if(!Y&&Q+y3<Date.now())H()}function V(U=XB){if(Y)return;B=setTimeout(()=>{q()},U),B.unref()}function j(U){if(Y)return;if(J6(U)==="ENOENT"||Q+y3<Date.now())H();else V(1000)}async function q(){if(W(),Y)return;let U;try{U=await v3(J)}catch(N){j(N);return}if(W(),Y)return;if(!Y4(U,z)||U.mtime.getTime()!==G){H();return}let L=new Date(Q4==="s"?Math.ceil(Date.now()/1000)*1000:Date.now());try{await x5(J,L,L)}catch(N){j(N);return}if(Y)return;G=L.getTime(),Q=Date.now(),X6.set(J,{...z,mtime:G,renewedAt:Q}),V()}return X?.(async()=>{if(B)clearTimeout(B);await q()}),V(),{assertFresh:W,async release(){if(Y)return;if(Y=!0,B)clearTimeout(B);X6.delete(J);let U=()=>Q+y3<Date.now();if(U()){H();return}let L;try{L=await v3(J)}catch(N){if(J6(N)!=="ENOENT")throw N;H();return}if(U()||!Y4(L,z)||G!==L.mtime.getTime()){H();return}await B4(J)}}}class a extends Error{code;constructor($){super(`Pi slot: ${$}`);this.code=$,this.name="PiSlotError"}}function QB($){let Z=$.indexOf("{")+1,X={offset:Z-1,children:[]},J=()=>{while(/\s/.test($[Z]??"")&&Z<$.length)Z++},z=()=>{Z++;while(Z<$.length){if($[Z++]==='"')return;if($[Z-1]==="\\")Z++}};J();while($[Z]!=="}"){let G=Z;z();let Q=JSON.parse($.slice(G,Z));J(),Z++,J();let Y=Z,B=0;while(Z<$.length){let W=$[Z];if(W==='"'){z();continue}if(W==="{"||W==="[")B++;if(W==="}"||W==="]"){if(B===0)break;B--}if(W===","&&B===0)break;Z++}let H=Z;while(/\s/.test($[H-1]??""))H--;if(X.children.push({key:Q,offset:G,length:H-G,value:{offset:Y,length:H-Y}}),J(),$[Z]==="}")break;Z++,J()}return X}function z6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V4($){if(Array.isArray($))return`[${$.map(V4).join(",")}]`;if(z6($))return`{${Object.keys($).sort().map((Z)=>`${JSON.stringify(Z)}:${V4($[Z])}`).join(",")}}`;return JSON.stringify($)}function d0($){return JB("sha256").update(V4($)).digest("hex")}function h3($){return z6($)?$.code:void 0}async function y5($,Z=!1,X){let J;try{J=await h5($,E5.O_RDONLY|E5.O_NOFOLLOW);let z=await J.stat();if(!z.isFile()||Z&&(z.mode&511)!==384)throw new a("unsafe-path");await X?.($);let G=await g5($);if(!G.isFile()||G.dev!==z.dev||G.ino!==z.ino)throw new a("unsafe-path");let Q=await J.readFile(),Y=Q.toString("utf8");if(!Q.equals(Buffer.from(Y)))throw new a(Z?"invalid-stash":"invalid-auth");return Y}catch(z){if(h3(z)==="ENOENT"&&!J)return;if(h3(z)==="ELOOP"||h3(z)==="ENOENT")throw new a("unsafe-path");throw z}finally{await J?.close()}}function YB($,Z){try{let X=JSON.parse($);if(!z6(X))throw Error();let J=QB($),z=J.children,G=z.map((B)=>B.key);if(new Set(G).size!==G.length)throw Error();let Q=z.find((B)=>B.key===Z),Y=Q?X[Z]:null;if(Y!==null&&!z6(Y))throw Error();if(Q&&Y===null)throw Error();return{text:$,root:J,property:Q,entry:Y}}catch{throw new a("invalid-auth")}}function BB($){let Z=$.property?.value;return Z?$.text.slice(Z.offset,Z.offset+Z.length):null}function v5($,Z,X){let{text:J,root:z,property:G}=$,Q=z.children??[];if(G){let H=G.value;if(!H)throw new a("invalid-auth");if(X!==null)return J.slice(0,H.offset)+X+J.slice(H.offset+H.length);let W=Q.indexOf(G),V=Q[W-1],j=Q[W+1],q=V?V.offset+V.length:G.offset,U=!V&&j?j.offset:G.offset+G.length;return J.slice(0,q)+J.slice(U)}if(X===null)return J;let Y=Q.at(-1),B=Y?Y.offset+Y.length:z.offset+1;return`${J.slice(0,B)}${Y?",":""}${JSON.stringify(Z)}:${X}${J.slice(B)}`}async function WB($){let Z=await h5($,"r");try{await Z.sync()}finally{await Z.close()}}async function H4($,Z,X,J){await P0($,null,{serialize:()=>Z,durable:!0,beforeRename:async()=>{await J?.($),X()}})}function j4($){return HB($)}function HB($,Z,X){let{provider:J,placeholderKey:z}=$,G=$.lockTimeoutMs??30000;if(!J||!$.authPath||!$.stashPath||!z||z.startsWith("!")||z.includes("$")||!Number.isFinite(G)||G<0)throw new a("invalid-options");let Q=f5($.authPath),Y=f5($.stashPath);if(Q===Y||Y===`${Q}.lock`)throw new a("invalid-options");let B=d0(Q),H=d0(z),W={type:"api_key",key:z},V=(N)=>d0(N)===d0(W);async function j(){let N=await y5(Y,!0,X?.afterReadCheck);if(N===void 0)return;try{let K=JSON.parse(N);if(K.version!==1||K.provider!==J||K.authIdentity!==B||K.placeholderIdentity!==H||K.entry!==null&&!z6(K.entry)||K.sha256!==d0(K.entry)||(K.entry===null?K.entryJson!==null:typeof K.entryJson!=="string"||d0(JSON.parse(K.entryJson))!==K.sha256))throw Error();return K}catch{throw new a("invalid-stash")}}async function q(N){let K,F,C=!1,M=()=>{if(F?.(),C)throw new a("lock-compromised")};try{await k5(g3(Q),{recursive:!0,mode:448});let D=Date.now()+G,P=0;while(!K)try{let f=await b5(Q,()=>{C=!0},X?.onRenew);K=f.release,F=f.assertFresh}catch(f){if(h3(f)!=="ELOCKED")throw f;let n=D-Date.now();if(n<=0)throw new a("lock-timeout");await GB(Math.min(Math.round(Math.min(10*2**P++,1000)*(1+Math.random())),n))}M();let S=await N(M);return M(),S}catch(D){if(D instanceof a)throw D;throw new a("io")}finally{await K?.().catch(()=>{}),M()}}async function U(){let N=YB(await y5(Q,!1,X?.afterReadCheck)??"{}",J),K=await j();return{auth:N,stash:K}}async function L(N){N(),await zB(Y),await WB(g3(Y)),Z?.("stash-deleted")}return{inspect:()=>q(async()=>{let{auth:N,stash:K}=await U();return{slot:V(N.entry)?"placeholder":N.entry===null?"empty":!K||d0(N.entry)===K.sha256?"original":"foreign",stash:K?"valid":"missing"}}),enterVault:()=>q(async(N)=>{let{auth:K,stash:F}=await U();if(V(K.entry)){if(!F)throw new a("missing-stash");return}if(F&&d0(K.entry)!==F.sha256)throw new a("conflict");if(!F){await k5(g3(Y),{recursive:!0,mode:448});let C=await g5(g3(Y));if(!C.isDirectory()||(C.mode&511)!==448)throw new a("unsafe-path");let M={version:1,provider:J,authIdentity:B,placeholderIdentity:H,entry:K.entry,entryJson:BB(K),sha256:d0(K.entry)};await H4(Y,JSON.stringify(M),N,X?.beforeRename),Z?.("stash-written")}await H4(Q,v5(K,J,JSON.stringify(W)),N,X?.beforeRename),Z?.("auth-written")}),exitVault:()=>q(async(N)=>{let{auth:K,stash:F}=await U();if(!F){if(V(K.entry))throw new a("missing-stash");return"nothing-to-do"}if(V(K.entry))await H4(Q,v5(K,J,F.entryJson),N,X?.beforeRename),Z?.("auth-written");else if(d0(K.entry)!==F.sha256)return"conflict";return await L(N),"restored"})}}import{getAgentDir as VB}from"@earendil-works/pi-coding-agent";var G6="openai-auth-vault-mode-not-a-credential",m5="Request refused locally: Pi has not loaded the credential vault placeholder. Reopen the session or disconnect Pi from the vault in /openai; local credentials are not used while connected.",p5="A Pi login was added while connected to the vault. Both that login and the stashed original are kept; neither was overwritten.";function u5($){return j4({authPath:w5(VB(),"auth.json"),provider:"openai-codex",stashPath:w5(x3($),"pi-openai-codex-login.json"),placeholderKey:G6})}function jB($){return{id:"pi-login",title:"Pi login",build:()=>{let Z=$(),X=Date.now(),J=c({limits:["primary","secondary"].flatMap((G)=>{let Q=Z?.[G];return Q?[{...Q,kind:"reading",scope:"all",label:G,checkedAt:Q.checkedAt??X}]:[]}),...Z?.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:X}}:{}}),z=p1(J,{now:X});return{lines:["Managed by Pi /login",...z.length>0?z:[T0(J,{now:X})]]}}}}function UB($,Z={}){let X=Z.beginAccountLogin??QZ,J=Z.packageVersion??T5.version,z=z4({vault:$.vault,changed:Z.afterApply,...Z.vaultWait?{wait:Z.vaultWait}:{}}),G=G4({store:$.store(),vault:$.vault,login:{begin:(Q)=>X({...Q,version:J}),mainIdentity:async()=>$.mainIdentity()},quotaCheck:async(Q)=>{if(Q.length===1){let B=$.store();for(let H of Q)await B.requestReading(H);await B.pullsSettled();return}let Y=(await $.refreshAllQuota()).filter((B)=>!B.ok);if(Y.length>0)throw new j0("quota-check-failed",Y.map((B)=>`${B.account}: ${B.error??"quota check failed"}`).join(`
114
+ `))},extras:[jB(()=>$.mainQuota()),J4({getPin:async(Q)=>A5(Q),clearPin:async(Q)=>R5(Q)}),{...z,build:async(Q)=>{let Y=await z.build(Q),B={id:"disconnect",label:"Disconnect",confirm:"Disconnect this Pi host from the vault and restore its original login?",run:async()=>{let W;try{W=await $.disconnectVault?.()}catch{let V=!1;try{await Z.afterApply?.()}catch{V=!0}let j=await $.readAuthority();throw new j0("vault-disconnect-failed",[j==="local"?"Disconnect did not finish cleanly; local accounts are active. Retry Disconnect if Pi login restoration did not complete.":"Disconnect failed; Pi is still enrolled or enrollment is unreadable. Local accounts remain disabled; retry Disconnect to restore the login.",...V?["Pi could not reload its auth snapshot; reopen the session."]:[]].join(`
115
+ `))}return await Z.afterApply?.(),[`Disconnected: ${$.vault.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${$.vault.name}\` to revoke it in the vault too.`,...W==="conflict"?[p5]:[]].join(`
116
+ `)}},H=Y.actions??[];return{...Y,actions:[...H.map((W)=>W.id==="disconnect"&&$.disconnectVault?{...W,run:B.run}:W),...$.vaultMode()&&$.disconnectVault&&!H.some((W)=>W.id==="disconnect")?[B]:[]]}}}],afterApply:async()=>{return await Z.afterApply?.(),$.reload()}});return{command:G.command,open:async(Q)=>{return await $.readAuthority(),G.open(Q)},apply:async(Q,Y)=>{return await $.readAuthority(),G.apply(Q,Y)}}}async function qB($,Z){let X=Z.pool;if(!X){$.ui.notify("The OpenAI account pool is not available.","error");return}if(Z.onContext?.($),Z.afterApply)await Z.afterApply();else await X.syncVaultSlot?.(()=>$.modelRegistry.refresh(),!0);if(!X.vaultMode())try{await X.observeLogin(await $.modelRegistry?.getApiKeyForProvider("openai-codex"))}catch{}await k8(UB(X,Z),$.ui,{sessionId:$.sessionManager.getSessionId()})}function l5($,Z={}){$.registerCommand(P1,{description:"OpenAI accounts: add and manage accounts, quota, routing and limits",handler:(X,J)=>qB(J,Z)})}import{connect as KB}from"node:net";import{connect as DB}from"node:tls";var NB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",d5=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class U4{url;readyState=0;socket;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,Z){this.url=$,this.connect($,Z)}addEventListener($,Z,X){this.listeners[$]?.add(Z)}removeEventListener($,Z){this.listeners[$]?.delete(Z)}emit($,Z){for(let X of[...this.listeners[$]??[]])try{X(Z)}catch{}}async connect($,Z){let X=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),J=X.hostname,z=X.port?Number(X.port):X.protocol==="https:"?443:80,G=`${X.pathname}${X.search}`,Q=crypto.getRandomValues(new Uint8Array(16)),Y=Buffer.from(Q).toString("base64"),B=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Y+NB));this.expectedAccept=Buffer.from(new Uint8Array(B)).toString("base64");let H={};for(let[j,q]of Object.entries(Z))H[j.toLowerCase()]=q;let W=[`GET ${G} HTTP/1.1`,`Host: ${J}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Y}`];for(let j of d5)if(H[j]!==void 0)W.push(`${MB(j)}: ${H[j]}`);for(let[j,q]of Object.entries(Z))if(!d5.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")W.push(`${j}: ${q}`);let V=`${W.join(`\r
211
117
  `)}\r
212
118
  \r
213
- `;try{this.log("connect_start",{host:X,port:J,tls:z.protocol==="https:"});let q=()=>{this.socket?.write(j)},K=z.protocol==="https:"?r9({host:X,port:J,servername:X},q):o9({host:X,port:J},q);this.socket=K,K.on("data",(L)=>{this.onData(typeof L==="string"?Buffer.from(L,"binary"):L)}),K.on("error",(L)=>{this.readyState=3;let U=L instanceof Error?L.message:String(L);this.log("socket_error",{message:U}),this.emit("error",{message:U})}),K.on("close",(L)=>{this.readyState=3,this.log("socket_close",{hadError:L}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(q){this.readyState=3,this.log("connect_exception",{message:q instanceof Error?q.message:String(q)}),this.emit("error",{message:q instanceof Error?q.message:String(q)})}}onData($){if(this.rxBuffer=Z2(this.rxBuffer,$),!this.handshakeDone){let Z=Buffer.from(this.rxBuffer).toString("latin1"),z=Z.indexOf(`\r
119
+ `;try{this.log("connect_start",{host:J,port:z,tls:X.protocol==="https:"});let j=()=>{this.socket?.write(V)},q=X.protocol==="https:"?DB({host:J,port:z,servername:J},j):KB({host:J,port:z},j);this.socket=q,q.on("data",(U)=>{this.onData(typeof U==="string"?Buffer.from(U,"binary"):U)}),q.on("error",(U)=>{this.readyState=3;let L=U instanceof Error?U.message:String(U);this.log("socket_error",{message:L}),this.emit("error",{message:L})}),q.on("close",(U)=>{this.readyState=3,this.log("socket_close",{hadError:U}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(j){this.readyState=3,this.log("connect_exception",{message:j instanceof Error?j.message:String(j)}),this.emit("error",{message:j instanceof Error?j.message:String(j)})}}onData($){if(this.rxBuffer=LB(this.rxBuffer,$),!this.handshakeDone){let Z=Buffer.from(this.rxBuffer).toString("latin1"),X=Z.indexOf(`\r
214
120
  \r
215
- `);if(z===-1)return;let X=Z.slice(0,z),J=X.split(`\r
216
- `)[0]??"",G=X.match(/sec-websocket-accept:\s*(\S+)/i);if(!J.includes(" 101")){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:J}),this.emit("error",{message:`WS upgrade failed: ${J}`});return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:J}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(z+4),this.log("open",{statusLine:J}),this.emit("open",{})}this.drainFrames()}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let Z=$[0],z=$[1],X=(Z&128)!==0,J=Z&15,G=(z&128)!==0,Q=z&127,Y=2;if(Q===126){if($.length<4)return;Q=$[2]<<8|$[3],Y=4}else if(Q===127){if($.length<10)return;Q=0;for(let B=0;B<8;B++)Q=Q*256+$[2+B];Y=10}if(G)Y+=4;if($.length<Y+Q)return;let W=$.slice(Y,Y+Q);this.rxBuffer=$.slice(Y+Q),this.handleFrame(X,J,W)}}handleFrame($,Z,z){if(Z===9){this.writeFrame(10,z);return}if(Z===10)return;if(Z===8){let J=1005,G="";if(z.length>=2)J=z[0]<<8|z[1],G=Buffer.from(z.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:J,reason:G});return}if(Z===1||Z===2)this.fragOpcode=Z,this.fragChunks=[z];else if(Z===0)this.fragChunks.push(z);if(!$)return;let X=z2(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let J=Buffer.from(X).toString("utf-8");this.emit("message",{data:J})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,Z){let z=Z.length,X=crypto.getRandomValues(new Uint8Array(4)),J;if(z<126)J=[128|$,128|z];else if(z<65536)J=[128|$,254,z>>8&255,z&255];else{J=[128|$,255];for(let Y=7;Y>=0;Y--)J.push(z/2**(8*Y)&255)}let G=new Uint8Array(z);for(let Y=0;Y<z;Y++)G[Y]=Z[Y]^X[Y%4];let Q=new Uint8Array(J.length+4+z);Q.set(J,0),Q.set(X,J.length),Q.set(G,J.length+4);try{this.socket?.write(Q)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log($,Z){return Promise.resolve()}}function $2($){return $}function Z2($,Z){let z=new Uint8Array($.length+Z.length);return z.set($,0),z.set(Z,$.length),z}function z2($){let Z=0;for(let J of $)Z+=J.length;let z=new Uint8Array(Z),X=0;for(let J of $)z.set(J,X),X+=J.length;return z}var l0="https://chatgpt.com/backend-api";class R1 extends F1{constructor($,Z){let z=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),z)}}var u0=0,I1;function G2(){let $=globalThis;if(u0===0)I1=$.WebSocket,$.WebSocket=R1;return u0++,()=>{if(u0=Math.max(0,u0-1),u0===0){if($.WebSocket===R1)$.WebSocket=I1;I1=void 0}}}var Q2=[{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:l0,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:5,output:30,cacheRead:0.5,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4",name:"GPT-5.4",api:"openai-codex-responses",provider:"openai-codex",baseUrl:l0,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:0.25,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-codex-responses",provider:"openai-codex",baseUrl:l0,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:0.75,output:4.5,cacheRead:0.075,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"openai-codex-responses",provider:"openai-codex",baseUrl:l0,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:128000}];function Y2($,Z,z){let X=X2(),J=G2(),G;try{G=J2($,Z,z)}catch(Q){throw J(),Q}return(async()=>{try{for await(let Q of G)X.push(Q);X.end()}catch(Q){X.push({type:"error",reason:"error",error:{role:"assistant",content:[],api:$.api,provider:$.provider,model:$.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:Q instanceof Error?Q.message:String(Q),timestamp:Date.now()}}),X.end()}finally{J()}})(),X}function W2($){M3($),$.registerProvider("openai-codex",{name:"OpenAI Codex (CortexKit OAuth)",baseUrl:l0,api:"openai-codex-responses",models:Q2,streamSimple:Y2})}export{G2 as installRawCodexWebSocket,W2 as default};
121
+ `);if(X===-1)return;let J=Z.slice(0,X),z=J.split(`\r
122
+ `)[0]??"",G=J.match(/sec-websocket-accept:\s*(\S+)/i);if(!z.includes(" 101")){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:z}),this.emit("error",{message:`WS upgrade failed: ${z}`});return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:z}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:z}),this.emit("open",{})}this.drainFrames()}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let Z=$[0],X=$[1],J=(Z&128)!==0,z=Z&15,G=(X&128)!==0,Q=X&127,Y=2;if(Q===126){if($.length<4)return;Q=$[2]<<8|$[3],Y=4}else if(Q===127){if($.length<10)return;Q=0;for(let H=0;H<8;H++)Q=Q*256+$[2+H];Y=10}if(G)Y+=4;if($.length<Y+Q)return;let B=$.slice(Y,Y+Q);this.rxBuffer=$.slice(Y+Q),this.handleFrame(J,z,B)}}handleFrame($,Z,X){if(Z===9){this.writeFrame(10,X);return}if(Z===10)return;if(Z===8){let z=1005,G="";if(X.length>=2)z=X[0]<<8|X[1],G=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:z,reason:G});return}if(Z===1||Z===2)this.fragOpcode=Z,this.fragChunks=[X];else if(Z===0)this.fragChunks.push(X);if(!$)return;let J=FB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let z=Buffer.from(J).toString("utf-8");this.emit("message",{data:z})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,Z){let X=Z.length,J=crypto.getRandomValues(new Uint8Array(4)),z;if(X<126)z=[128|$,128|X];else if(X<65536)z=[128|$,254,X>>8&255,X&255];else{z=[128|$,255];for(let Y=7;Y>=0;Y--)z.push(X/2**(8*Y)&255)}let G=new Uint8Array(X);for(let Y=0;Y<X;Y++)G[Y]=Z[Y]^J[Y%4];let Q=new Uint8Array(z.length+4+X);Q.set(z,0),Q.set(J,z.length),Q.set(G,z.length+4);try{this.socket?.write(Q)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log($,Z){return Promise.resolve()}}function MB($){return $}function LB($,Z){let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function FB($){let Z=0;for(let z of $)Z+=z.length;let X=new Uint8Array(Z),J=0;for(let z of $)X.set(z,J),J+=z.length;return X}import{statSync as kB}from"node:fs";var K0="main",s5=5;function i5($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function q4($){return $.reason==="exhausted"||$.reason==="budget-spent"}function a5($,Z,X){if($===void 0)return{reason:"no-credential"};if(X.get($)===!1)return{reason:"killswitch"};let J=Z.excluded.find((G)=>G.id===$);if(J?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:J.until};if(J)return{reason:"no-credential"};let z=Z.refused.find((G)=>G.id===$);if(z&&"resetAtMs"in z)return{reason:"quota-exhausted",resetAtMs:z.resetAtMs};if(z)return{reason:"quota-unknown"};return{reason:"no-credential"}}function c5($,Z,X){if(Z.refused.find((z)=>!q4(z)&&X.get(z.id)!==!1))return{reason:"quota-unknown"};return a5($[0],Z,X)}function n5($){let Z=$.replayable!==!1,X=Z?$.placement:"main-first",J=s3({rows:$.rows,placement:X,formerMainId:K0,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),z=u1($.rows.map((Y)=>Y.id),X,K0),G=new Set(J.admission.refused.filter((Y)=>q4(Y)&&$.killswitch.get(Y.id)!==!1).map((Y)=>Y.id)),Q=z.filter((Y)=>G.has(Y));if(!Z){let Y=z.includes(K0),B=Y?K0:J.order[0]??Q[0];if(B!==void 0&&J.order.includes(B))return{kind:"send",order:[B],lastPath:!1};if(B!==void 0&&G.has(B))return{kind:"send",order:[B],lastPath:!0};return{kind:"block",block:Y?a5(K0,J.admission,$.killswitch):c5(z,J.admission,$.killswitch)}}if(J.order.length>0)return{kind:"send",order:J.order,lastPath:!1};if(Q.length>0)return{kind:"send",order:Q,lastPath:!0};return{kind:"block",block:c5(z,J.admission,$.killswitch)}}function K4($){let Z=O1({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),X=new Map;for(let J of $.rows)X.set(J.id,c(J.quota));for(let J of Z.admitted)if(J.projection)X.set(J.id,J.projection);return{projections:X,excluded:new Set(Z.excluded.map((J)=>J.id))}}function r5($,Z,X){let J=X.exclude,z=J?$.rows.filter((Q)=>!J.has(Q.id)):$.rows,G=new Map;for(let Q of z){let Y=Z.resetCredits(Q.id);if(Y!==void 0)G.set(Q.id,Y)}return e3({rows:z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...X.pendingBytes?{pendingBytes:X.pendingBytes}:{},rowReservePercent:(Q)=>Z.reservePercent(Q.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...X.pin===void 0?{}:{pin:{accountId:X.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function o5($,Z,X,J){let z=r5($,Z,{exclude:X,pendingBytes:J});if(z.outcome!=="dispatch"||z.source==="pin")return;return{accountId:z.accountId,source:z.source,...z.quotaCheckedAt===void 0?{}:{quotaCheckedAt:z.quotaCheckedAt}}}function t5($,Z,X){let J=$.killswitch.get(X)===!1,z=r5($,Z,{pin:X});if(z.outcome==="dispatch"){if(z.pin.action==="assign")return{kind:"move",reason:J?"killswitch":"exhausted"};return z.accountId===X?{kind:"serve"}:{kind:"detour"}}let G=z.admission.refused.find((Q)=>Q.id===X);if(!J&&G&&q4(G))return{kind:"last-path"};return{kind:"none"}}function e5($,Z,X,J){let z=$.killswitch.get(X);return t3({quota:Z.projections.get(X),now:$.now,...J===void 0?{}:{status:J},...z===void 0?{}:{killswitchPasses:z}})}var PB=15000;function Q6($){if(!$)return;let Z=Z$($);return Z?X$(Z):void 0}class D4{deps;now;token;identity;quota;snapshot;firstPolledFor;inflight;lastPull;constructor($){this.deps=$,this.now=$.now??Date.now}observeToken($){if(!$)return;let Z=Q6($);if(this.token!==void 0&&this.accountKey(this.token,this.identity)!==this.accountKey($,Z))this.quota=void 0,this.snapshot=void 0;this.token=$,this.identity=Z;let X=this.accountKey($,Z);if(this.firstPolledFor!==X)this.firstPolledFor=X,this.pollNow()}currentToken(){return this.token}currentIdentity(){return this.identity}quotaMap(){return this.quota}quotaSnapshot(){let $=e$(this.quota);if(!$&&!this.snapshot)return;return{...this.snapshot?.resetCreditsAvailable!==void 0?{resetCreditsAvailable:this.snapshot.resetCreditsAvailable}:{},...this.snapshot?.spendControl?{spendControl:this.snapshot.spendControl}:{},...$}}requestReading($=!1){let Z=this.now();if(!$&&this.lastPull!==void 0&&Z-this.lastPull<(this.deps.pullRetryMs??PB))return;this.pollNow()}pending(){return this.inflight}pollNow(){if(this.inflight)return this.inflight;let $=this.token;if(!$)return Promise.resolve({ok:!1,error:"Pi holds no OpenAI login"});let Z=this.identity;this.lastPull=this.now();let X=(async()=>{try{let J=await this.deps.poll($,Z);if(this.accountKey(this.token,this.identity)!==this.accountKey($,Z))return{ok:!0};return this.snapshot=J.snapshot,this.merge(J.observation),{ok:!0}}catch(J){let z=J instanceof Error?J.message:String(J);return this.deps.log?.warn("Pi login quota poll failed",{error:z}),{ok:!1,error:z}}})();return this.inflight=X,X.finally(()=>{if(this.inflight===X)this.inflight=void 0}),X}record($,Z,X){if(!this.owns(Z))return!1;let J=$1($,this.now(),X);if(J)this.merge(J);return!0}owns($){if(!this.token)return!1;let Z=Q6($);return Z&&this.identity?Z===this.identity:$===this.token}merge($){try{let Z=s0(this.quota,$);if(o(Z))this.quota=Z}catch(Z){this.deps.log?.warn("Pi login quota observation not merged",{error:Z instanceof Error?Z.message:String(Z)})}}accountKey($,Z){if(Z)return`identity:${Z}`;return $?`token:${$}`:void 0}}import{homedir as OB}from"node:os";import{join as $X}from"node:path";function _B(){return process.env.PI_AGENT_DIR?.trim()||$X(OB(),".pi","agent")}function ZX(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||$X(_B(),s6)}function CB($=ZX()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||w8($)}function XX($=ZX()){return{configPath:$,statePath:CB($)}}function N4($){return $!==void 0&&($.vault===!0||!!$.token)}function JX($,Z,X,J,z=new Set){return $.filter((G)=>{if(!G.candidate||G.type!=="oauth")return!1;if(G.credential?.type!=="oauth")return!1;if(u0(G.credential))return!1;if(G.id===K0)return!1;if(J&&G.identity===J)return!1;if(G.identity!==void 0&&z.has(G.identity))return!1;return I3(e$(G.quota),Z,X)})}function M4($,Z){let X=$.now(),J=new Map;if(c2($.storage))for(let G of Z)J.set(G.id,r7(e$(G.quota),$.storage,G.id===K0?void 0:G.id,X));return{rows:Z.map((G)=>({id:G.id,kind:G.kind??"oauth",...o(G.quota)?{quota:G.quota}:{}})),now:X,rateLimitMarks:new Map,refreshBackoff:$.refreshBackoff(Z),killswitch:J,requestPull:$.requestPull}}async function zX($){let Z=$.accounts();if($.mode==="sticky-balanced"&&$.sessionId){let X=await AB($,Z,$.sessionId);if(X)return X}return TB($,Z)}async function TB($,Z){let X=i5($.mode),J=n5({...M4($,Z),placement:X});if(J.kind==="block")return $.log?.debug("pool admission blocked the request",{reason:J.block.reason}),{kind:"blocked",block:J.block};if(J.lastPath)$.log?.debug("pool admission: every account is exhausted; probing anyway",{order:J.order});let z=new Map(Z.map((H)=>[H.id,H])),G=n7($.storage),Q=[],Y=new Set,B;for(;;){let H=i3(J.order.filter((j)=>!Y.has(j)),Q,G);if(H===void 0)break;let W=z.get(H);if(!N4(W)){Y.add(H);continue}let V=await $.send(W);if(!V){Y.add(H);continue}B={attempt:V,accountId:W.id},Q.push({id:W.id,...V.status!==void 0?{status:V.status}:{}})}if(B)return{kind:"sent",...B};return{kind:"blocked",block:{reason:"no-credential"}}}async function AB($,Z,X){let J=$.requestBytes,z=new Map(Z.map((N)=>[N.id,N])),G=M4($,Z),Q=K4(G),Y={requestBytes:J,reservePercent:(N)=>L1($.storage,N===K0?void 0:N),resetCredits:()=>{return},onEmptyWeightedSet:()=>{$.log?.debug("sticky routing: no fresh weighted candidates; using configured order")}},B=(N,K,F)=>(C,M)=>{let D=new Set(C);return $.placePin({sessionId:X,requestBytes:J,validPinnedAccountIds:N.rows.map((P)=>P.id).filter((P)=>!K.excluded.has(P)),excludeAccountIds:C,quotaCheckedAtByAccount:Object.fromEntries(N.rows.map((P)=>[P.id,K.projections.get(P.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(F.map((P)=>[P.id,P.identity])),select:(P)=>o5(N,Y,D,P),persist:M})},H=B(G,Q,Z),W=H([],!0);if(!W)return;let V=W.accountId,j=(N)=>{let K=H([V],!0);if(!K)return!1;return $.log?.debug("sticky routing: migrated session pin",{fromAccountId:V,toAccountId:K.accountId,reason:N}),V=K.accountId,!0},q=t5(G,Y,V);if(q.kind==="none")return;if(q.kind==="move"){if(!j(q.reason)&&q.reason==="killswitch")return}else if(q.kind==="detour"){let N=H([V],!1);if(!N)return;$.log?.debug("sticky routing: pinned account awaits a quota reading",{pinnedAccountId:V,servedAccountId:N.accountId}),V=N.accountId}let U=z.get(V);if(!N4(U))return;let L=await $.send(U);if(!L)return;if(L.status===401||L.status===403||L.status===429){let N=$.accounts();G=M4($,N),Q=K4(G),H=B(G,Q,N);let K=e5(G,Q,V,L.status);if(K.action==="migrate"){let F=V;if(j(K.reason)&&V!==F){let C=N.find((D)=>D.id===V),M=N4(C)?await $.send(C):void 0;if(C&&M)L=M,U=C;else V=F}}}return{kind:"sent",attempt:L,accountId:U.id}}import{readFileSync as jL,statSync as RB}from"node:fs";var SB=500,IB=15000,GX=30000,xB=8,bB=1800000;function Y6($,Z,X){return new Promise((J,z)=>{let G=setTimeout(()=>J(X()),Z);G.unref?.(),$.then((Q)=>{clearTimeout(G),J(Q)},(Q)=>{clearTimeout(G),z(Q)})})}function QX($){try{let Z=RB($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function YX($){return $.identity?`identity:${$.identity}`:`row:${$.id}`}function D$($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}var EB={info(){},warn(){}};class L4{deps;now;log;snapshot={active:!1,rows:[],key:void 0,readAt:0};inflightRead;store;initializing;refreshing=new Map;backoff=new Map;rotated=new Map;pending=new Map;writes=new Map;lastPull=new Map;polled=new Set;polledSnapshots=new Map;pollOutcomes=new Map;disposed=!1;constructor($){this.deps=$,this.now=$.now??Date.now,this.log=$.log??EB}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}async current(){let $=this.filesKey();if(this.snapshot.key===$)return this.peek();let Z=await Y6(this.startRead($),this.deps.readBudgetMs??SB,()=>this.snapshot);return{active:Z.active,rows:Z.rows}}async load(){let $=await this.startRead(this.filesKey());return{active:$.active,rows:$.rows}}poolStore(){return this.storeFor(this.deps.paths())}polledSnapshot($){return this.polledSnapshots.get($)}filesKey(){let $=this.deps.paths();return`${$.configPath}|${QX($.configPath)}|${QX($.statePath)}`}storeFor($){if(this.store?.configPath===$.configPath)return this.store.store;let Z=R8({provider:"openai",configPath:$.configPath,statePath:$.statePath,quota:l3,now:this.now,pull:(X)=>this.pull(X),onPullFailure:(X,J)=>{this.pollOutcomes.set(X,{id:X,ok:!1,error:J.message}),this.log.warn("pool quota poll failed",{rowId:X,kind:J.kind,error:J.message})},logger:this.log,...this.deps.store,onStep:async(X,J)=>{if(await this.deps.store?.onStep?.(X,J),J.operation!=="updateSettings"&&X.startsWith("before-")&&(this.deps.vaultAuthority?await this.deps.vaultAuthority()!=="local":this.setAside()))throw Error("Local account writes are disabled while connected to the vault.")}});return this.store={configPath:$.configPath,store:Z},Z}startRead($){if(this.inflightRead?.key===$)return this.inflightRead.promise;let Z=this.now(),X=this.read($,Z),J={key:$,promise:X};this.inflightRead=J;let z=()=>{if(this.inflightRead===J)this.inflightRead=void 0};return X.then(z,z),X}async read($,Z){let X=this.deps.paths(),J;try{J=await this.storeFor(X).read()}catch(G){return this.log.warn("account pool read failed",{error:G instanceof Error?G.message:String(G)}),this.snapshot}if(J.status==="pending-migration"){if(!this.setAside())this.initialize(X)}else if(J.status==="error")this.log.warn("account pool is unreadable",{file:J.file,reason:J.reason});let z=J.status==="ready"?{active:!0,rows:J.rows,key:$,readAt:Z}:{active:!1,rows:[],key:$,readAt:Z};if(Z>=this.snapshot.readAt)this.snapshot={...z,rows:this.withLocalState(z.rows)};if(this.snapshot.active)this.pollUnseenRows();return this.snapshot}initialize($){if(this.disposed||this.initializing?.configPath===$.configPath)return;let Z=this.storeFor($).initialize().then((X)=>{this.log.info("account pool initialized",{status:X.status})},(X)=>{if(this.log.warn("account pool initialization failed",{error:X instanceof Error?X.message:String(X)}),this.initializing?.promise===Z)this.initializing=void 0});this.initializing={configPath:$.configPath,promise:Z}}withLocalState($){let Z=this.now();return $.map((X)=>{let J=X,z=this.rotated.get(X.id);if(z?.type==="oauth"&&X.credential?.type==="oauth"){let Q=X.credential.lastRefreshedAt??0,Y=z.lastRefreshedAt??0;if(Q>=Y)this.rotated.delete(X.id);else J={...J,credential:z}}let G=(this.pending.get(YX(X))??[]).filter((Q)=>Z-Q.observation.checkedAt<=bB);for(let Q of G){if(Q.credentialEpoch!==X.credentialEpoch||Q.identity!==X.identity)continue;J={...J,quota:this.merged(J.quota,Q.observation)}}return J})}merged($,Z){try{return s0($,Z)}catch{return $}}replaceRow($,Z){this.snapshot={...this.snapshot,rows:this.snapshot.rows.map((X)=>X.id===$?Z(X):X)}}pollUnseenRows(){if(this.disposed||this.setAside())return;for(let $ of this.snapshot.rows){let Z=$.torn===!0&&$.enabled;if(!($.candidate||Z)||$.type!=="oauth")continue;let X=`${$.id}\x00${$.credentialEpoch??0}\x00${$.identity??""}`;if(this.polled.has(X))continue;this.polled.add(X),this.requestReading($.id,!0)}}requestReading($,Z=!1){if(this.disposed||this.setAside())return;let X=this.now(),J=this.lastPull.get($);if(!Z&&J!==void 0&&X-J<(this.deps.pullRetryMs??IB))return;this.lastPull.set($,X),this.storeFor(this.deps.paths()).requestReading($)}async pull($){let Z;try{Z=await this.deps.pullQuota($)}catch(J){throw this.pollOutcomes.set($.id,{id:$.id,ok:!1,error:J instanceof Error?J.message:String(J)}),J}this.pollOutcomes.set($.id,{id:$.id,ok:!0}),this.polledSnapshots.set($.id,Z.snapshot);let X=this.snapshot.rows.find((J)=>J.id===$.id);if(X&&X.credentialEpoch===$.credentialEpoch&&X.identity===$.identity)this.applyObservation(X,Z.observation);return Z.observation}applyObservation($,Z){let X=YX($),J=[...this.pending.get(X)??[],{credentialEpoch:$.credentialEpoch,identity:$.identity,observation:Z}].slice(-xB);this.pending.set(X,J),this.replaceRow($.id,(z)=>({...z,quota:this.merged(z.quota,Z),needsFirstReading:!1}))}recordSnapshot($,Z,X,J){if(!this.snapshot.active||this.disposed||this.setAside())return;let z=this.snapshot.rows.find((j)=>j.id===$);if(z?.type!=="oauth")return;let G=Q6(X);if(!(G&&z.identity?G===z.identity:D$(z)?.access===X))return;let Y=$1(Z,this.now(),J);if(!Y)return;if(this.applyObservation(z,Y),z.credentialEpoch===void 0)return;let B={credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},H=this.storeFor(this.deps.paths()),V=(this.writes.get(z.id)??Promise.resolve()).then(async()=>{if(this.disposed||(this.deps.vaultAuthority?await this.deps.vaultAuthority()!=="local":this.setAside()))return;return H.recordQuota(z.id,B,Y)}).catch((j)=>{this.log.warn("pool quota not recorded",{rowId:z.id,error:j instanceof Error?j.message:String(j)})});this.writes.set(z.id,V),V.finally(()=>{if(this.writes.get(z.id)===V)this.writes.delete(z.id)})}rowForToken($){let Z=Q6($);return this.snapshot.rows.find((X)=>Z&&X.identity?X.identity===Z:D$(X)?.access===$)}refreshDueTokens($,Z){if(this.setAside())return Promise.resolve();let X=this.now(),J=s2(Z),z=[];for(let G of $){if(!G.candidate)continue;let Q=D$(G);if(!Q)continue;let Y=(Q.expires??0)-X;if(!(!Q.access||!Q.expires||Y<=J)||this.refreshBackedOff(G,X))continue;z.push(this.refresh(G.id))}return Promise.all(z).then(()=>{})}refreshBackedOff($,Z=this.now()){let X=D$($);if(!X)return!1;let J=this.backoff.get($.id);return Boolean(J&&J.tokenHash===E$(X.refresh)&&J.nextRetryAt>Z)}usableToken($,Z=this.now()){if(this.setAside())return;let X=D$($);if(!X?.access.trim())return;if(typeof X.expires!=="number"||X.expires<=Z)return;return X.access}refresh($){let Z=this.refreshing.get($);if(Z)return Z;let X=this.runRefresh($).finally(()=>{if(this.refreshing.get($)===X)this.refreshing.delete($)});return this.refreshing.set($,X),X}async runRefresh($){let Z=this.snapshot.rows.find((J)=>J.id===$),X=Z?D$(Z)?.refresh:void 0;try{let J=await this.storeFor(this.deps.paths()).refresh($,this.deps.refreshProvider,{refuse:()=>this.setAside()?"vault-mode":void 0});if(this.setAside())return;if(J.status==="rotated"){this.backoff.delete($),this.rotated.set($,J.credential),this.replaceRow($,(z)=>({...z,credential:J.credential,...J.identity!==void 0&&z.identity===void 0?{identity:J.identity}:{}}));return}if(J.status==="identity-contradicted"){this.backoff.delete($),this.replaceRow($,(z)=>({...z,enabled:!1,candidate:!1})),this.log.warn("pool row disabled: its refresh returned a different account",{rowId:$});return}this.recordRefreshFailure($,X,Error(J.reason))}catch(J){this.recordRefreshFailure($,X,J)}}recordRefreshFailure($,Z,X){if(this.log.warn("pool row refresh failed",{rowId:$,error:X instanceof Error?X.message:String(X)}),!Z)return;let J=this.now(),z=E$(Z),G=this.backoff.get($);if(typeof X?.status==="number"||y8(X)){let Y=u6({error:X,now:J,refreshToken:Z,...G?{previous:{message:"",checkedAt:J,nextRetryAt:G.nextRetryAt,retryCount:G.retryCount,tokenHash:G.tokenHash}}:{}});this.backoff.set($,{nextRetryAt:Y.nextRetryAt,tokenHash:z,retryCount:Y.retryCount})}else this.backoff.set($,{nextRetryAt:J+GX,tokenHash:z,retryCount:G?.tokenHash===z?G.retryCount:0})}refreshBackoffFor($){let Z=this.now(),X=new Map;for(let J of $){if(this.usableToken(J,Z))continue;let z=this.backoff.get(J.id);X.set(J.id,z&&z.nextRetryAt>Z?z.nextRetryAt:Z+GX)}return X}async pollRows($){if(this.setAside())return[];let Z=await this.load();if(!Z.active||this.disposed)return[];let X=Z.rows.filter((J)=>J.candidate&&J.type==="oauth");if(X.length===0)return[];await this.refreshDueTokens(X,$);for(let J of X)this.pollOutcomes.delete(J.id),this.requestReading(J.id,!0);return await this.poolStore().pullsSettled(),X.map((J)=>this.pollOutcomes.get(J.id)??{id:J.id,ok:!1,error:"the quota poll did not run"})}setAside(){return this.deps.vaultMode?.()===!0}dispose(){this.disposed=!0}async settled(){for(;;){let $=[...this.writes.values(),...this.refreshing.values(),...this.initializing?[this.initializing.promise]:[]];if(await Promise.allSettled($),await this.store?.store.pullsSettled(),this.writes.size===0&&this.refreshing.size===0)return}}}var fB=5000,yB=500,vB=64;function gB(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function B6($,Z){return{type:"error",reason:"error",error:{role:"assistant",content:[],api:$.api,provider:$.provider,model:$.id,usage:gB(),stopReason:"error",errorMessage:Z,timestamp:Date.now()}}}function hB($){let Z=$.resetAtMs!==void 0?` It resets at ${new Date($.resetAtMs).toISOString()}.`:"";switch($.reason){case"quota-unknown":return`No OpenAI account has a quota reading yet; one is being taken now. Try again in ${s5} seconds.`;case"quota-exhausted":return`Every OpenAI account has used up its quota.${Z}`;case"killswitch":return"Every OpenAI account is below its killswitch quota floor (see the Limits section of `/openai`).";case"mid-stream-rate-limit":return`Every OpenAI account is rate-limited.${Z}`;case"no-credential":return"No OpenAI account holds a usable sign-in. Sign in with `/login` or add an account with `/openai`."}}function wB($){for(let[Z,X]of Object.entries($)){if(Z.toLowerCase()!=="authorization")continue;return/^Bearer\s+(.+)$/i.exec(X.trim())?.[1]}return}class F4{main;pool;vault;deps;vaultTokens=new Map;now;paths;slot;slotVaultMode;slotNeedsRefresh=!1;slotQueue=Promise.resolve();storageCache;storageRead;constructor($){this.deps=$,this.now=$.now??Date.now,this.paths=$.paths??XX;let Z=()=>$.fetchImpl??globalThis.fetch;this.main=new D4({now:this.now,poll:async(X,J)=>{if(await this.readAuthority()!=="local")throw Error("Pi login quota polling is disabled while enrolled");let z=await H$({accessToken:X,fetchImpl:Z(),now:this.now,...J?{accountId:J}:{},accountKey:K0}),G=$1(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.pool=new L4({paths:this.paths,now:this.now,...$.readBudgetMs!==void 0?{readBudgetMs:$.readBudgetMs}:{},vaultMode:()=>this.vaultMode(),vaultAuthority:()=>this.readAuthority(),refreshProvider:async(X)=>{if(await this.readAuthority()!=="local")throw Error("Local token refresh is disabled while enrolled");let J=await h7({refreshToken:X.refresh,fetchImpl:Z(),now:this.now}),z=g$({id_token:"",access_token:J.access,refresh_token:J.refresh});return{...J,...z?{identity:z}:{}}},pullQuota:async(X)=>{if(await this.readAuthority()!=="local")throw Error("Local quota polling is disabled while enrolled");let J=X.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let z=await H$({accessToken:J.access,fetchImpl:Z(),now:this.now,...X.identity?{accountId:X.identity}:{},accountKey:X.id}),G=$1(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.vault=$.vault??new a2({host:"pi",stateDir:x3(this.paths().statePath),reservedRouteIds:()=>this.pool.peek().rows.map((X)=>X.id),fetchImpl:Z,now:this.now})}vaultMode(){return this.vault.enrolled()}readAuthority(){return this.vault.authority()}vaultSlot(){return this.slot??=this.deps.slot??u5(this.paths().statePath),this.slot}withSlot($){let Z=this.slotQueue.then($);return this.slotQueue=Z.catch(()=>{this.slotVaultMode=void 0}),Z}syncVaultSlot($,Z=!1){return this.withSlot(async()=>{if(await this.reconcileSlot(Z),this.slotNeedsRefresh&&$)await $(),this.slotNeedsRefresh=!1})}disconnectVault(){return this.withSlot(async()=>{this.slotVaultMode=void 0;try{let $=await this.vaultSlot().exitVault();return this.slotNeedsRefresh=!0,await this.vault.disconnect(),$}finally{await this.reconcileSlot()}})}async reconcileSlot($=!1){let Z=await this.readAuthority()!=="local";if(Z===this.slotVaultMode&&!$)return;let X=this.slotVaultMode;this.slotVaultMode=void 0;let J=await this.vaultSlot().inspect();if(Z)await this.vaultSlot().enterVault();else await this.vaultSlot().exitVault();this.slotNeedsRefresh=Z&&J.slot!=="placeholder"||!Z&&J.slot==="placeholder"||X!==void 0&&Z!==X||this.slotNeedsRefresh;let z=await this.readAuthority()!=="local";if(z!==Z){if(z)await this.vaultSlot().enterVault();else await this.vaultSlot().exitVault();this.slotNeedsRefresh=!0}this.slotVaultMode=z}async start(){return await this.readAuthority(),this.vault.start(),this.pool.load().then(()=>{},()=>{})}async storage(){let $=this.paths(),Z;try{let X=kB($.configPath);Z=`${$.configPath}|${X.ino}:${X.size}:${X.mtimeMs}`}catch{Z=`${$.configPath}|-`}if(this.storageCache?.key===Z)return this.storageCache.storage;if(this.storageRead?.key!==Z){let X=d2($).then((J)=>{return this.storageCache={key:Z,storage:J},J},()=>this.storageCache?.storage??null);this.storageRead={key:Z,promise:X}}return Y6(this.storageRead.promise,this.deps.readBudgetMs??yB,()=>this.storageCache?.storage??null)}accounts($){let Z=[];if(!this.vaultMode())this.localAccounts($,Z);for(let X of this.vault.routes())Z.push({id:X.id,token:void 0,kind:X.kind,vault:!0,...X.identity?{identity:X.identity}:{},...X.quota!==void 0?{quota:X.quota}:{}});return Z}localAccounts($,Z){let X=this.main.currentToken(),J=this.main.currentIdentity(),z=this.vault.identities();if(X&&!(J!==void 0&&z.has(J))){let Y=this.main.quotaMap();Z.push({id:K0,token:X,...J?{identity:J}:{},...Y?{quota:Y}:{}})}let G=this.pool.peek(),Q=this.now();if(G.active)for(let Y of JX(G.rows,$,Q,J,z))Z.push({id:Y.id,token:this.pool.usableToken(Y,Q),...Y.identity?{identity:Y.identity}:{},...Y.quota!==void 0?{quota:Y.quota}:{}})}poolRowById($){return this.pool.peek().rows.find((Z)=>Z.id===$)}requestPull($){if($===K0)this.main.requestReading();else if(this.vault.owns($))this.vault.requestReading($);else this.pool.requestReading($)}rememberVaultToken($,Z){this.vaultTokens.delete($),this.vaultTokens.set($,Z);while(this.vaultTokens.size>vB){let X=this.vaultTokens.keys().next().value;if(X===void 0)break;this.vaultTokens.delete(X)}}recordHeaders($,Z,X){let J=new Headers(X),z=qZ(J),G=KZ(J),Q=this.vaultTokens.get(Z);if(Q?.id===$)this.vault.recordSnapshot($,z,G,Q.receipt);else if($===K0)this.main.record(z,Z,G);else this.pool.recordSnapshot($,z,Z,G)}recordRateLimitFrame($,Z){let X=this.vaultTokens.get($);if(X){this.vault.recordSnapshot(X.id,Z,!0,X.receipt);return}if(this.main.record(Z,$,!0))return;let J=this.pool.rowForToken($);if(J)this.pool.recordSnapshot(J.id,Z,$,!0)}observeWebSocketMessage($,Z){if(!Z.includes("codex.rate_limits"))return;let X=wB($);if(!X)return;let J;try{J=JSON.parse(Z)}catch{return}if(!J||typeof J!=="object"||J.type!=="codex.rate_limits")return;this.recordRateLimitFrame(X,DZ(J))}stream($,Z,X){let J=this.deps.createStream(),z=this.deps.installWebSocket?.()??(()=>{});return(async()=>{try{if(await this.readAuthority()!=="local"&&X?.apiKey!==G6){J.push(B6($,m5));return}let G=await this.route($,Z,X);if(G.kind==="blocked"){J.push(B6($,G.refusal?z5[G.refusal]:hB(G.block)));return}if(G.head)J.push(G.head);if(G.rest)for(;;){let Q=await G.rest.next();if(Q.done)break;J.push(Q.value)}}catch(G){J.push(B6($,Z6(G instanceof Error?G.message:String(G),X?.apiKey)))}finally{J.end(),z()}})(),J}async route($,Z,X){let J=await this.storage(),z=await this.readAuthority()!=="local";if(z)await Y6(this.vault.firstRoster().then(()=>!0),b3,()=>!1);else this.main.observeToken(X?.apiKey),await this.pool.current(),this.pool.refreshDueTokens(this.pool.peek().rows,J);let G=J?.routing?.mode??"main-first",Q=!1,Y=0,B=()=>zX({accounts:()=>{let W=this.accounts(J);return Y=W.length,W},storage:J,mode:G,sessionId:X?.sessionId,requestBytes:Buffer.byteLength(JSON.stringify(Z),"utf8"),now:this.now,refreshBackoff:(W)=>this.pool.refreshBackoffFor(W.map((V)=>this.poolRowById(V.id)).filter((V)=>V!==void 0)),requestPull:(W)=>this.requestPull(W),send:(W)=>W.vault?this.vaultAttempt($,Z,X,W.id).then((V)=>{if(!V)Q=!0;return V}):W.token?this.attempt($,Z,X,W.id,W.token):Promise.resolve(void 0),placePin:S5}),H=await B();if(H.kind==="blocked"&&H.block.reason==="quota-unknown"&&!z){let W=this.main.pending();if(W)await Y6(W.then(()=>!0),this.deps.firstReadingWaitMs??fB,()=>!1),H=await B()}if(H.kind==="blocked"){if(z&&(Y===0||Q))return{...H,refusal:Q?"vault-refused":G5(this.vault)};if(z&&H.block.reason==="no-credential")return{...H,refusal:"vault-empty"};return H}return{kind:"sent",...H.attempt}}async attempt($,Z,X,J,z){let G,Q;try{Q=this.deps.streamSimple($,Z,{...X,apiKey:z,onResponse:async(W,V)=>{G=W.status,this.recordHeaders(J,z,W.headers),await X?.onResponse?.(W,V)}})}catch(W){return{head:B6($,Z6(W instanceof Error?W.message:String(W),z)),rest:void 0}}let Y=async function*(){try{for await(let W of Q)yield W.type==="error"?{...W,error:{...W.error,errorMessage:Z6(W.error.errorMessage??"",z)}}:W}catch(W){yield B6($,Z6(W instanceof Error?W.message:String(W),z))}}(),B=await Y.next(),H=B.done?void 0:B.value;return{...G!==void 0?{status:G}:{},head:H,rest:B.done||H?.type==="error"?void 0:Y}}async vaultAttempt($,Z,X,J){let z;return await this.vault.send(J,async(Q,Y)=>{return this.rememberVaultToken(Q,{id:J,receipt:{credentialId:Y.credentialId,accountIdentitySource:Y.accountIdentitySource,...Y.accountIdentity!==void 0?{accountIdentity:Y.accountIdentity}:{},...Y.expectedAccountIdentity!==void 0?{expectedAccountIdentity:Y.expectedAccountIdentity}:{}}}),z=await this.attempt($,Z,X,J,Q),new Response(null,{status:z.status??200})},{site:"model",...X?.signal?{signal:X.signal}:{}})?z:void 0}commandSupport(){return{vaultMode:()=>this.vaultMode(),readAuthority:()=>this.readAuthority(),syncVaultSlot:($,Z)=>this.syncVaultSlot($,Z),disconnectVault:()=>this.disconnectVault(),observeLogin:async($)=>{if(await this.readAuthority()==="local")this.main.observeToken($)},store:()=>this.pool.poolStore(),mainIdentity:()=>this.main.currentIdentity(),mainQuota:()=>this.main.quotaSnapshot(),reload:()=>this.pool.load(),vault:this.vault,refreshAllQuota:async()=>{let $=await this.readAuthority()==="local"?await this.storage():null;if(await this.readAuthority()!=="local")return(await this.vault.pollStale(0)).map((G)=>({account:G.id,ok:G.ok,...G.error?{error:G.error}:{}}));let[Z,X,J]=await Promise.all([this.main.currentToken()?this.main.pollNow():void 0,this.pool.pollRows($),this.vault.pollStale(0)]),z=[];if(Z)z.push({account:K0,ok:Z.ok,...Z.error?{error:Z.error}:{}});for(let G of[...X,...J])z.push({account:G.id,ok:G.ok,...G.error?{error:G.error}:{}});return z}}}}var H6="https://chatgpt.com/backend-api",WX;class O4 extends U4{constructor($,Z){let X=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),X);let J=WX;if(J)this.addEventListener("message",(z)=>{let G=z?.data;if(typeof G==="string")J(X,G)})}}var W6=0,P4;function uB(){let $=globalThis;if(W6===0)P4=$.WebSocket,$.WebSocket=O4;return W6++,()=>{if(W6=Math.max(0,W6-1),W6===0){if($.WebSocket===O4)$.WebSocket=P4;P4=void 0}}}var lB=[{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:H6,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:5,output:30,cacheRead:0.5,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4",name:"GPT-5.4",api:"openai-codex-responses",provider:"openai-codex",baseUrl:H6,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:0.25,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-codex-responses",provider:"openai-codex",baseUrl:H6,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:0.75,output:4.5,cacheRead:0.075,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"openai-codex-responses",provider:"openai-codex",baseUrl:H6,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:128000}],dB=5000;function BX($,Z){$.registerProvider("openai-codex",{baseUrl:H6,api:"openai-codex-responses",name:"OpenAI Codex (CortexKit)",...Z.vaultMode()?{apiKey:G6}:{},models:lB,streamSimple:(X,J,z)=>Z.stream(X,J,z)})}function cB(){return new F4({streamSimple:($,Z,X)=>pB($,Z,X),createStream:mB,installWebSocket:uB})}async function sB($){let Z=cB();WX=(Q,Y)=>Z.observeWebSocketMessage(Q,Y);let X,J,z=(Q=!0)=>Z.syncVaultSlot(X?async()=>{BX($,Z),await X?.()}:void 0,Q),G=()=>{z(!1).catch(()=>{J?.("Pi could not load the vault login slot. Reopen the session or disconnect in /openai.","error")})};if(l5($,{pool:Z.commandSupport(),afterApply:z,onContext:(Q)=>{X=()=>Q.modelRegistry.refresh(),J=(Y,B)=>Q.ui.notify(Y,B)}}),await z().catch(()=>{}),BX($,Z),setInterval(G,dB).unref?.(),typeof $.on==="function")$.on("session_start",async(Q,Y)=>{X=()=>Y.modelRegistry.refresh(),J=(B,H)=>Y.ui.notify(B,H),Z.start();try{await z()}catch{J("Pi could not load the vault login slot. Reopen the session or disconnect in /openai.","error");return}if(Z.vaultMode())return;try{await Z.commandSupport().observeLogin(await Y.modelRegistry.getApiKeyForProvider("openai-codex"))}catch{}})}export{BX as registerPiProvider,uB as installRawCodexWebSocket,sB as default,cB as createPiOpenAIRuntime};