@cortexkit/pi-openai-auth 1.1.0 → 1.2.0

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,13 +1,13 @@
1
- import{createRequire as j5}from"node:module";var D5=j5(import.meta.url);import{createAssistantMessageEventStream as ZQ}from"@earendil-works/pi-ai";import{streamSimple as XQ}from"@earendil-works/pi-ai/compat";var X0="all",UZ=Object.freeze(["primary"]);function m8($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function k1($,Z){return JSON.stringify([$,Z])}function K1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j0($){return typeof $==="number"&&Number.isFinite($)}function v8($){return typeof $==="string"&&$.length>0}function O0($,Z,X){return $[Z]===void 0||X($[Z])}function K5($){return j0($)&&$>0}function VZ($){return typeof $==="string"}function q5($){if(!K1($)||!v8($.scope)||!v8($.label))return!1;switch($.kind){case"reading":return j0($.checkedAt)&&j0($.usedPercent)&&O0($,"resetsAt",VZ)&&O0($,"windowMinutes",K5);case"retired":return j0($.retiredAt);case"absent":return j0($.checkedAt);default:return!1}}function N5($){if(!K1($)||!j0($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&O0($,"remainingPercent",j0)&&O0($,"usedPercent",j0)&&O0($,"resetsAt",VZ)&&O0($,"limit",j0)&&O0($,"used",j0)&&O0($,"remaining",j0)&&O0($,"unit",VZ)}function w8($){return K1($)&&j0($.value)&&Number.isInteger($.value)&&$.value>=0&&j0($.checkedAt)}function jZ($){return K1($)&&Object.values($).every(w8)}function DZ($){if(!K1($))return;let Z=Object.entries($).filter(([,X])=>w8(X));return Z.length===0?void 0:Object.fromEntries(Z)}function q1($){if(Q0($))return $;if(!K1($))return;let{counters:Z,...X}=$;if(!Q0(X))return;let J=DZ(Z);return{...X,...J===void 0?{}:{counters:J}}}function Q0($){if(!K1($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!q5(X))return!1;let J=k1(X.scope,X.label);if(Z.has(J))return!1;Z.add(J)}return O0($,"budget",N5)&&O0($,"counters",jZ)}class e$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function Z6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function $6($){return typeof $==="number"&&Number.isFinite($)}function p8($){return $===void 0||typeof $==="string"&&$!==""}function u8($){return typeof $==="string"&&$!==""}function Y$($,Z){return $[Z]===void 0||$6($[Z])}function KZ($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function M5($){return Z6($)&&p8($.scope)&&u8($.label)&&$6($.usedPercent)&&KZ($,"resetsAt")&&($.windowMinutes===void 0||$6($.windowMinutes)&&$.windowMinutes>0)}function F5($){return Z6($)&&p8($.scope)&&u8($.label)}function L5($){if(!Z6($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&Y$($,"remainingPercent")&&Y$($,"usedPercent")&&KZ($,"resetsAt")&&Y$($,"limit")&&Y$($,"used")&&Y$($,"remaining")&&KZ($,"unit")}function l8($){if(!Z6($)||!$6($.checkedAt))return!1;let Z=$.readings??[],X=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(X))return!1;let J=new Set;for(let G of Z){if(!M5(G))return!1;let z=k1(G.scope??X0,G.label);if(J.has(z))return!1;J.add(z)}if(!X.every(F5))return!1;return($.budget===void 0||L5($.budget))&&($.counters===void 0||jZ($.counters))}function _5($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function O5($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function C5($,Z){let X=new Map(Object.entries($??{}));for(let[J,G]of Object.entries(Z??{})){let z=X.get(J);if(z===void 0||G.checkedAt>=z.checkedAt)X.set(J,G)}return X.size===0?void 0:Object.fromEntries(X)}function E0($,Z){let X=$===void 0?void 0:q1($);if($!==void 0&&X===void 0)throw new e$("stored quota map is malformed");if(!l8(Z))throw new e$("quota observation is malformed");let J=X??{limits:[]},G=Z.checkedAt,z=new Map;for(let U of J.limits)z.set(k1(U.scope,U.label),U);let B=(U)=>{let N=z.get(U);return N===void 0||G>=m8(N)},Q=new Set;for(let U of Z.readings??[]){let N=U.scope??X0,K=k1(N,U.label);if(Q.add(K),!B(K))continue;z.set(K,{scope:N,label:U.label,kind:"reading",checkedAt:G,usedPercent:U.usedPercent,...U.resetsAt===void 0?{}:{resetsAt:U.resetsAt},...U.windowMinutes===void 0?{}:{windowMinutes:U.windowMinutes}})}for(let U of Z.coverage??[]){let N=U.scope??X0,K=k1(N,U.label);if(Q.has(K)||!B(K))continue;let M=z.get(K);z.set(K,M===void 0||M.kind==="absent"?{scope:N,label:U.label,kind:"absent",checkedAt:G}:{scope:N,label:U.label,kind:"retired",retiredAt:G})}let{limits:Y,budget:H,counters:W,...V}=J,j=O5(J.budget,Z.budget,G),D=C5(J.counters,Z.counters);return{...V,limits:[...z.values()].sort(_5),...j===void 0?{}:{budget:j},...D===void 0?{}:{counters:D}}}var qZ=Object.freeze({validate:Q0,decode:q1,merge:E0});var s8=900000,i8="no quota reading yet",a8="no limits reported";function n8($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let G=Math.floor(Z/60),z=Z%60;return z===0?`${G}h`:`${G}h${z}m`}let X=Math.floor(Z/1440),J=Math.floor(Z%1440/60);return J===0?`${X}d`:`${X}d${J}h`}function P5($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function X6($){if($.scope!==X0||$.windowMinutes===void 0)return $.label;return P5($.windowMinutes)}function NZ($){return Math.min(100,Math.max(0,$))}function d8($){return`${Math.round(NZ($))}% left`}function c8($,Z,X){let J=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(J)&&J>X?{resetIn:n8(J-X)}:{},resetSinceReading:Number.isFinite(J)&&J>Z&&J<=X}}function T5($,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===X0)return-1;if(Z.scope===X0)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function r8($,Z){if(!$)return{windows:[]};let{now:X}=Z,G=$.limits.filter((B)=>B.kind==="reading"&&B.remainingPercent!==void 0).sort(T5).map((B)=>{let Q=NZ(B.remainingPercent??0);return{kind:"window",name:X6(B),figure:d8(B.remainingPercent??0),remainingPercent:Q,checkedAt:B.checkedAt,...c8(B.resetsAt,B.checkedAt,X)}}),z=$.budget;if(z){let B=z.remainingPercent,Q=z.reached?"credits spent":B!==void 0?`credits ${d8(B)}`:"credits available";G.push({kind:"budget",name:"credits",figure:Q,...B===void 0?{}:{remainingPercent:NZ(B)},checkedAt:z.checkedAt,...c8(z.resetsAt,z.checkedAt,X)})}if(G.length>0){let B=X-Math.min(...G.map((Q)=>Q.checkedAt));if(B>(Z.staleAfterMs??s8))return{windows:G,age:`checked ${n8(B)} ago`}}return{windows:G}}function y1($,Z){let X=r8($,Z),J=(Z.form??"full")==="full",G=X.windows.map((z)=>{let B=J&&z.resetIn?`, resets ${z.resetIn}`:"";return`${z.kind==="budget"?"":`${z.name} `}${z.figure}${B}`});return X.age===void 0?G:[...G,X.age]}function C0($,Z){let X=y1($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?a8:i8}function A5($){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 S5($,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 R5($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function s($,Z=X0){let X=new Map;for(let H of $?.limits??[]){if(H.scope!==Z&&H.scope!==X0)continue;let W=X.get(H.label);if(W===void 0){X.set(H.label,H);continue}let V=H.scope===X0?W:H,j=H.scope===X0?H:W;X.set(H.label,V.kind==="reading"?V:j)}let J=[...X.values()].map(A5).sort(S5),G=J.filter((H)=>H.kind==="reading"),z=G.length>0?G:J,B=z.length>0?Math.min(...z.map((H)=>H.checkedAt)):void 0,Q=$?.budget?.kind==="reading"?R5($.budget):void 0,Y=DZ($?.counters);return{scope:Z,limits:J,...B===void 0?{}:{checkedAt:B},...Q===void 0?{}:{budget:Q},...Y===void 0?{}:{counters:Y}}}function H$($,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 MZ($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function J6($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}function o8($,Z,X){let J=Z.rateLimitMarks?.get($);if(J!==void 0&&X<J)return{id:$,reason:"rate-limited",until:J};let G=Z.refreshBackoff?.get($);if(G!==void 0&&X<G)return{id:$,reason:"refresh-backoff",until:G};return}function E5($,Z,X,J){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let z of X)if(!Z.limits.some((B)=>B.label===z))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:z},pullRequested:!0};let G=Z.limits.filter(MZ);for(let z of G)if(J6(z,J)===void 0)return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:z.scope,label:z.label},pullRequested:!0};for(let z of G){let B=J6(z,J);if(B!==void 0&&typeof z.resetsAt==="string")return{id:$,stage:1,gate:5,reason:"exhausted",window:{scope:z.scope,label:z.label},resetsAt:z.resetsAt,resetAtMs:B}}return}function h0($){let Z=$.scope??X0,X=$.requiredLabels??UZ,J=[],G=[],z=[];for(let j of $.rows){let D=o8(j.id,$,$.now);if(D){J.push(D);continue}if(j.kind==="api-key"){z.push({id:j.id,kind:j.kind});continue}let U=s(j.quota,Z),N=E5(j.id,U,X,$.now);if(N){G.push(N);continue}z.push({id:j.id,kind:j.kind,projection:U})}let B=new Map(z.flatMap((j)=>{let D=H$(j.projection,$.now);return D?[[j.id,D]]:[]})),Q=B.size>0&&B.size===z.length,Y=[];for(let j of z){let D=B.get(j.id);if(D===void 0)Y.push(j);else if(Q)Y.push({...j,lastPath:!0});else G.push({id:j.id,stage:2,reason:"budget-spent",...D})}let H=new Map($.rows.map((j,D)=>[j.id,D])),W=(j,D)=>(H.get(j.id)??0)-(H.get(D.id)??0);G.sort(W);let V=G.filter((j)=>("pullRequested"in j)).map((j)=>j.id);for(let j of V)$.requestPull?.(j);return{admitted:Y,refused:G,excluded:J,pulls:V}}var G6="main";function FZ($){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 f1($,Z,X=G6){if(Z==="roster"||!$.includes(X))return[...$];let J=$.filter((G)=>G!==X);return Z==="main-first"?[X,...J]:[...J,X]}function LZ($){let Z=h0($),X=new Set(Z.admitted.map((G)=>G.id));return{order:f1($.rows.map((G)=>G.id),$.placement??"roster",$.formerMainId).filter((G)=>X.has(G)&&$.killswitch?.get(G)!==!1),admission:Z}}function _Z($,Z,X){let J=Z.at(-1);if(J!==void 0){if(J.status===void 0||!X.includes(J.status))return}let G=new Set(Z.map((z)=>z.id));return $.find((z)=>!G.has(z))}function W$($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function OZ($,Z,X){let J=new Map;for(let[G,z]of $){if(G===X)continue;if(z.quotaCheckedAt!==Z.get(z.accountId))continue;J.set(z.accountId,(J.get(z.accountId)??0)+(z.inputBytes??0))}return J}var TZ=900000,e8=0.016666666666666666,CZ=0.000001;function z6($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function $9($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function Z9($){return $.limits.filter((Z)=>Z.kind==="reading").sort((Z,X)=>{let J=Z.windowMinutes!==void 0,G=X.windowMinutes!==void 0;if(J!==G)return J?-1:1;if(J&&G)return(X.windowMinutes??0)-(Z.windowMinutes??0);return 0})}function AZ($){let Z=($.classifyStatus??$9)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=z6($.quota,$.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||$.now-X>TZ)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let G of Z9($.quota)){let z=G.remainingPercent;if(typeof z==="number"&&Number.isFinite(z)&&z<=0)return{action:"migrate",reason:"exhausted",window:{scope:G.scope,label:G.label},...typeof G.resetsAt==="string"?{resetsAt:G.resetsAt}:{}}}let J=H$($.quota,$.now);if(J)return{action:"migrate",reason:"exhausted",resetsAt:J.resetsAt};return{action:"retain",reason:Z}}function PZ($,Z,X){let J=Math.max(0,$.remainingPercent-Z);if(J<=0)return 0;if(!$.resetsAt)return J;let G=Date.parse($.resetsAt);if(!Number.isFinite(G)||G<=X)return J;let z=Math.max((G-X)/3600000,e8);return J/z}function t8($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function I5($,Z){if(!$.quota)return;let X=z6($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>TZ)return;let J=Z9($.quota).map((B)=>PZ({remainingPercent:B.remainingPercent??Number.NaN,...B.resetsAt===void 0?{}:{resetsAt:B.resetsAt}},$.reservePercent[B.label]??0,Z)),G=$.quota.budget;if(G&&typeof G.remainingPercent==="number"&&Number.isFinite(G.remainingPercent))J.push(PZ({remainingPercent:G.remainingPercent,...G.resetsAt===void 0?{}:{resetsAt:G.resetsAt}},0,Z));let z=J.length>0?Math.min(...J):0;return z>0?{candidate:$,quotaCheckedAt:X,weight:z}:void 0}function X9($){let Z=$.candidates.filter((G)=>G.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((G)=>I5(G,$.now)).filter((G)=>G!==void 0);if(X.length>0){X.sort((z,B)=>{let Q=(($.pendingBytes.get(z.candidate.accountId)??0)+$.requestBytes)/Math.max(z.weight,CZ),Y=(($.pendingBytes.get(B.candidate.accountId)??0)+$.requestBytes)/Math.max(B.weight,CZ);return Q-Y||z.candidate.configuredOrder-B.candidate.configuredOrder||t8(z.candidate.accountId,B.candidate.accountId)});let G=X[0];if(G)return{accountId:G.candidate.accountId,quotaCheckedAt:G.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let J=[...Z].sort((G,z)=>{let B=(G.resetCreditsApplicable??0)>0?1:0;return((z.resetCreditsApplicable??0)>0?1:0)-B||G.configuredOrder-z.configuredOrder||t8(G.accountId,z.accountId)})[0];if(!J)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:J.accountId,quotaCheckedAt:z6(J.quota,J.quotaCheckedAt),source:"mode-fallback"}}function SZ($){let Z=h0($),X=new Map(Z.admitted.map((U)=>[U.id,U])),J=new Map(Z.refused.map((U)=>[U.id,U])),G=new Set(Z.excluded.map((U)=>U.id)),z=new Set($.rows.map((U)=>U.id)),B=$.pin!==void 0&&W$($.pin,z,$.identities?.get($.pin.accountId));if(B&&$.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 Q=$.pin?J.get($.pin.accountId):void 0,Y=B&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||Q?.reason==="exhausted"||Q?.reason==="budget-spent"),H=(U)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(U):$.rowReservePercent?.get(U.id))??$.reservePercent??{}},W=$.scope,V=$.rows.map((U,N)=>({row:U,configuredOrder:N})).filter(({row:U})=>!G.has(U.id)).map(({row:U,configuredOrder:N})=>{let K=$.killswitch?.get(U.id),M=$.resetCreditsApplicable?.get(U.id);return{accountId:U.id,quota:U.kind==="api-key"?void 0:X.get(U.id)?.projection??s(U.quota,W),reservePercent:H(U),configuredOrder:N,...M===void 0?{}:{resetCreditsApplicable:M},...K===void 0?{}:{killswitchPasses:K}}}),j=[],D=B?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(V.length>0){let U=X9({candidates:V,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!U)break;let N=J.get(U.accountId);if(N){j.push(N),V=V.filter((M)=>M.accountId!==U.accountId);continue}let K=$.identities?.get(U.accountId);return{outcome:"dispatch",accountId:U.accountId,source:U.source,...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt},pin:B&&!Y?{action:"retain"}:{action:"assign",pin:{accountId:U.accountId,inputBytes:$.requestBytes,...K===void 0?{}:{wireIdentity:K},...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt}}},refusedSelections:j,admission:Z}}return{outcome:"no-admissible-account",pin:D,refusedSelections:j,admission:Z}}import{appendFileSync as m5,chmodSync as w5,existsSync as bZ,renameSync as W9,statSync as p5}from"node:fs";import{open as u5}from"node:fs/promises";import{dirname as l5,resolve as d5}from"node:path";import{randomUUID as b5}from"node:crypto";import{lstat as B9,readFile as Q9,rename as x5,unlink as J9}from"node:fs/promises";import{dirname as i0,resolve as N0}from"node:path";var I=process.platform==="win32",G9=new Set;function RZ($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var z9;function g1(){return z9??=import("@cortexkit/private-files"),z9}class d extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,X){let J=X;super(`Private file refused at ${Z}: ${$} (${J?.reason??J?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:X});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=RZ(J),this.win32Code=J?.win32Code,this.reason=J?.reason}}async function D0($,Z,X){try{return await X()}catch(J){if(J instanceof d)throw J;throw new d($,Z,J)}}var k5;async function v0($,Z){$=N0($),Z??=k5,await D0($,"safe-parent",async()=>{let X=await(await g1()).verifySafeParent($,Z);if(X.ok===!1){if(X.reason==="io-error"||X.reason==="wrong-kind")await B9($);throw new d(X.level??X.path,"safe-parent",{...X,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function J0($,Z,X=!1){if($=N0($),Z==="directory")return v0($);await D0($,"verify",async()=>{let J=await g1(),G=await J.verifyOwnerOnly($),z=!1;if(!G.ok){let{reason:B}=G.refusal;if(B==="io-error")await J.verifyPrivatePath($,Z);if(X&&[J.EXTRA_ACE,J.NOT_PROTECTED,J.NULL_DACL,J.EMPTY_DACL].includes(B))await v0(i0($)),await J.securePrivatePath($,Z),z=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:B,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await J.verifyPrivatePath($,Z),z&&!G9.has($))G9.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function K0($,Z=!1,X){$=N0($),await D0($,"directory",async()=>{let J=await g1();try{return await B9($),await v0($,X)}catch(z){if(RZ(z)!=="ENOENT")throw z}let G=i0($);if(G===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await K0(G,!1,X);try{await J.createOwnerOnly($,{kind:"dir"})}catch(z){if(RZ(z)!=="EEXIST")throw z}await v0($,X)})}async function M0($,Z=!1){if(!I)return Q9($,"utf8");return(await EZ($,Z)).toString("utf8")}async function EZ($,Z=!1){if(!I)return Q9($);if($=N0($),Z)await v0(i0($)),await J0($,"file",!0);return D0($,"read",async()=>(await g1()).readOwnerOnly($))}async function h1($,Z){await v0(i0(N0($))),await D0($,"create",async()=>{await(await g1()).createPrivateFile(N0($),Z)})}async function Y9($){await v0(i0(N0($))),await D0($,"directory-create",async()=>{await(await g1()).createOwnerOnly(N0($),{kind:"dir"})})}async function IZ($,Z,X={}){$=N0($),Z=N0(Z);let J=X.now??(()=>performance.now()),G=J(),z=Math.min(G+500,X.deadline??1/0),B=[0,10,20,40,80,100],Q,Y=0;for(let W of B){if(J()>=z)break;if(W)await(X.sleep??((V)=>new Promise((j)=>setTimeout(j,V))))(Math.min(W,Math.max(0,z-J())));if(J()>=z)break;if(await X.beforeRename?.(),J()>=z)break;Y++;try{return await(X.rename??x5)($,Z),{attempts:Y,elapsedMs:J()-G}}catch(V){Q??=V;let j=V;if(!(j.win32Code!==void 0?j.win32Code===32||j.win32Code===33:["EBUSY","EPERM","EACCES"].includes(j.code??"")&&!j.reason))break}}let H=new d(Z,"rename",Q??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw H.attempts=Y,H.elapsedMs=J()-G,H}async function v1($,Z,X={}){$=N0($),await K0(i0($));try{await J0($,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}let J=N0(X.stagePath??`${$}.${b5()}.tmp`);if(i0(J)!==i0($))throw new d($,"stage-directory",{code:"EXDEV"});let G=!1,z=!1,B={attempts:0,elapsedMs:0},Q="stage-create",Y=(H)=>{try{X.onOutcome?.({path:$,stage:H?.stage??"published",published:z,fileDurable:z,durabilityConfirmed:!1,attempts:H?.attempts??B.attempts,elapsedMs:H?.elapsedMs??B.elapsedMs,...H&&{code:H.code,win32Code:H.win32Code}})}catch{}};try{if(await h1(J,Z),G=!0,Q="before-rename",B=await IZ(J,$,X),G=!1,z=!0,Q="published-callback",X.onRenamed?.(),Q="published-verify",await J0($,"file"),X.durable&&X.durability!=="file-only-on-windows")throw new d($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(H){let W=H instanceof d?H:new d($,Q,H);if(W.published=z,W.fileDurable=z,z)Object.assign(W,B);if(G){try{await J9(J)}catch{W.orphanPath=J}G=!1}throw Y(W),W}finally{if(G)await J9(J).catch(()=>{})}}var y5=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,f5=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function g5($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function I0($={}){let Z=[f5,...$.extraValuePatterns??[]].map((z)=>new RegExp(z.source,z.flags.includes("g")?z.flags:`${z.flags}g`));function X(z){let B=z.toLowerCase().replace(/[-_]/g,"");return y5.test(z)||B.includes("apikey")||B.endsWith("secret")||B.endsWith("password")||B.endsWith("token")&&!B.endsWith("tokens")||!!$.extraSecretKeys?.(B)}function J(z){let B=z,Q=[["name",z.name],["message",z.message],["stack",z.stack]];for(let H of["code","status","cause"])if(B[H]!==void 0)Q.push([H,B[H]]);let Y=new Set(Q.map(([H])=>H));for(let H of Object.entries(z))if(!Y.has(H[0]))Q.push(H);return Q}function G(z,B,Q,Y=0){if(typeof z==="string")return Z.reduce((H,W)=>H.replace(W,"***REDACTED***"),z);if(!z||typeof z!=="object")return z;if(Q.has(z))return"[Circular]";Q.add(z);try{if(Array.isArray(z))return z.map((V)=>G(V,B,Q,Y));let H=g5(z);if(H&&Y>=8)return"[Truncated]";let W=H?Y+1:Y;return Object.fromEntries((H?J(z):Object.entries(z)).map(([V,j])=>[V,B&&X(V)?"***REDACTED***":G(j,B,Q,W)]))}finally{Q.delete(z)}}return{redact:(z)=>G(z,!0,new WeakSet),redactStrings:(z)=>G(z,!1,new WeakSet)}}var H9=I0(),h5=H9.redact,v5=H9.redactStrings;var B6={error:0,warn:1,info:2,debug:3,trace:4},U9=5242880,j9=3;function xZ($){try{w5($,384)}catch{}}function c5($){try{if(!(bZ($)&&p5($).size>=U9))return;for(let X=j9-1;X>=1;X--)if(bZ(`${$}.${X}`)){let J=`${$}.${X+1}`;W9(`${$}.${X}`,J),xZ(J)}let Z=`${$}.1`;W9($,Z),xZ(Z)}catch{}}async function m0($){let{file:Z,handle:X}=$;if($.file=void 0,$.handle=void 0,Z&&X)await D0(Z,"log-close",()=>X.close())}async function V9($,Z){await K0(l5(Z));try{await J0(Z,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X;try{await h1(Z,"")}catch(J){if(J.code!=="EEXIST")throw J;await J0(Z,"file",!0)}}return $.handle=await D0(Z,"log-open",()=>u5(Z,"a")),$.file=Z,$.handle}async function s5($,Z,X){Z=d5(Z);try{if($.file!==Z)await m0($);let J=$.handle??await V9($,Z);if((await D0(Z,"log-stat",()=>J.stat())).size>=U9){await m0($);for(let z=j9-1;z>=0;z--){let B=z===0?Z:`${Z}.${z}`,Q=`${Z}.${z+1}`;try{await J0(B,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await J0(Q,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await IZ(B,Q),await J0(Q,"file")}J=await V9($,Z)}await D0(Z,"log-append",()=>J.appendFile(X,"utf8"))}catch(J){throw await m0($).catch(()=>{}),J}}function i5($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function a5($){let Z,X,J,G=I0(),z,B=[],Q,Y=Promise.resolve(),H,W={};function V(q){let L=Y.then(q);return Y=L.catch((S)=>{H=S}),L}function j(q){if(I&&q.file!==Z)V(()=>m0(W)).catch(()=>{});Z=q.file,X=q.level,G=I0(q),z=q.captureSink}function D(q){if(q===void 0||q in B6)J=q}function U(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function N(){if(J)return J;let q=typeof X==="function"?X():X;if(q&&q in B6)return q;return"info"}function K(q=!0){if(Q)clearTimeout(Q),Q=void 0;if(!B.length){if(I)return V(async()=>{if(q)await m0(W);if(H)throw H});return}let L;try{L=U()}catch{if(B=[],I&&q)return V(()=>m0(W));return}let S=B.join("");if(B=[],!L){if(I&&q)return V(()=>m0(W));return}if(I)return V(async()=>{try{await s5(W,L,S)}finally{if(q)await m0(W)}});try{if(c5(L),bZ(L))xZ(L);m5(L,S,{encoding:"utf8",mode:384})}catch{}}function M(){if(!Q)Q=setTimeout(()=>{Q=void 0;let q=K(!1);if(q instanceof Promise)q.catch(()=>{})},500)}function P(q,L,S,A){if(Z===void 0&&z===void 0)return;try{if(B6[L]>B6[N()])return;let x=G.redactStrings(S),w;try{w=G.redact(A)}catch{w="[unserializable]"}let y=`[${new Date().toISOString()}] ${L.toUpperCase()} [${q}] ${x}`+(A===void 0?"":i5(w))+`
2
- `;try{z?.({channel:q,level:L,message:x,data:w})}catch{}if(Z===void 0)return;if(B.push(y),B.length>=50){let f=K(!1);if(f instanceof Promise)f.catch(()=>{})}else M()}catch{}}function E(q){return{error:(L,S)=>P(q,"error",L,S),warn:(L,S)=>P(q,"warn",L,S),info:(L,S)=>P(q,"info",L,S),debug:(L,S)=>P(q,"debug",L,S),trace:(L,S)=>P(q,"trace",L,S)}}function F(){if(I)V(()=>m0(W)).catch(()=>{});if(H=void 0,B=[],Q)clearTimeout(Q),Q=void 0;Z=void 0,X=void 0,J=void 0,G=I0(),z=void 0}if($)j($);return{configure:j,createLogger:E,setLogLevel:D,flushLogs:K,reset:F}}var n5=a5();function a($){return n5.createLogger($)}class g 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 Q6 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 m1="identity-contradicted: ",kZ="duplicate-identity";function a0($,Z,X){let J=$.rosterRow(Z);if(!J)return;J.enabled=!1;let G=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0},z=typeof G.disabledReason==="string"&&G.disabledReason.startsWith("identity-contradicted: ");$.setEntry(Z,{...G,disabledReason:z?G.disabledReason:X})}function V$($,Z){let X=$.rosterRow(Z);if(!X)return;X.enabled=!0;let J=$.entry(Z);if(J&&"disabledReason"in J){let G={...J};delete G.disabledReason,$.setEntry(Z,G)}}function w1($,Z){let X=$.rows().filter((G)=>G.invalid===void 0&&!G.staged&&G.type==="oauth"&&G.enabled&&G.identity===Z),J=[];for(let G of X.slice(1))a0($,G.id,"duplicate-identity"),J.push(G.id);return J}function N1($,Z,X){let J=$.rosterRow(Z);if(!J)return[];return J.accountId=X,w1($,X)}import{setTimeout as PX}from"node:timers/promises";import{randomUUID as D9}from"node:crypto";import{mkdir as ZX,open as Y6,rename as XX,rm as JX}from"node:fs/promises";import{dirname as yZ}from"node:path";class U$ extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function F0($,Z,X={}){await fZ($,Z,X)}async function fZ($,Z,X,J){if(I)return v1($,X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
3
- `,{beforeRename:X.beforeRename,stagePath:`${$}.${(X.stageName??D9)()}.tmp`,onRenamed:J,durable:X.durable,durability:X.durability,onOutcome:X.onOutcome});await ZX(yZ($),{recursive:!0});let G=`${$}.${(X.stageName??D9)()}.tmp`,z,B=!1;try{if(z=await Y6(G,"wx",384),B=!0,await z.writeFile(X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
4
- `,"utf8"),await z.chmod(384),X.durable)try{await z.sync()}catch(Q){throw new U$(Q)}if(await z.close(),z=void 0,await X.beforeRename?.(),await XX(G,$),B=!1,J?.(),X.durable){let Q=await Y6(yZ($),"r");try{await Q.sync()}catch(Y){throw new U$(Y)}finally{await Q.close()}}}finally{if(await z?.close().catch(()=>{}),B)await JX(G,{force:!0}).catch(()=>{})}}async function gZ($){if(I){await J0($,"file");let J=new d($,"directory-sync-unsupported",{code:"ENOTSUP"});throw J.published=!0,J}let Z=await Y6($,"r");try{await Z.sync()}finally{await Z.close()}let X=await Y6(yZ($),"r");try{await X.sync()}finally{await X.close()}}import{randomUUID as H6}from"node:crypto";import{mkdir as K9,open as _9,readFile as q9,rename as N9,rm as W6,stat as M9}from"node:fs/promises";import{dirname as hZ,join as F9}from"node:path";async function L9($,Z){let X=await _9($,"wx",384);try{await X.writeFile(Z,"utf8")}finally{await X.close()}}var GX=globalThis.setTimeout.bind(globalThis),zX=globalThis.clearTimeout.bind(globalThis);function vZ($){let Z=$?.code;return Z==="ENOENT"||!I&&(Z==="EINVAL"||Z==="ENOTDIR")}function e($){return BX({...$,now:Date.now})}async function BX($){let Z=mZ($.path,$.name),X=F9(Z,"owner.json"),J=H6(),G=$.now??Date.now,z=null,B=!1,Q=!1,Y,H,W=new Promise((C)=>{H=C});function V(C){try{let T=$.onRenewalTimer?.(C);if(T&&(typeof T==="object"||typeof T==="function")&&"then"in T&&typeof T.then==="function")Promise.resolve(T).catch(()=>{})}catch{}}function j(){if(!z)return;zX(z),z=null,V("cancelled")}function D(C,T){if(Y||B)return;Y=Object.freeze({reason:C,expectedOwnerId:J,...typeof T?.ownerId==="string"?{observedOwnerId:T.ownerId}:{},...typeof T?.expiresAt==="number"?{observedExpiresAt:T.expiresAt}:{}}),j(),H(Y)}let U,N=null,K=`${Z}.evicting`,M=F9(K,"owner.json"),P=H6(),E=5000,F=8;async function q(){if(I)try{return JSON.parse(await M0(Z,!0))}catch(C){if(C.code!=="EISDIR"&&C.reason!=="wrong-kind")throw C;return await J0(Z,"directory",!0),JSON.parse(await M0(X,!0))}try{return JSON.parse(await q9(Z,"utf8"))}catch(C){if(C.code!=="EISDIR")throw C;return JSON.parse(await q9(X,"utf8"))}}async function L(){if(I){let u=await q(),o=Number(u?.expiresAt)-G();await v1(Z,`${JSON.stringify({ownerId:J,expiresAt:G()+$.ttlMs})}
5
- `,{deadline:performance.now()+Math.max(0,o),beforeRename:async()=>{let t$=await q();if(t$?.ownerId!==J||!(Number(t$?.expiresAt)>G())||!await h())throw new n0({target:$.path,name:$.name})}});return}let C=`${Z}.${H6()}.tmp`,T,b=!1;try{T=await _9(C,"wx",384),b=!0,await T.writeFile(`${JSON.stringify({ownerId:J,expiresAt:G()+$.ttlMs})}
6
- `,"utf8"),await T.chmod(384),await T.close(),T=void 0;let u=await q();if(u?.ownerId!==J||!(Number(u?.expiresAt)>G())||!await h())throw new n0({target:$.path,name:$.name});await N9(C,Z),b=!1}finally{if(await T?.close().catch(()=>{}),b)await W6(C,{force:!0}).catch(()=>{})}}async function S(){let C=`${JSON.stringify({ownerId:J,expiresAt:G()+$.ttlMs})}
7
- `;if(I)await h1(Z,C);else await L9(Z,C)}async function A(C){let T=C.code;if(T==="EEXIST"){if(I)await q();return!0}if(T==="EISDIR"){if(I)await J0(Z,"directory",!0),await M0(X,!0);return!0}return!1}async function x(){if(I)await K0(hZ(Z));try{return await S(),!0}catch(C){let T=C.code;if(await A(C))return!1;if(T==="ENOENT"){if(I)await K0(hZ(Z));else await K9(hZ(Z),{recursive:!0});try{return await S(),!0}catch(b){if(await A(b))return!1;throw b}}throw C}}async function w(){await new Promise((C)=>setTimeout(C,Math.floor(Math.random()*4)))}async function y(C=!0){if(C&&$.onStep)await $.onStep("lock-read-ready");let T;try{T=await q()}catch(u){if(I&&u.code!=="ENOENT")throw u}let b=Number(T?.expiresAt);if(Number.isFinite(b)&&b>G())return{status:"live"};if(typeof T?.ownerId==="string"&&Number.isFinite(b))return{status:"stale",identity:{kind:"owner",ownerId:T.ownerId,expiresAt:b}};try{let u=await M9(Z),o=Number.isFinite(b)?b:u.mtimeMs+$.ttlMs;if(o>G())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:u.dev,ino:u.ino,mtimeMs:u.mtimeMs,expiresAt:o}}}catch(u){if(u.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw u}}function f(C,T){if(T.status!=="stale")return!1;let b=T.identity;if(C.kind==="owner"&&b.kind==="owner")return C.ownerId===b.ownerId&&C.expiresAt===b.expiresAt;return C.kind==="stat"&&b.kind==="stat"&&C.dev===b.dev&&C.ino===b.ino&&C.mtimeMs===b.mtimeMs&&C.expiresAt===b.expiresAt}async function h(){try{return JSON.parse(await M0(M,I))?.ownerId===P}catch(C){if(I&&C.code!=="ENOENT")throw C;return!1}}async function r(C){if(I)await D0(C,"remove",()=>W6(C,{recursive:!0,force:!0}));else await W6(C,{recursive:!0,force:!0}).catch(()=>{})}async function c(){if(await h())await r(K)}async function r$(){if(I)await Y9(K);else await K9(K);try{let C=`${JSON.stringify({ownerId:P,createdAt:G()})}
8
- `;if(I)await h1(M,C);else await L9(M,C)}catch(C){if(vZ(C))return!1;throw await c(),C}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function x1(){let C;try{C=await M9(K)}catch(b){if(b.code==="ENOENT")return"missing";throw b}if(I)await J0(K,"directory",!0);if(C.mtimeMs+E>G())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let T=`${K}.${H6()}`;try{await N9(K,T)}catch(b){if(b.code==="ENOENT")return"missing";throw b}if($.onStep)await $.onStep("stale-marker-claimed");return await r(T),"recovered"}async function o$(C){try{if(!await r$())return!1}catch(T){if(T.code==="EEXIST"){if(I){await J0(K,"directory",!0);try{await M0(M,!0)}catch(b){if(b.code!=="ENOENT")throw b}}return!1}throw T}try{await C()}finally{await c()}return!0}async function v(){for(let C=0;C<F;C++){if($.onStep)await $.onStep("relinquish-read");let T;try{T=await q()}catch(b){if(I)throw b;return}if(T?.ownerId!==J)return;try{await W6(Z,{recursive:!0,force:!0});return}catch(b){if(I)throw b;await w()}}}function g0(){if(!$.renew||B||Y)return;let C=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(z=GX(()=>{z=null;let T=(async()=>{let b=!B;try{if(!await o$(async()=>{let o=await q(),t$=G();if(B||Y){b=!1;return}if(o?.ownerId!==J){D("taken-over",o),b=!1;return}if(!(Number(o?.expiresAt)>t$)){D("expired",o),b=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(B||Y){b=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-fenced");if(B||Y){b=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-ready");if(B||Y){b=!1;return}if(await L(),$.onStep)await $.onStep("renewal-write-finished");if(!await h()){D("marker-lost"),b=!1,await v();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(u){if(I&&u instanceof d)U=u,D("renewal-failed"),b=!1;try{let o=await q();if(o?.ownerId!==J)D("taken-over",o);else if(!(Number(o?.expiresAt)>G()))D("expired",o)}catch{D("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(b&&!B&&!Y)g0()}})();N=T,T.finally(()=>{if(N===T)N=null})},C),"unref"in z)z.unref();V("scheduled")}function h8(){try{let C=$.onContended?.();if(C&&(typeof C==="object"||typeof C==="function")&&"then"in C&&typeof C.then==="function")Promise.resolve(C).catch(()=>{})}catch{}return null}let D1=await x();if(!D1)for(let C=0;C<F;C++){if(D1=await x(),D1)break;let T=await y();if(T.status==="live")return h8();if(T.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await r$()){await w();continue}}catch(b){if(b.code!=="EEXIST")throw b;if(await x1()==="fresh")return null;await w();continue}try{let b=await y();if(b.status==="live")return h8();if(!f(T.identity,b))continue;if(!await h())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await h())return null;let u=await y(!1);if(!f(T.identity,u))continue;if(await r(Z),!await h())return null;if($.onStep)await $.onStep("stale-lock-removed");if(D1=await x(),!D1)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await h())return await v(),D1=!1,null;break}finally{await c()}}if(!D1)return null;return g0(),{ownerId:J,whenLost:()=>W,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(U)throw U;let C;try{let T=await q();if(C=T,!B&&!Y&&T?.ownerId===J&&Number(T?.expiresAt)>G())return;D(T?.ownerId!==J?"taken-over":"expired",T)}catch(T){if(D("unreadable"),I&&T instanceof d)throw T}throw new n0({target:$.path,name:$.name,expectedOwnerId:J,...typeof C?.ownerId==="string"?{observedOwnerId:C.ownerId}:{},...typeof C?.expiresAt==="number"?{observedExpiresAt:C.expiresAt}:{}})},release:async()=>{if(I&&Q)return;B=!0,j(),await N;for(let C=0;C<F;C++){try{let T=!1;if(await o$(async()=>{let u;try{u=await q()}catch(o){if(I&&o.code==="ENOENT"){T=!0;return}throw o}if(u?.ownerId!==J){T=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await h())return;await r(Z),T=!0})){if(I&&!T)throw new d(Z,"release-not-confirmed",{code:"EIO"});Q=T;return}await x1()}catch(T){if(I)throw T;return}await w()}if(I)throw new d(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}function mZ($,Z){return`${$}.${Z}.lock`}class M1 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class n0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function wZ($,Z,X){let J=performance.now();for(;;){let G=await e({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(G)try{return await X(G)}finally{await G.release()}let z=Z.timeoutMs-(performance.now()-J);if(z<=0)throw new M1({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((B)=>setTimeout(B,Math.min(25,Math.ceil(z))))}}import{AsyncLocalStorage as QX}from"node:async_hooks";var O9=new QX;function G0($){if(O9.getStore()!==void 0)throw new Q6($)}function b0($,Z){return O9.run($,async()=>await Z())}async function C9($,Z,X,J,G){if(!Z)return;try{await b0($,()=>Z(X,J))}catch(z){G?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:X,error:z instanceof Error?z.message:String(z)})}}var pZ=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function YX($,Z,X){let J=(B)=>{try{let Q=X.onLockEvent?.({type:B,name:$.name,path:$.path});if(Q&&(typeof Q==="object"||typeof Q==="function")&&"then"in Q&&typeof Q.then==="function")Promise.resolve(Q).catch(()=>{})}catch{}},G={...Z,...HX($)},z=performance.now();for(;;){let B=await e({name:$.name,path:$.path,ttlMs:G.ttlMs,renew:G.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(H)=>X.onRenewalTimer?.({name:$.name,path:$.path},H)}:{},...G.renewIntervalMs!==void 0?{renewIntervalMs:G.renewIntervalMs}:{},...X.onLockStep?{onStep:(H)=>X.onLockStep?.({name:$.name,path:$.path},H)}:{}});if(B){J("acquired");let H={name:$.name,path:$.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),J("released")}};try{await H.assertOwned()}catch(W){throw await H.release(),W}return H}let Q=G.timeoutMs-(performance.now()-z);if(Q<=0)throw new M1({target:$.path,name:$.name,timeoutMs:G.timeoutMs});let Y=Math.floor(Math.random()*(G.retryMs+1));await new Promise((H)=>setTimeout(H,Math.min(G.retryMs+Y,Q)))}}function HX($){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 r0{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await YX($,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 F1($,Z,X){if(X!==void 0)throw new g({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 j$}from"node:crypto";var p="commonAuthPool",o0=1,P0="rows",V6="retiredEpochs",D$=1,uZ=300000,m=p;function WX($){let Z=JSON.parse(JSON.stringify($)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(O(J))return`{${Object.keys(J).sort().map((G)=>`${JSON.stringify(G)}:${X(J[G])}`).join(",")}}`;return JSON.stringify(J)};return X(Z)}function L1($){return j$("sha256").update(WX($)).digest("hex")}function P9($){if(!O($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function VX($){if(!O($)||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 Y0="commonAuthProviderState";function O($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var UX=new Set(["__proto__","constructor","prototype"]);function p1($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(UX.has($))return"id is a reserved object key";return}function lZ($){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 T9($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function t0($){return j$("sha256").update(T9($)).digest("hex")}function x0($){return j$("sha256").update(`credential-stamp\x00${T9($)}`).digest("hex")}function w0($){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 j$("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function dZ($,Z,X,J={}){return{credentialEpoch:Z,digest:x0($),dispatch:w0($),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function u1($,Z){let X=$?.credentialBound?$.credentialBound(Z):Z;return j$("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function K$($,Z,X,J){if(!Z||X===void 0)return;if(!O($)||!Object.hasOwn($,Y0))return;let G=V0($[m]);if(!G||G.providerState===void 0||G.digest!==x0(Z)||G.credentialEpoch!==X||G.binding?.identity!==J)return;return G.providerState}function $0($){return Number.isSafeInteger($)&&$>=1}function V0($){if(!O($))return;let Z=$.credentialEpoch;if(!$0(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 $?VX($.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 G=$.binding;if(!O(G))return;if("identity"in G&&(typeof G.identity!=="string"||!G.identity))return;if("baseURL"in G&&!lZ(G.baseURL))return;if("authHeader"in G&&G.authHeader!=="authorization-bearer"&&G.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...J,binding:{...typeof G.identity==="string"?{identity:G.identity}:{},...typeof G.baseURL==="string"?{baseURL:G.baseURL.trim()}:{},...G.authHeader==="authorization-bearer"||G.authHeader==="x-api-key"?{authHeader:G.authHeader}:{}}}}function jX($,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 DX($,Z,X,J){if(!$)return"none";if(!O(J)||!Object.hasOwn(J,m))return"missing";let G=V0(J[m]);if(!G)return"malformed";if(G.digest!==x0($))return"mismatched";if(G.dispatch===void 0)return"legacy";if(G.credentialEpoch!==Z)return"mismatched";if(!G.binding||!jX(G.binding,$,X))return"mismatched";if(G.dispatch!==w0($))return"mismatched";return"bound"}function A9($){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(!O(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(!(p in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let X=Z[p];if(!O(X))return{status:"error",reason:`${p} is not an object`};let J=X.schemaVersion;if(typeof J!=="number"||!Number.isInteger(J)||J<1)return{status:"error",reason:`${p}.schemaVersion is invalid`};if(J>o0)return{status:"error",reason:`${p}.schemaVersion ${J} is newer than ${o0}`};if(P0 in X&&!O(X[P0]))return{status:"error",reason:`${p}.${P0} is not an object`};return{status:"ready",exists:!0,config:Z}}function S9($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!O($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!O($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function l1($){return Array.isArray($.accounts)?$.accounts:[]}function R9($){let Z=$[p];if(!O(Z))return{};let X=Z[P0];return O(X)?X:{}}function KX($){return O($.accounts)?$.accounts:{}}function qX($){if(!O($))return"not an object";let Z=p1($.id);if(Z)return Z;if($.type==="api")return lZ($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function NX($,Z){if(!O($))return;let X=$.credentialEpoch;if(!$0(X))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let J="quota"in $&&Z.decode?Z.decode($.quota):$.quota;if("quota"in $&&!Z.validate(J))return;if("staged"in $&&!P9($.staged))return;return{credentialEpoch:X,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:J}:{}}}function MX($,Z){if(!O(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 U6($,Z){return l1($).find((X)=>O(X)&&X.id===Z)}function E9($){if(!O($[p]))$[p]={};return $[p]}function cZ($){let Z=E9($);if(!O(Z[P0]))Z[P0]={};return Z[P0]}function e0($,Z){let X=R9($),J=Object.hasOwn(X,Z)?X[Z]:void 0;return O(J)?J:void 0}function j6($,Z,X){Object.defineProperty(cZ($),Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function I9($,Z){let X=$[p];if(!O(X))return;let J=X[V6];if(!O(J)||!Object.hasOwn(J,Z))return;let G=J[Z];return $0(G)?G:void 0}function b9($,Z){let X=e0($,Z)?.credentialEpoch;return $0(X)?X:void 0}function D6($,Z){return Math.max(I9($,Z)??0,b9($,Z)??0)+1}function x9($,Z){let X=[...Z];if(X.length===0)return;let J=E9($),G=O(J[V6])?J[V6]:{},z={},B=(Q,Y)=>Object.defineProperty(z,Q,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[Q,Y]of Object.entries(G))if($0(Y))B(Q,Y);for(let Q of X)B(Q,Math.max(I9($,Q)??0,b9($,Q)??1));J[V6]=z}function $1($,Z,X,J){let G=R9($),z=KX(Z),B=new Set,Q=[];for(let Y of l1($)){let H=qX(Y),W=O(Y)&&typeof Y.id==="string"?Y.id:void 0,V=W===void 0?void 0:G[W],j=O(V)&&Object.hasOwn(V,"staged"),D=j?P9(V.staged):void 0;if(H||!O(Y)||W===void 0||B.has(W)){if(W!==void 0&&!B.has(W))B.add(W);if(W!==void 0)Q.push({id:W,type:O(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(G,W),candidate:!1,invalid:"roster",stamp:"none",...D?{staged:D}:{}});continue}B.add(W);let U=Y.type==="api"?"api":"oauth",N=Object.hasOwn(G,W),K=N?NX(G[W],X):void 0,M=MX(Y,z[W]),P=Y.enabled!==!1,E=K?K.credentialEpoch:N?void 0:1,F=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,q={id:W,type:U,enabled:P,needsFirstReading:K?K.needsFirstReading:U==="oauth",hasEntry:N,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},...F!==void 0?{identity:F}:{},...M?{credential:M,fingerprint:t0(M)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...D?{staged:D}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...FX(z[W],M,E,F,J),stamp:DX(M,E,F,z[W])};if(N&&!K)q.invalid="entry";else q.candidate=P&&M!==void 0&&!j;Q.push(q)}return Q}function FX($,Z,X,J,G){if(!O($)||!Object.hasOwn($,Y0))return{};let z=K$($,Z,X,J);if(z===void 0)return{providerStateDropped:"uncovered"};let B=$[Y0];if(!G?.validate(B))return{providerStateDropped:"invalid"};if(u1(G,B)!==z)return{providerStateDropped:"uncovered"};return{providerState:B}}function l($){return $.identity??$.id}function q$($,Z){if($===void 0||$>Z+uZ)return Z;return Math.max(Z,$+1)}function sZ($,Z){return q$($,Z)>Z+uZ}function d1($){let{id:Z,credential:X,identity:J,label:G,addedAt:z}=$;return{id:Z,...G!==void 0?{label:G}:{},type:X.type,addedAt:z,...J!==void 0?{accountId:J}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}}}function k9($,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 y9($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function f9($,Z={}){if(!O($))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)&&!lZ($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var K6="transition",g9="transitionMark";function LX($){if(!O($))return;let Z=$[K6];if(!O(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 N$($,Z,X){if(X.enabled)V$($,Z);else a0($,Z,X.reason??"");if(!$.rosterRow(Z))return;let J=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...J,[g9]:X.mark}),!X.enabled)return;let G=$.rows().find((z)=>z.id===Z);if(G?.type==="oauth"&&G.identity!==void 0)w1($,G.identity)}function _X($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function OX($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function CX($,Z,X,J={}){let G=O(Z.accounts)?Z.accounts:{},z=new Map;for(let B of $1($,Z,X)){if(B.invalid||B.staged||!B.credential)continue;let Q=Object.hasOwn(G,B.id)?G[B.id]:void 0;if(!O(Q))continue;let Y=V0(Q[m]);if(!Y?.binding)continue;if(Y.digest!==x0(B.credential))continue;let H=B.credentialEpoch??1;if(Y.credentialEpoch>H){if(!OX(Y))continue;if(J.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==w0(_X(B.credential,Y.binding)))continue}z.set(B.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===H&&Y.dispatch!==void 0&&Y.dispatch===w0(B.credential)&&Y.binding.identity!==void 0&&B.identity===void 0)z.set(B.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===H&&Y.binding.identity===B.identity){if(J.requireCredentialStamps&&Y.dispatch!==w0(B.credential))continue;let W=LX(Q[m]);if(W&&e0($,B.id)?.[g9]!==W.mark)z.set(B.id,{kind:"transition",transition:W})}}return z}function iZ($,Z,X,J){let z={...$.entry(Z)??{},credentialEpoch:X,needsFirstReading:!0};if(delete z.quota,J.identity!==void 0&&typeof z.disabledReason==="string"&&z.disabledReason.startsWith(m1))delete z.disabledReason;$.setEntry(Z,z);let B=$.rosterRow(Z);if(!B)return;if(J.identity!==void 0)B.accountId=J.identity;else delete B.accountId;if(J.baseURL!==void 0)B.baseURL=J.baseURL;if(J.authHeader!==void 0)B.authHeader=J.authHeader}function aZ($,Z,X,J={}){let G=CX($,Z,X,J);if(G.size===0)return{config:$,torn:[]};let z=structuredClone($),B={rows:()=>$1(z,Z,X),rosterRow:(Q)=>U6(z,Q),entry:(Q)=>e0(z,Q),setEntry:(Q,Y)=>j6(z,Q,Y)};for(let[Q,Y]of G)if(Y.kind==="replace")iZ(B,Q,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[Q,Y]of G)if(Y.kind==="identity")N1(B,Q,Y.identity);else if(Y.kind==="transition")N$(B,Q,Y.transition);else if(Y.stamp.binding.identity!==void 0)w1(B,Y.stamp.binding.identity);return{config:z,torn:[...G.keys()]}}function nZ($,Z,X,J={}){let{config:G,torn:z}=aZ($,Z,X,J),B=$1(G,Z,X,J.providerState);for(let Q of B){if(z.includes(Q.id))Q.torn=!0,Q.candidate=!1;if(J.requireCredentialStamps&&Q.stamp!=="bound")Q.unbound=!0,Q.candidate=!1}return B}async function rZ($){try{return await M0($,I)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function h9($){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 rZ($.configPath),J=await rZ($.statePath),G=await rZ($.configPath);if(X!==G){if(Z<2)await PX(2+Math.floor(Math.random()*4));continue}let z=A9(h9(X));if(z.status==="error")return{status:"error",file:"config",reason:z.reason};let B=S9(h9(J));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(z.status==="pending-migration")return{status:"pending-migration",config:z.config};return{status:"ready",configExists:z.exists,stateExists:B.exists,config:z.config,state:B.state,rows:nZ(z.config,B.state,$.codec,{requireCredentialStamps:$.requireCredentialStamps===!0,...$.providerState?{providerState:$.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function T0($,Z,X,J="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:J,kind:"snapshot-contended",retryable:!0,message:$.reason});return new g({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 v9{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,X,J,G){this.ctx=$,this.snapshot=Z,this.locks=X,this.progress=J,this.info=G,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return nZ(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($)?.[m];return O(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){F1(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),U6(this.config,$)}dropRosterRows($){let Z=this.roster(),X=Z.filter((J)=>!(O(J)&&J.id===$));return this.config.accounts=X,Z.length-X.length}entries(){return cZ(this.config)}entry($){return this.entries(),e0(this.config,$)}setEntry($,Z){j6(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=aZ(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=O(this.state.accounts)?this.state.accounts:{},X=Object.hasOwn(Z,$)?Z[$]:void 0;return O(X)?X:void 0}dropStateAccount($){if(O(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!O(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 Y of Z)if(O(Y)&&typeof Y.id==="string")X.add(Y.id);let J=new Set;for(let Y of l1(this.snapshot.config))if(O(Y)&&typeof Y.id==="string"&&!X.has(Y.id))J.add(Y.id);for(let Y of Object.keys(this.entries()))if(!X.has(Y))J.add(Y);x9(this.config,J);let G=this.entries(),z={};for(let[Y,H]of Object.entries(G))if(X.has(Y))Object.defineProperty(z,Y,{value:H,enumerable:!0,writable:!0,configurable:!0});let B=this.config[p],Q={...this.config,version:D$,accounts:Z,[p]:{...B,schemaVersion:o0,[P0]:z}};await this.write(this.ctx.configPath,Q,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let Y of J)this.ctx.removedIds.add(Y);this.config=Q}),this.config=Q}async commitState($,Z={}){let X={...this.state,version:D$,accounts:O(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 gZ(this.ctx.statePath)}catch($){throw new g({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 gZ(this.ctx.configPath)}async write($,Z,X,J=!0,G=!1,z){await fZ($,Z,{durable:G,beforeRename:async()=>{await this.ctx.onStep?.(`before-${X}-write`,this.info),await this.locks.assertAll()}},()=>{if(J)this.progress.writes++;z?.()}),await this.ctx.onStep?.(`after-${X}-write`,this.info)}}async function m9($,Z){let X=new r0($.lockDefaults,$.lockEnv),J={writes:0};try{for(let Q of $.storeLocks)await X.acquire(Q);let G=await H0($);if(G.status==="error")throw T0(G,"initialize",void 0);if(G.status==="ready")return"already-ready";let z={};for(let[Q,Y]of Object.entries(G.config))if(!Z.includes(Q))z[Q]=Y;z.version=D$,z[p]={schemaVersion:o0,[P0]:{}};let B={operation:"initialize",rowId:void 0};return await F0($.configPath,z,{beforeRename:async()=>{await $.onStep?.("before-config-write",B),await X.assertAll()}}),J.writes++,await $.onStep?.("after-config-write",B),"initialized"}catch(G){throw c1(G,"initialize",void 0,J)}finally{await X.releaseAll()}}async function n($,Z,X,J,G,z={}){let B=Z.held.length;try{for(let H of $.storeLocks)await Z.acquire(H);let Q=await H0($);if(Q.status!=="ready")throw T0(Q,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let Y=new v9($,Q,Z,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))Y.assertNotStaged(J.rowId);if(z.completeTorn??!0)await Y.completeTorn();return await G(Y)}finally{await Z.releaseTo(B)}}function c1($,Z,X,J){let G=Z==="pull"?"pull":J.writes>0?"after-first-write":"before-first-write",z=G==="after-first-write"?J.committed:void 0;if(Z==="publishRoster"&&J.publicationDecided)return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:G,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 U$)return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:G,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof g){if($.phase===G&&$.rowId===X&&$.operation===Z&&$.committed===z)return $;return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:$.kind==="after-persist-hook"?$.phase:G,retryable:$.retryable,kind:$.kind,...$.committed??z?{committed:$.committed??z}:{},message:$.message,...$.cause!==void 0?{cause:$.cause}:{}})}let B={operation:Z,...X!==void 0?{rowId:X}:{},phase:G,...z?{committed:z}:{},cause:$};if($ instanceof n0)return new g({...B,retryable:!0,kind:"lock-ownership",message:G==="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 M1)return new g({...B,retryable:!0,kind:"lock-contention",message:$.message});return new g({...B,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function z0($,Z,X,J,G){let z=new r0($.lockDefaults,$.lockEnv),B={writes:0};try{return await G(z,B)}catch(Q){let Y=c1(Q,Z,X,B);if(Y.kind!=="after-persist-hook")await C9(Z,J,X,Y,$.logger);throw Y}finally{await z.releaseAll()}}function q0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(l(Z))}`,path:$.ctx.statePath}}async function p0($,Z,X){let J=await H0($.ctx);if(J.status!=="ready")throw T0(J,Z,X);let G=J.rows.find((H)=>H.id===X),z=e0(J.config,X),B=J.state.accounts,Q=O(B)&&Object.hasOwn(B,X)?B[X]:void 0,Y=O(Q)?Q[m]:void 0;if(G&&!["enable","disable"].includes(Z)&&z&&Object.hasOwn(z,"staged"))F1(Z,X,z.staged);if(!G&&O(Y)&&Object.hasOwn(Y,"staged"))F1(Z,X,Y.staged);if(!G)throw A0(Z,X);return{result:J,row:G}}function A0($,Z){return new g({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function W0($,Z){if(Z.unbound)throw _($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function _($,Z,X,J,G=!1){return new g({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:G,kind:X,message:J})}async function q6($,Z,X,J){let{ctx:G}=$,z=new r0(G.lockDefaults,G.lockEnv),B={writes:0};try{if(!$0(X?.credentialEpoch))throw _("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await n(G,z,B,{operation:"pull",rowId:Z},async(Q)=>{Q.assertNotStaged(Z);let Y=Q.row(Z);if(!Y)throw A0("pull",Z);if(Y.invalid)throw _("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!Y.credential)throw _("pull",Z,"no-credential",`row ${Z} holds no credential`);W0("pull",Y);let H=Q.entry(Z);if(Y.torn||!H||H.credentialEpoch!==X.credentialEpoch||Y.identity!==X.identity)throw new g({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=G.codec.merge(H.quota,J);if(!G.codec.validate(W))throw _("pull",Z,"invalid-quota","the quota codec rejected the merged map");Q.setEntry(Z,{...H,quota:W,needsFirstReading:!1}),await Q.commitConfig()},{completeTorn:!1})}catch(Q){throw c1(Q,"pull",Z,B)}finally{await z.releaseAll()}}function u0($,Z,X,J,G="the provider state"){if(!$)throw _(Z,X,"invalid-input","the store was opened without a provider-state codec");let z;try{let B=JSON.stringify(J);z=B===void 0?void 0:JSON.parse(B)}catch{z=void 0}if(z===void 0)throw _(Z,X,"invalid-provider-state",`${G} cannot be stored as JSON`);if(!$.validate(z))throw _(Z,X,"invalid-provider-state",`the provider-state codec rejected ${G}`);return z}function M$($,Z,X,J,G){if(J===void 0||!$?.merge)return{kind:"set",value:G};return{kind:"set",value:u0($,Z,X,$.merge(structuredClone(J),structuredClone(G)),"the merged provider state")}}function w9($,Z,X,J,G){let z=$?.onReplace,B=z?z(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}:{},...G!==void 0?{incoming:structuredClone(G)}:{}}):G;if(B===void 0)return{kind:"clear"};if(!z)return{kind:"set",value:B};return{kind:"set",value:u0($,"replace",Z.id,B,"the provider state onReplace returned")}}function p9($,Z,X,J,G){if(Z.kind==="set")return u1($,Z.value);if(Z.kind==="clear")return;return K$(X,J?.credential,G,J?.identity)}async function u9($,Z,X,J,G={}){G0("updateProviderState");let{ctx:z}=$,B="updateProviderState";return z0(z,B,Z,G.onFailure,async(Q,Y)=>{let H=z.providerState;if(!H)throw _(B,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw _(B,Z,"invalid-input","a mutator is required");let W=O(X)?X.credentialEpoch:void 0;if(!$0(W))throw _(B,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await p0($,B,Z);await Q.acquire(q0($,V));for(let j of G.extraLocks??[])await Q.acquire(j);return n(z,Q,Y,{operation:B,rowId:Z},async(j)=>{let D=j.row(Z);if(!D)throw A0(B,Z);if(l(D)!==l(V))throw _(B,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(D.invalid)throw _(B,Z,"invalid-row",`row ${Z} failed validation`);if(!D.credential)throw _(B,Z,"no-credential",`row ${Z} holds no credential`);if(W0(B,D),(D.credentialEpoch??1)!==W||D.identity!==X.identity)throw _(B,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let N=await oZ(j,H,B,D,J);if(N.kind!=="changed")return{id:Z,outcome:"unchanged",...N.kind==="unchanged"&&N.value!==void 0?{providerState:N.value}:{}};return j.setStateAccount(Z,N.account),await j.commitState(),N.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:N.value}})})}var l9=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function oZ($,Z,X,J,G,z=!1){let{id:B,credential:Q}=J;if(!Q)throw _(X,B,"no-credential",`row ${B} holds no credential`);let Y=J.credentialEpoch??1,H=$.stateAccount(B),W=H?.[m],V=V0(W);if(!O(W)||!V?.binding||V.digest!==x0(Q)||V.credentialEpoch!==Y||V.binding.identity!==J.identity)throw _(X,B,"unbound-credential",`row ${B}'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),D=await b0(X,()=>G(j,J));if(z&&D===l9)return{kind:"declined"};let U=D===void 0?void 0:u0(Z,X,B,D,"the provider state the mutator returned"),N=H!==void 0&&Object.hasOwn(H,Y0);if(U===void 0?!N:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let K={...H};if(U===void 0){delete K[Y0];let M={...W};delete M.providerState,K[m]=M}else{K[Y0]=U;let M=u1(Z,U);if(V.providerState!==M)K[m]={...W,providerState:M}}return{kind:"changed",...U!==void 0?{value:U}:{},account:K}}import{randomUUID as d9}from"node:crypto";async function L6($,Z,X){if(!X)return;let J=$.rows().map((z)=>{let{id:B,type:Q,label:Y,enabled:H,disabledReason:W,identity:V,credentialEpoch:j,stamp:D,staged:U,torn:N,invalid:K}=z;return{id:B,type:Q,label:Y,enabled:H,disabledReason:W,identity:V,credentialEpoch:j,stamp:D,staged:U,torn:N,invalid:K}}),G=await b0($.info.operation,()=>X({id:Z,row:J.find((z)=>z.id===Z),rows:J,config:structuredClone($.snapshot.config)}));if(G!==void 0)throw _($.info.operation,Z,"row-protected",G)}var TX=["access","refresh","expires","lastRefreshedAt","apiKey"];function AX($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function SX($,Z,X){if(X.type!=="api")return X;let J=$.rosterRow(Z);if(!O(J)){if(X.baseURL===void 0)throw _($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...X,baseURL:X.baseURL}}let G=$.row(Z)?.credential,z=G?.type==="api"?{baseURL:G.baseURL.trim(),authHeader:G.authHeader??"authorization-bearer"}:AX(J),B=X.baseURL?.trim()??z.baseURL,Q=X.authHeader??z.authHeader;if(B!==z.baseURL||Q!==z.authHeader)throw _($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...X,baseURL:B,authHeader:Q}}function c9($,Z,X,J){let G=$.rosterRow(Z),z=$.row(Z),B=J??(z?z.identity:O(G)&&typeof G.accountId==="string"&&G.accountId?G.accountId:void 0);return{...B!==void 0?{identity:B}:{},...X.type==="api"?{baseURL:X.baseURL,authHeader:X.authHeader??"authorization-bearer"}:{}}}function N6($,Z,X,J,G={}){let z=SX(Z,X,J),B=Z.stateAccount(X),Q=G.providerState??{kind:"keep"},Y=Z.row(X)?.credentialEpoch??Z.entry(X)?.credentialEpoch,H=typeof Y==="number"?Y:1,W=p9($.ctx.providerState,Q,B,B&&Object.hasOwn(B,Y0)?Z.row(X):void 0,H),V=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,j=z.type==="oauth"?G.stamp??q$(V,$.ctx.now()):void 0,D={...B??{}};for(let K of TX)delete D[K];if(G.clearErrors)delete D.lastRefreshError,delete D.lastQuotaRefreshError,delete D.quota;if(Q.kind==="clear")delete D[Y0];else if(Q.kind==="set")D[Y0]=Q.value;let U=y9(z,j),N={...D,...k9(z,j),[m]:{...G.staged?{staged:G.staged}:{},...G.transition!==void 0?{[K6]:G.transition}:{},...dZ(U,H,G.binding??c9(Z,X,U,G.identity),{replace:G.binding!==void 0,...W!==void 0?{providerState:W}:{}})}};return{stored:U,account:N}}async function M6($,Z,X){return $.setStateAccount(Z,X.account),await $.commitState(X.stored),X.stored}async function _6($,Z,X,J,G={}){return M6(Z,X,N6($,Z,X,J,G))}async function RX($,Z,X){if(!Z.credential||Z.stamp!=="bound")return;let J=$.stateAccount(Z.id),G=K$(J,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...J??{},[m]:dZ(Z.credential,Z.credentialEpoch??1,c9($,Z.id,Z.credential,X),G!==void 0?{providerState:G}:{})}),await $.commitState()}function eZ($,Z,X){let J=$==="add"?p1(Z):void 0;if(J)throw _($,Z,"invalid-input",J);let G=f9(X,{baseURLOptional:$==="rotate"});if(G)throw _($,Z,"invalid-input",G)}function O6($,Z,X,J){if(!X)throw A0($,Z);if(X.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if(J&&J.type!==X.type)throw _($,Z,"type-mismatch",`row ${Z} holds a ${X.type} credential`);return X}function i1($,Z,X){if(X!==void 0&&!$0(O(X)?X.credentialEpoch:void 0))throw _($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function C6($,Z,X,J){if(!X)throw A0($,Z);if(X.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw _($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function F6($,Z){return _($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function F$($,Z){return _($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function EX($,Z,X,J){let{id:G,credential:z,identity:B}=X;if(!$.ctx.requireCredentialStamps||Z.rosterRow(G)||!s1(Z.state,G))return;let Q=()=>{throw _("add",G,"unbound-credential",`orphan ${G} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=Z.stateAccount(G),H=V0(Y?.[m]);if(!H?.binding||H.dispatch===void 0||H.replace)return Q();if(z.type==="api"&&(H.binding.baseURL===void 0||H.binding.authHeader===void 0))return Q();let W=z.type==="api"?{...z,baseURL:H.binding.baseURL,authHeader:H.binding.authHeader}:z,[V]=$1({accounts:[d1({id:G,credential:W,identity:H.binding.identity,addedAt:0})],[p]:{rows:{[G]:{credentialEpoch:D6(Z.config,G)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return Q();if(B!==void 0&&B!==V.identity)return Q();if(x0(z)!==H.digest)return Q();if(z.type==="api"){if(z.baseURL.trim()!==H.binding.baseURL)return Q();if((z.authHeader??"authorization-bearer")!==H.binding.authHeader)return Q()}else if(w0(z)!==H.dispatch)return Q();if(H.providerState!==void 0&&V.providerState===void 0)return Q();if(J!==void 0&&u1($.ctx.providerState,J)!==H.providerState)return Q();return V}function IX($,Z,X,J){let{id:G,credential:z,identity:B,label:Q}=X,Y=Z.rosterRow(G),H=()=>{throw _("add",G,Y?"id-exists":"unbound-credential",`row ${G} does not match this staged add`)},W=Z.stateAccount(G),V=V0(W?.[m]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return H();if(Y&&(Y.type!==z.type||Y.label!==Q||Y.accountId!==B))return H();if(j.reservation!==X.stage?.reservation||j.label!==Q||j.disabledReason!==X.disabled?.reason||V.binding.identity!==B)return H();let D=J===void 0?void 0:L1(J),U=W?.[Y0],N=U===void 0?void 0:L1(U);if(j.providerState!==D||j.providerState!==N)return H();if(x0(z)!==V.digest||w0(z)!==V.dispatch)return H();let K=Y?Z.config:{accounts:[{...d1({id:G,credential:z.type==="api"?{...z,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:z,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[p]:{rows:{[G]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},M=$1(K,Z.state,$.ctx.codec,$.ctx.providerState).find((P)=>P.id===G);if(!M?.credential||M.invalid||M.stamp!=="bound"||M.type!==z.type||M.enabled||M.label!==j.label||M.identity!==V.binding.identity||M.disabledReason!==j.disabledReason||M.staged?.reservation!==j.reservation)return H();if(Y)return{id:G,outcome:"exists",credential:M.credential,credentialEpoch:V.credentialEpoch};if(D6(Z.config,G)!==V.credentialEpoch)return H();return Z.roster().push({...d1({id:G,credential:z,identity:B,label:Q,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(G,{credentialEpoch:V.credentialEpoch,needsFirstReading:z.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),Z.commitConfig().then(()=>({id:G,outcome:"completed",credential:M.credential,credentialEpoch:V.credentialEpoch}))}async function s9($,Z,X={}){G0("add");let{ctx:J}=$,{id:G,credential:z,identity:B,label:Q}=Z,Y=Z.stage!==void 0||Z.disabled!==void 0,H=await z0(J,"add",G,X.onFailure,async(W,V)=>{eZ("add",G,z);let j=X.onExisting??"rotate";if(Z.stage!==void 0&&j==="rotate")throw _("add",G,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||Z.stage!==void 0&&(Q!==void 0&&typeof Q!=="string"||B!==void 0&&(typeof B!=="string"||!B))||Z.disabled!==void 0&&(!O(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!O(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||j==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw _("add",G,"invalid-input","staging requires a reservation and a disabled reason");let D=Z.providerState===void 0?void 0:u0(J.providerState,"add",G,Z.providerState);if(await W.acquire(q0($,{id:G,identity:B})),z.type==="oauth")await W.acquire(X.providerLock??$.providerLock);for(let U of X.extraLocks??[])await W.acquire(U);return n(J,W,V,{operation:"add",rowId:G},async(U)=>{await L6(U,G,X.protect);let N=O(U.state.accounts)?U.state.accounts:{},K=Object.entries(N).find(([y,f])=>{if(y===G||U.rosterRow(y)||!O(f))return!1;let h=f[m];if(!O(h)||!Object.hasOwn(h,"staged"))return!1;return z.type==="oauth"?f.refresh===z.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===z.apiKey.trim()});if(K)throw _("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(J.removedIds.has(G))throw _("add",G,"id-removed",`id ${G} was removed from the roster in this process and is not reused`);if(Z.stage&&j!=="rotate"&&(U.rosterRow(G)||s1(U.state,G)))return IX($,U,Z,D);if(j==="rotate"){U.assertNotStaged(G);let y=U.rows().find((f)=>f.fingerprint===t0(z));if(y)U.assertNotStaged(y.id)}if(j==="refuse"){let y=U.rows().find((c)=>c.fingerprint===t0(z)||c.id===G&&c.credential),f=O(U.state.accounts)?U.state.accounts:{},h=Object.entries(f).find(([,c])=>{if(!O(c))return!1;if(z.type==="oauth")return c.refresh===z.refresh;return typeof c.apiKey==="string"&&c.apiKey.trim()===z.apiKey.trim()})?.[0],r=y?.id??h??G;if(y||h!==void 0||s1(U.state,G))throw _("add",r,"credential-exists",`row ${r} already holds this secret or id`)}if(j==="stage-duplicate"&&(U.rosterRow(G)||s1(U.state,G)))throw _("add",G,"id-exists",`row ${G} already exists`);let M=EX($,U,Z,D),P=U.rows(),E=t0(z),F=j==="rotate"&&!M&&P.find((y)=>y.invalid===void 0&&y.fingerprint===E);if(F){if(U.assertNotStaged(F.id),W0("add",F),B!==void 0&&F.identity!==void 0&&B!==F.identity)throw F6("add",F.id);let y=N6($,U,F.id,z,{...D!==void 0?{providerState:M$(J.providerState,"add",F.id,F.providerState,D)}:{}});await U.completeTorn(),U.assertNotStaged(F.id);let f=await M6(U,F.id,y);return{id:F.id,outcome:"rotated",credential:f,credentialEpoch:F.credentialEpoch??1}}let q=P.find((y)=>y.id===G);if(q){if(q.invalid)throw _("add",G,"invalid-row",`row ${G} is invalid`);if(q.credential)throw _("add",G,"id-exists",`row ${G} already holds a credential`);if(W0("add",q),q.type!==z.type)throw _("add",G,"type-mismatch",`row ${G} is a ${q.type} row`);if(B!==void 0&&q.identity!==void 0&&B!==q.identity)throw F6("add",G);if(!q.hasEntry)U.setEntry(G,{credentialEpoch:1,needsFirstReading:z.type==="oauth"});let y=N6($,U,G,z,{clearErrors:!0,...D!==void 0?{providerState:{kind:"set",value:D}}:{}});await U.completeTorn();let f=await M6(U,G,y);if(!q.hasEntry)await U.commitConfig();return{id:G,outcome:"completed",credential:f,credentialEpoch:q.credentialEpoch??1}}let L=D6(U.config,G);if(!$0(L))throw _("add",G,"id-removed",`id ${G} has held every credential epoch and is not reused; add the credential under another id`);let S=M?.identity??B;U.roster().push(d1({id:G,credential:z,...S!==void 0?{identity:S}:{},...Q!==void 0?{label:Q}:{},addedAt:J.now()})),U.setEntry(G,{credentialEpoch:L,needsFirstReading:z.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let A="added";if(Z.disabled)a0(U,G,Z.disabled.reason),A="added-disabled";if(!Z.disabled&&S!==void 0&&z.type==="oauth"){if(P.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===S))a0(U,G,kZ),A="added-disabled"}if(M?.credential)return await U.commitConfig(),{id:G,outcome:A,credential:M.credential,credentialEpoch:M.credentialEpoch??L};U.dropStateAccount(G);let x=N6($,U,G,z,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...Q!==void 0?{label:Q}:{},...D!==void 0?{providerState:L1(D)}:{}}}:{},...D!==void 0?{providerState:{kind:"set",value:D}}:{}});if(j==="rotate")await U.completeTorn();let w=await M6(U,G,x);return await U.commitConfig(),{id:G,outcome:A,credential:w,credentialEpoch:L}},{completeTorn:!1})});if(!Y&&z.type==="oauth"&&(H.outcome==="added"||H.outcome==="completed"))$.firePull(H.id,"add");return H}async function i9($,Z,X,J={},G={}){G0("replace");let{ctx:z}=$,B=await z0(z,"replace",Z,G.onFailure,async(Q,Y)=>{eZ("replace",Z,X),i1("replace",Z,G.attribution);let H=J.providerState===void 0?void 0:u0(z.providerState,"replace",Z,J.providerState),{row:W}=await p0($,"replace",Z);if(await Q.acquire(q0($,W)),X.type==="oauth")await Q.acquire(G.providerLock??$.providerLock);for(let V of G.extraLocks??[])await Q.acquire(V);return n(z,Q,Y,{operation:"replace",rowId:Z},async(V)=>{if(G.attribution!==void 0)C6("replace",Z,V.row(Z),G.attribution),await V.completeTorn();let j=O6("replace",Z,V.row(Z),X);if(l(j)!==l(W))throw F$("replace",Z);let D=V.entry(Z)?.credentialEpoch,U=(typeof D==="number"?D:1)+1;if(!$0(U))throw _("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let N=w9(z.providerState,j,U,J.identity,H),K={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(iZ(V,Z,U,K),J.identity!==void 0)w1(V,J.identity);let M=await _6($,V,Z,X,{clearErrors:!0,binding:K,providerState:N});return await V.commitConfig(),{id:Z,credential:M,credentialEpoch:U}},{completeTorn:G.attribution===void 0})});if(X.type==="oauth")$.firePull(Z,"replace");return B}async function a9($,Z,X,J={},G={}){G0("rotate");let{ctx:z}=$;return z0(z,"rotate",Z,G.onFailure,async(B,Q)=>{eZ("rotate",Z,X),i1("rotate",Z,G.attribution);let Y=J.providerState===void 0?void 0:u0(z.providerState,"rotate",Z,J.providerState),{row:H}=await p0($,"rotate",Z);if(await B.acquire(q0($,H)),J.identity!==void 0&&X.type==="oauth")await B.acquire(G.providerLock??$.providerLock);for(let W of G.extraLocks??[])await B.acquire(W);return n(z,B,Q,{operation:"rotate",rowId:Z},async(W)=>{if(G.attribution!==void 0)C6("rotate",Z,W.row(Z),G.attribution),await W.completeTorn();let V=O6("rotate",Z,W.row(Z),X);if(l(V)!==l(H))throw F$("rotate",Z);if(W0("rotate",V),J.identity!==void 0&&V.identity!==void 0&&J.identity!==V.identity)throw F6("rotate",Z);let j=J.identity!==void 0&&V.identity===void 0?J.identity:void 0,D=await _6($,W,Z,X,{identity:j,...Y!==void 0?{providerState:M$(z.providerState,"rotate",Z,V.providerState,Y)}:{}}),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)N1(W,Z,J.identity),U=!0;if(U)await W.commitConfig();return{id:Z,credential:D}},{completeTorn:G.attribution===void 0})})}async function n9($,Z,X,J,G){G0(Z);let{ctx:z}=$,B=z.providerState,Q=G.attribution,Y=G.providerState;return z0(z,Z,X,G.onFailure,async(H,W)=>{if(i1(Z,X,Q),Y!==void 0){if(typeof Y!=="function")throw _(Z,X,"invalid-input","the provider-state mutator must be a function");if(Q===void 0)throw _(Z,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw _(Z,X,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await p0($,Z,X);await H.acquire(q0($,V));for(let j of G.extraLocks??[])await H.acquire(j);return n(z,H,W,{operation:Z,rowId:X},async(j)=>{await L6(j,X,G.protect),j.assertNotStaged(X);let D=j.row(X),U=J.enabled?O6("enable",X,D):D;if(!U||!j.rosterRow(X))throw A0(Z,X);if(l(U)!==l(V))throw F$(Z,X);if(Q!==void 0)C6(Z,X,U,Q);if(J.enabled&&U.disabledReason?.startsWith(m1))throw _("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let N=!J.enabled||!U.enabled||U.disabledReason!==void 0;if(J.enabled&&N&&U.type==="oauth"){let F=U.identity===void 0?void 0:j.rows().find((q)=>q.id!==X&&q.invalid===void 0&&q.type==="oauth"&&q.enabled&&q.identity===U.identity);if(F)throw _("enable",X,"duplicate-identity",`row ${F.id} is enabled with the same identity as row ${X}`)}if(Y===void 0||B===void 0){if(await j.completeTorn(),!N)return{id:X};if(J.enabled)V$(j,X);else a0(j,X,J.reason);return await j.commitConfig(),{id:X}}if(!U.credential)throw _(Z,X,"no-credential",`row ${X} holds no credential`);W0(Z,U);let K=await oZ(j,B,Z,U,Y,!0);if(K.kind==="declined")return{id:X,declined:!0};await j.completeTorn();let M={id:X,providerStateOutcome:K.kind==="unchanged"?"unchanged":K.value===void 0?"cleared":"updated",...K.value!==void 0?{providerState:K.value}:{}};if(K.kind==="unchanged"){if(N){if(J.enabled)V$(j,X);else a0(j,X,J.reason);await j.commitConfig()}return M}if(!N)return j.setStateAccount(X,K.account),await j.commitState(),M;let P=J.enabled?{mark:d9(),enabled:!0}:{mark:d9(),enabled:!1,reason:J.reason},E=K.account[m];return j.setStateAccount(X,{...K.account,[m]:{...E,[K6]:P}}),await j.commitState(),N$(j,X,P),await j.commitConfig(),M},{completeTorn:!1})})}function r9($,Z,X,J={}){return n9($,"disable",Z,{enabled:!1,reason:X},J)}function o9($,Z,X={}){return n9($,"enable",Z,{enabled:!0},X)}async function t9($,Z,X={}){G0("remove");let{ctx:J}=$;return z0(J,"remove",Z,X.onFailure,async(G,z)=>{if(typeof Z!=="string"||Z.length===0)throw _("remove",Z,"invalid-input","id must be non-empty");let B=X.attribution;if(i1("remove",Z,B),X.staged!==void 0&&(!O(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw _("remove",Z,"invalid-input","a staged removal needs a reservation");let Q=await H0(J);if(Q.status!=="ready")throw T0(Q,"remove",Z);let Y=Q.rows.find((W)=>W.id===Z);if(!Y&&!s1(Q.state,Z))throw A0("remove",Z);let H=l(Y??{id:Z});await G.acquire(q0($,Y??{id:Z}));for(let W of X.extraLocks??[])await G.acquire(W);return n(J,G,z,{operation:"remove",rowId:Z},async(W)=>{let V=W.reservation(Z);if(V!==void 0){if(!O(V)||!X.staged||V.reservation!==X.staged.reservation)throw _("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(X.staged)throw _("remove",Z,"attribution",`row ${Z} is no longer reserved`);let j=W.row(Z),D=s1(W.state,Z);if(!j&&!D)throw A0("remove",Z);if(l(j??{id:Z})!==H)throw F$("remove",Z);if(B!==void 0)if(j)P6(Z,j,B);else bX($,W,Z,B);let U=X.protect;if(U){let N={row:j,config:W.snapshot.config,state:W.snapshot.state},K=await b0("remove",()=>U(Z,N));if(K!==void 0)throw _("remove",Z,"row-protected",K)}if(j){if(B===void 0)await W.completeTorn();W.dropRosterRows(Z),await W.commitConfig()}if(D)W.dropStateAccount(Z),await W.commitState();return{id:Z,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function P6($,Z,X,J="remove"){if(C6(J,$,Z,X),Z.torn)throw _(J,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw _(J,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function bX($,Z,X,J){let G=()=>_("remove",X,"unbound-credential",`orphan ${X} has no credential stamp this store can bind, so the removal cannot be attributed to it`),z=Z.stateAccount(X),B=V0(z?.[m]);if(!z||!B?.binding||B.dispatch===void 0||B.replace)throw G();let Q;if(typeof z.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw G();Q={type:"api",apiKey:z.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof z.refresh==="string")Q={type:"oauth",refresh:z.refresh};else throw G();let[Y]=$1({accounts:[d1({id:X,credential:Q,identity:B.binding.identity,addedAt:0})],[p]:{rows:{[X]:{credentialEpoch:B.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw G();if(B.credentialEpoch!==J.credentialEpoch||B.binding.identity!==J.identity)throw _("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function s1($,Z){let X=$.accounts;return O(X)&&Object.hasOwn(X,Z)}function tZ($){return O($)&&typeof $.id==="string"?$.id:void 0}function xX($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let X=new Set;for(let z of $){let B=tZ(z);if(B!==void 0)X.add(B)}let J=new Set;for(let z of Z){if(typeof z!=="string")return"ids must be an array of roster ids";if(J.has(z))return`id ${z} appears more than once`;if(!X.has(z))return`id ${z} is not in the roster`;J.add(z)}let G=[...X].filter((z)=>!J.has(z));if(G.length>0)return`the order leaves out roster id(s) ${G.join(", ")}`;return}function kX($,Z){let X=new Map;for(let z of $){let B=tZ(z);if(B===void 0)continue;let Q=X.get(B);if(Q)Q.push(z);else X.set(B,[z])}let J=Z.flatMap((z)=>X.get(z)??[]),G=0;return $.map((z)=>tZ(z)===void 0?z:J[G++])}async function e9($,Z,X={}){G0("reorder");let{ctx:J}=$,G=X.onFailure;return z0(J,"reorder",void 0,G&&((z,B)=>G(B)),async(z,B)=>{for(let Q of X.extraLocks??[])await z.acquire(Q);return n(J,z,B,{operation:"reorder",rowId:void 0},async(Q)=>{let Y=Q.roster(),H=xX(Y,Z);if(H)throw new g({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:H});let W=[...Z],V=kX(Y,W);if(V.every((j,D)=>j===Y[D]))return{ids:W,outcome:"unchanged"};return Q.config.accounts=V,await Q.commitConfig(),{ids:W,outcome:"reordered"}},{completeTorn:!1})})}async function $4($,Z,X,J,G={}){return G0("recordIdentity"),z0($.ctx,"recordIdentity",Z,G.onFailure,async(z,B)=>{if(typeof X!=="string"||X.length===0)throw _("recordIdentity",Z,"invalid-input","identity must be non-empty");let Q=O(J)?J.credentialEpoch:void 0;if(!$0(Q))throw _("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await p0($,"recordIdentity",Z);await z.acquire(q0($,Y)),await z.acquire(G.providerLock??$.providerLock);for(let H of G.extraLocks??[])await z.acquire(H);return n($.ctx,z,B,{operation:"recordIdentity",rowId:Z},async(H)=>{let W=O6("recordIdentity",Z,H.row(Z));if(l(W)!==l(Y))throw F$("recordIdentity",Z);if(W0("recordIdentity",W),(W.credentialEpoch??1)!==Q)throw _("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 F6("recordIdentity",Z);if(W.identity===void 0)await RX(H,W,X);let V=N1(H,Z,X);return await H.commitConfig(),{id:Z,disabled:V}})})}function X4($){let Z=$[p];return O(Z)&&O(Z.publications)?Z.publications:{}}function J4($,Z){let X=X4($);if(!Object.hasOwn(X,Z))return;let J=X[Z];if(!O(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((G)=>!O(G)||typeof G.id!=="string"||!$0(G.credentialEpoch))||J.finalized.some((G)=>!O(G)||typeof G.id!=="string"||!$0(G.credentialEpoch)||typeof G.reservation!=="string"||!G.reservation||typeof G.enabled!=="boolean"))throw _("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function G4($,Z){let X=await H0($.ctx);if(X.status!=="ready")throw T0(X,"publishRoster",Z);return J4(X.config,Z)}function yX($,Z){let X=()=>{throw _("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!O(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 G of[...Z.remove,...Z.finalize]){if(!O(G)||typeof G.id!=="string"||p1(G.id)||J.has(G.id)||!G.attribution)X();if(J.add(G.id),i1("publishRoster",G.id,G.attribution),G.attribution.identity!==void 0&&(typeof G.attribution.identity!=="string"||!G.attribution.identity))X()}for(let G of Z.remove)if($.ctx.requireRemovedFingerprint&&!G.fingerprint||G.fingerprint!==void 0&&typeof G.fingerprint!=="string")X();for(let G of Z.finalize)if(typeof G.reservation!=="string"||!G.reservation||typeof G.enabled!=="boolean"||(G.enabled?G.disabledReason!==void 0:typeof G.disabledReason!=="string"))X();if(Z.order.some((G)=>typeof G!=="string"||p1(G))||new Set(Z.order).size!==Z.order.length)X()}function z4($,Z){$.entries();let X=$.config[p],J={...X4($.config)};Object.defineProperty(J,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function fX($,Z,X){let J=new Set;for(let B of l1($.config)){if(!O(B)||typeof B.id!=="string")continue;if(J.has(B.id))throw _("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");J.add(B.id)}let G=new Set(Z.remove.map((B)=>B.id)),z=X.filter((B)=>B.invalid!=="roster"&&!G.has(B.id));if(z.length!==Z.order.length||Z.order.some((B)=>!z.some((Q)=>Q.id===B))||z.some((B)=>!Z.order.includes(B.id)))throw _("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return z}async function Z4($,Z){await $.assertAll();for(let J of Z.removed)if(V0($.stateAccount(J.id)?.[m])?.credentialEpoch===J.credentialEpoch&&!$.rosterRow(J.id))$.dropStateAccount(J.id);for(let J of Z.finalized){let G=$.stateAccount(J.id),z=V0(G?.[m]);if(G&&z?.credentialEpoch===J.credentialEpoch&&z.staged?.reservation===J.reservation){let B={...G[m]};delete B.staged,$.setStateAccount(J.id,{...G,[m]:B})}}await $.commitState(void 0,{durable:!0});let X={...Z,phase:"cleaned"};return z4($,X),await $.commitConfig({durable:!0}),X}async function B4($,Z,X={}){return G0("publishRoster"),z0($.ctx,"publishRoster",Z?.operationId??"",X.onFailure,async(J,G)=>{if(!O(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw _("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let z=L1(Z),B=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((Q)=>O(Q)&&typeof Q.id==="string");for(let Q=0;;Q++){let Y=await H0($.ctx);if(Y.status!=="ready")throw T0(Y,"publishRoster",Z.operationId);let H=new Map(B.map(({id:V})=>[V,l(Y.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(H.values())].sort())await J.acquire(q0($,{id:V}));await J.acquire(X.providerLock??$.providerLock);for(let V of X.extraLocks??[])await J.acquire(V);let W=await n($.ctx,J,G,{operation:"publishRoster",rowId:Z.operationId},async(V)=>{let j=V.rows();if(B.some(({id:q})=>l(j.find((L)=>L.id===q)??{id:q})!==H.get(q)))return;let D=J4(V.config,Z.operationId);if(D){if(D.planDigest!==z)throw _("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(D.phase==="cleaned")return{outcome:"already-cleaned",receipt:D};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await Z4(V,D)}}yX($,Z);let U=fX(V,Z,j),N=[];for(let q of Z.remove){V.assertNotStaged(q.id);let L=j.find((S)=>S.id===q.id);if(!L)throw _("publishRoster",q.id,"attribution","the removed row no longer exists");if(P6(q.id,L,q.attribution,"publishRoster"),!L.credential||q.fingerprint!==void 0&&t0(L.credential)!==q.fingerprint)throw _("publishRoster",q.id,"attribution","the removed secret no longer matches");N.push(L)}let K=[];for(let q of Z.finalize){let L=j.find((f)=>f.id===q.id),S=V0(V.stateAccount(q.id)?.[m]);if(!L||L.staged?.reservation!==q.reservation||S?.staged?.reservation!==q.reservation||L.enabled)throw _("publishRoster",q.id,"row-staged","the finalized row is not disabled under this reservation");let A=V.stateAccount(q.id),x=V.rosterRow(q.id),w=A?.[Y0],y=w===void 0?void 0:L1(w);if(!S?.staged||S.staged.label!==x?.label||S.staged.disabledReason!==L.disabledReason||S.staged.providerState!==y)throw _("publishRoster",q.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");P6(q.id,L,q.attribution,"publishRoster"),K.push(L)}let M=U.find((q)=>q.torn);if(M)throw _("publishRoster",Z.operationId,"attribution",`Row ${M.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let P=new Set;for(let q of U){if(!(Z.finalize.find((S)=>S.id===q.id)?.enabled??q.enabled)||q.type!=="oauth"||q.identity===void 0)continue;if(P.has(q.identity))throw _("publishRoster",q.id,"invalid-input","the final enabled roster repeats a known identity");P.add(q.identity)}for(let q of U)if(q.identity!==void 0&&q.fingerprint!==void 0&&U.some((L)=>L.id!==q.id&&L.identity!==void 0&&L.identity!==q.identity&&L.fingerprint===q.fingerprint))throw _("publishRoster",q.id,"attribution","the resulting pool gives the same secret different known identities");for(let q of K)if(q.identity!==void 0&&N.some((L)=>L.identity!==void 0&&L.identity!==q.identity&&L.fingerprint===q.fingerprint))throw _("publishRoster",q.id,"attribution","the staged secret belonged to a different known identity");await L6(V,Z.operationId,X.protect);let E={operationId:Z.operationId,planDigest:z,phase:"committed",removed:N.map((q)=>({id:q.id,credentialEpoch:q.credentialEpoch??1})),finalized:Z.finalize.map((q,L)=>({id:q.id,credentialEpoch:K[L]?.credentialEpoch??1,reservation:q.reservation,enabled:q.enabled}))};for(let q of Z.remove)V.dropRosterRows(q.id);for(let q of Z.finalize){let L=V.rosterRow(q.id);L.enabled=q.enabled;let S={...V.entry(q.id)};if(delete S.staged,q.enabled)delete S.disabledReason;else S.disabledReason=q.disabledReason;V.setEntry(q.id,S)}let F=V.roster().filter((q)=>!O(q)||typeof q.id!=="string"||j.find((L)=>L.id===q.id)?.invalid==="roster");return V.config.accounts=[...Z.order.map((q)=>V.rosterRow(q)),...F],z4(V,E),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await Z4(V,E)}},{completeTorn:!1});if(W)return W;if(await J.releaseAll(),Q>=1)throw _("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class $3{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,X,J,G){this.rt=$,this.hook=Z,this.onFailure=X,this.firedAtLoad=J,this.logger=G}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,G=new r0(J.lockDefaults,J.lockEnv),z={writes:0};try{let B=await n(J,G,z,{operation:"pull",rowId:$},async(Y)=>{if(Y.reservation($)!==void 0)return;await Y.completeTorn();let H=Y.row($);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)W0("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.hasEntry)Y.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await Y.commitConfig();let W=Y.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 G.releaseAll(),!B){this.firedAtLoad.delete($);return}await J.hold?.("pull-before-request",$);let Q;try{Q=await this.hook?.(B)}catch(Y){throw new g({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Y})}await q6(X,$,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(B){this.firedAtLoad.delete($);let Q=c1(B,"pull",$,z);if(this.onFailure)try{await this.onFailure($,Q)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:$,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:Q.kind})}finally{await G.releaseAll()}}}import{randomUUID as gX}from"node:crypto";function Z3($,Z){if(F1("refresh",$,Z?.staged),!Z)throw _("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw _("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw _("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw _("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function Q4($){return _("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function Y4($,Z,X,J={}){G0("refresh");let{ctx:G}=$;return z0(G,"refresh",Z,J.onFailure,async(z,B)=>{let{row:Q}=await p0($,"refresh",Z);Z3(Z,Q);let Y=await J.refuse?.(Q);if(Y!==void 0)return{status:"refused",rowId:Z,reason:Y};let H=l(Q),W;for(let U=0;;U++){await z.acquire(q0($,{id:Z,identity:H===Z?void 0:H})),await z.acquire(J.providerLock??$.providerLock);for(let M of J.extraLocks??[])await z.acquire(M);let K=await n(G,z,{writes:0},{operation:"refresh",rowId:Z},async(M)=>{let P=Z3(Z,M.row(Z));if(W0("refresh",P),!P.hasEntry)M.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await M.commitConfig(),P=Z3(Z,M.row(Z));if(l(P)!==H)return{keyNow:l(P)};let E=await J.refuse?.(P);if(E!==void 0)return{refused:E};return{row:P,credential:P.credential,credentialEpoch:P.credentialEpoch,identity:P.identity}});if("refused"in K)return{status:"refused",rowId:Z,reason:K.refused};if("keyNow"in K){if(await z.releaseAll(),U>=1)throw _("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);H=K.keyNow;continue}W=K;break}if(sZ(W.credential.lastRefreshedAt,G.now()))throw Q4(Z);await G.hold?.("refresh-before-provider",Z),await z.assertAll();let V;try{V=await X(W.credential,W.row)}catch(U){throw new g({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 _("refresh",Z,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:u0(G.providerState,"refresh",Z,V.providerState,"the provider state the provider returned"),D=await n(G,z,B,{operation:"refresh",rowId:Z},async(U)=>{let N=U.row(Z),K=U.entry(Z);if(!N||N.invalid||!K||K.credentialEpoch!==W.credentialEpoch||N.identity!==W.identity)throw new g({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`});W0("refresh",N);let M=await J.refuse?.(N);if(M!==void 0)return{refused:M};let P=G.now(),E=N.credential?.type==="oauth"?N.credential.lastRefreshedAt:void 0;if(sZ(E,P))throw Q4(Z);let F={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},q=N.identity!==void 0&&V.identity!==void 0&&N.identity!==V.identity?{expectedIdentity:N.identity,returnedIdentity:V.identity}:void 0,L=q?{mark:gX(),enabled:!1,reason:`${m1}${JSON.stringify(q)}`}:void 0,S=N.identity===void 0&&V.identity?V.identity:void 0,A=await _6($,U,Z,F,{stamp:q$(E,P),transition:L,identity:S,...j!==void 0?{providerState:M$(G.providerState,"refresh",Z,N.providerState,j)}:{}});if(L!==void 0)N$(U,Z,L),await U.commitConfig();let x=N.identity;if(S!==void 0)N1(U,Z,S),x=S,await U.commitConfig();return{stored:A,identity:x,contradiction:q,refused:void 0}});if(D.refused!==void 0)return{status:"refused",rowId:Z,reason:D.refused};if(D.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...D.contradiction,credential:D.stored};if(J.onPersisted)try{let U=J.onPersisted;await b0("refresh",()=>U(Z,D.stored))}catch(U){throw new g({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:D.stored,message:"the after-persist hook threw; the rotation stays committed",cause:U})}return{status:"rotated",rowId:Z,credential:D.stored,...D.identity!==void 0?{identity:D.identity}:{}}})}import{isDeepStrictEqual as hX}from"node:util";var A6=Object.freeze(["version","accounts",p]);function X3($){let Z={};for(let[X,J]of Object.entries($))if(!A6.includes(X))T6(Z,X,J);return Z}function T6($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function vX($,Z){let X={};for(let[J,G]of Object.entries($))if(A6.includes(J))T6(X,J,G);else if(Object.hasOwn(Z,J))T6(X,J,Z[J]);for(let[J,G]of Object.entries(Z))if(!Object.hasOwn($,J))T6(X,J,G);return X}function H4($){return new g({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}async function W4($){let Z=await H0($.ctx);if(Z.status==="error")return Z;return{status:Z.status,settings:X3(Z.config)}}async function V4($,Z,X={}){G0("updateSettings");let{ctx:J}=$,G=X.onFailure;return z0(J,"updateSettings",void 0,G&&((z,B)=>G(B)),async(z,B)=>{for(let Y of X.extraLocks??[])await z.acquire(Y);let Q=z.held.length;try{for(let K of J.storeLocks)await z.acquire(K);let Y=await H0(J);if(Y.status!=="ready")throw T0(Y,"updateSettings",void 0);let H=X3(Y.config),W=structuredClone(H),V=await b0("updateSettings",()=>Z(W)),j=V===void 0?W:V;if(!O(j))throw H4("the settings mutator must produce an object");let D=A6.filter((K)=>Object.hasOwn(j,K));if(D.length>0)throw H4(`settings cannot set the pool-owned key(s) ${D.join(", ")}`);if(hX(j,H))return{settings:H,outcome:"unchanged"};let U=vX(Y.config,j),N={operation:"updateSettings",rowId:void 0};return await F0(J.configPath,U,{beforeRename:async()=>{await J.onStep?.("before-config-write",N),await z.assertAll()}}),B.writes++,await J.onStep?.("after-config-write",N),{settings:X3(U),outcome:"updated"}}finally{await z.releaseTo(Q)}})}var U4=new Map;function mX($){let Z=U4.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},U4.set($,Z);return Z}function j4($){if($.status==="ready")return{status:"ready",schemaVersion:o0,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function J3($){let Z=mX($.configPath),X={...pZ,...$.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:{...$.onLockEvent?{onLockEvent:$.onLockEvent}:{},...$.onLockStep?{onLockStep:$.onLockStep}:{},...$.onRenewalTimer?{onRenewalTimer:$.onRenewalTimer}:{}},removedIds:Z.removedIds,requireCredentialStamps:$.requireCredentialStamps===!0,requireRemovedFingerprint:$.requireRemovedFingerprint===!0,...$.logger?{logger:$.logger}:{},...$.onStep?{onStep:$.onStep}:{},...$.hold?{hold:$.hold}:{}},G=new $3(()=>z,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),z={ctx:J,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(B,Q)=>G.fire(B,Q)};return{async load(){let B=await H0(J);if(B.status==="ready"){for(let Q of B.rows)if((Q.candidate||Q.torn&&Q.enabled)&&Q.type==="oauth"&&Q.needsFirstReading)G.fire(Q.id,"load")}return j4(B)},async read(){return j4(await H0(J))},async initialize(B={}){return{status:await m9(J,B.dropKeys??[])}},add:(B,Q)=>s9(z,B,Q),publishRoster:(B,Q)=>B4(z,B,Q),publication:(B)=>G4(z,B),replace:(B,Q,Y,H)=>i9(z,B,Q,Y,H),rotate:(B,Q,Y,H)=>a9(z,B,Q,Y,H),updateProviderState:(B,Q,Y,H)=>u9(z,B,Q,Y,H),disable:(B,Q,Y)=>r9(z,B,Q,Y),enable:(B,Q)=>o9(z,B,Q),remove:(B,Q)=>t9(z,B,Q),reorder:(B,Q)=>e9(z,B,Q),readSettings:()=>W4(z),updateSettings:(B,Q)=>V4(z,B,Q),recordIdentity:(B,Q,Y,H)=>$4(z,B,Q,Y,H),refresh:(B,Q,Y)=>Y4(z,B,Q,Y),recordQuota:(B,Q,Y)=>q6(z,B,Q,Y),requestReading:(B)=>G.fire(B,"admission"),pullsSettled:()=>G.settled()}}var wX=[/\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 B3($={}){let{redactStrings:Z}=I0({...$,extraValuePatterns:[...wX,...$.extraValuePatterns??[]]});return(X)=>Z(X)}class B0 extends Error{code;constructor($,Z,X){super(Z,X);this.name="CommandError",this.code=$}}var D4=/^[a-z][a-z0-9-]{0,63}$/,G3={code:"action-failed",text:"That action failed."},pX=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 L$($){if($ instanceof B0)return{code:D4.test($.code)?$.code:G3.code,text:$.message};if($ instanceof g)return{code:`pool-${$.kind}`,text:pX.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return G3}var K4="This cannot be undone. Continue?",uX=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function lX($){let Z=$.toLowerCase().replace(/[-_]/g,"");return uX.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function dX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function z3($,Z,X){if(typeof $==="string"){let G=X.redact($);if(G!==$)X.redacted.push(Z);return G}if(Array.isArray($))return $.map((G,z)=>z3(G,`${Z}[${z}]`,X));if(!dX($))return $;let J={};for(let[G,z]of Object.entries($)){if(lX(G)){X.dropped.push(`${Z}.${G}`);continue}Object.defineProperty(J,G,{value:z3(z,`${Z}.${G}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function q4($,Z,X){let J={redact:X.redact,dropped:[],redacted:[]},G=z3($,"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 G}function cX($){return{value:String($.value),label:String($.label)}}function sX($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(cX),...$.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 Q3($){if($.irreversible===!0)return{message:$.confirm||K4,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function N4($){let Z=Q3($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(sX),...Z?{confirm:Z}:{}}}function iX($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function aX($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:iX($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(N4)}}function nX($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(aX),actions:(Z.actions??[]).map(N4),...Z.facts!==void 0?{facts:Z.facts}:{}}}function M4($,Z,X){return{command:$,title:Z,sections:X.map(nX)}}function F4($,Z,X,J){return q4({command:$,menu:M4($,Z,X)},$,J)}function L4($,Z,X,J,G){return q4({command:$,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:D4.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:M4($,Z,X)},$,G)}var C4="disabled from the command menu";function rX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function l0($){return rX($)?{...$}:{}}function oX($){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 tX($,Z){return $.label??Z??$.id}function S6($,Z){return Q0($.quota)?s($.quota,Z):void 0}function P4($,Z){return`${$} ${Z}${$===1?"":"s"}`}var _$="Actions";function eX($){if($.status==="pending-migration")return"The account pool has not been migrated yet.";if($.status==="error")return`The ${$.file} file cannot be read: ${$.reason}`;return}function _4($,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 O4($){return L$($).text}async function $J($){let Z=await $.read(),X=await $.readSettings();return{load:Z,rows:oX(Z),settings:X.status==="error"?{}:X.settings}}function R6($,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:tX($,X)}}function ZJ($,Z){let{store:X,extraLocks:J}=$,G=J?{extraLocks:J}:{},z=Z.rows.map((V)=>V.id),B=eX(Z.load),Q=Z.rows.filter((V)=>V.enabled).length,Y=Z.rows.map((V,j)=>{let{account:D,name:U}=R6(V,$),N=[V.type==="api"?"API key":"OAuth",...D.identity!==void 0?[D.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),K=V.invalid?"invalid":V.enabled?"enabled":"disabled",M=[];if(!V.invalid&&V.enabled)M.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(V.id,C4,G),`Disabled ${U}.`}});if(!V.invalid&&!V.enabled)M.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(V.id,G),`Enabled ${U}.`}});if(z.length>1)M.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:z.map((P,E)=>({value:String(E+1),label:String(E+1)})),value:String(j+1)}],run:async({values:P})=>{let E=Number(P.position),F=z.filter((L)=>L!==V.id);return F.splice(E-1,0,V.id),(await X.reorder(F,G)).outcome==="unchanged"?`${U} is already at position ${E}.`:`Moved ${U} to position ${E}.`}});return M.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await X.remove(V.id,{...G,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${U}.`}}),{id:V.id,label:U,detail:N,group:"Accounts",status:K,account:D,actions:M}}),H=$.accounts?.login,W=[];if(H&&!B)W.push({id:"add",label:H.label??"Add account",group:_$,knobs:H.knobs??[],run:async({values:V,invocation:j})=>{let D=await H.run(V,j);if(D.status==="cancelled")return{ok:!1,text:D.message??"Login cancelled."};if(D.status==="ready"){let U=await X.add(D.account,G);return _4(D.account.label??U.id,U)}return D.completion.then(async(U)=>{if(!U){j.notify("Login cancelled.","warning");return}let N=await X.add(U,G);j.notify(_4(U.label??N.id,N))},(U)=>{j.notify(`Adding the account failed: ${O4(U)}`,"error")}).catch((U)=>{j.notify(`Adding the account failed: ${O4(U)}`,"error")}),D.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[Z.rows.length===0?"No accounts yet":`${P4(Z.rows.length,"account")}, ${Q} enabled`],items:B?[]:Y,actions:W}}}function XJ($,Z){let X=$.quota?.scope??"all",J=$.now(),G=X==="all"?"Accounts":`Accounts · ${X}`,z=async(W,V)=>{if($.quota?.check)await $.quota.check(W,V);else{for(let j of W)$.store.requestReading(j);await $.store.pullsSettled()}},B=Z.rows.filter((W)=>W.candidate),Q=B.map((W)=>{let{account:V,name:j}=R6(W,$),D=S6(W,X);return{id:W.id,label:j,group:G,status:C0(D,{now:J,form:"compact"}),detail:C0(D,{now:J,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await z([W.id],U),`Checked quota for ${j}.`}}]}}),Y=Z.rows.filter((W)=>!W.candidate).map((W)=>{let{name:V}=R6(W,$),j=W.invalid?"invalid":!W.enabled?"disabled":W.credential===void 0?"no credential":"unavailable",D=C0(S6(W,X),{now:J,form:"compact"});return`${V} (${j}): ${D}`}),H=[];if(B.length>0)H.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:_$,run:async({invocation:W})=>{let V=B.map((j)=>j.id);return await z(V,W),`Checked quota for ${P4(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Y,items:Q,actions:H}}}function JJ($,Z){let{store:X,extraLocks:J}=$,G=J?{extraLocks:J}:{},z=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=l0(Z.settings.routing).mode,Q=typeof B==="string"&&z.some((U)=>U.value===B)?B:"ordered",Y=FZ(Q),H=Z.rows.map((U)=>U.id),W=f1(H,Y.placement,$.routing?.formerMainId??G6),j=[`Mode: ${z.find((U)=>U.value===Q)?.label??Q}`];if(H.length>0)j.push(`Roster order: ${H.join(", ")}`);if(Y.mode==="ordered"&&W.join()!==H.join())j.push(`Tried in order: ${W.join(", ")}`);let D=[{id:"mode",label:"Change mode",group:_$,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:z,value:Q}],run:async({values:U})=>{let N=String(U.mode);return await X.updateSettings((K)=>{K.routing={...l0(K.routing),mode:N};return},G),`Routing mode set to ${z.find((K)=>K.value===N)?.label??N}.`}}];if(H.length>1)D.push({id:"order",label:"Set order",group:_$,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:H.join(", "),required:!0}],run:async({values:U})=>{let N=String(U.order).split(/[\s,]+/).filter((M)=>M.length>0),K=await X.reorder(N,G);return K.outcome==="unchanged"?"The order is unchanged.":`Order set to ${K.ids.join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:D}}}function GJ($,Z){if($.limits?.labels)return[...$.limits.labels];let X=$.quota?.scope??"all",J=[];for(let G of Z.rows)for(let z of S6(G,X)?.limits??[])if(!J.includes(z.label))J.push(z.label);return J.length>0?J:["primary"]}function zJ($,Z){let X=$.quota?.scope??"all",J=new Map;for(let G of Z.rows)for(let z of S6(G,X)?.limits??[])if(z.windowMinutes!==void 0&&!J.has(z.label))J.set(z.label,X6(z));return(G)=>J.get(G)??G}function BJ($,Z){let{store:X,extraLocks:J}=$,G=J?{extraLocks:J}:{},z=l0(Z.settings.killswitch),B=z.enabled===!0,Q=l0(z.accounts),Y=GJ($,Z),H=zJ($,Z),W=B?"on":"off",V=Z.rows.map((j)=>{let{account:D,name:U}=R6(j,$),N=l0(Q[j.id]),K=Y.filter((M)=>typeof N[M]==="number");return{id:j.id,label:U,group:`Floors · killswitch ${W}`,status:K.length===0?"no floors":K.map((M)=>`${H(M)} ≥${N[M]}%`).join(" · "),account:D,actions:[{id:"floors",label:"Set floors",knobs:Y.map((M)=>({kind:"number",id:M,label:`Minimum % left for ${H(M)}`,min:0,max:100,...typeof N[M]==="number"?{value:N[M]}:{}})),run:async({values:M})=>{return await X.updateSettings((P)=>{let E=l0(P.killswitch),F=l0(E.accounts),q=l0(F[j.id]);for(let L of Y){let S=M[L];if(typeof S==="number")q[L]=S;else if(S===null)delete q[L]}if(Object.keys(q).length>0)F[j.id]=q;else delete F[j.id];if(Object.keys(F).length>0)E.accounts=F;else delete E.accounts;P.killswitch=E;return},G),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${W}`],items:V,actions:[{id:"killswitch",label:B?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:_$,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:j})=>{let D=j.enabled===!0;return await X.updateSettings((U)=>{U.killswitch={...l0(U.killswitch),enabled:D};return},G),`Killswitch ${D?"on":"off"}.`}}]}}}async function T4($){let Z=await $J($.store);return[ZJ($,Z),XJ($,Z),JJ($,Z),BJ($,Z)]}var QJ=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),Y3=["accounts","quota","routing","limits"];function A4($,Z){let{sessionId:X}=$,J=$.notify.bind($);return Object.freeze({...X!==void 0?{sessionId:X}:{},notify:(G,z)=>z===void 0?J(Z(String(G))):J(Z(String(G)),z)})}function YJ($,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 HJ($,Z){let X={};for(let J of $){let G=Z&&Object.hasOwn(Z,J.id)?Z[J.id]:void 0,z=YJ(J,G);if("problem"in z)return z;X[J.id]=z.value}return{values:X}}function WJ($,Z){let X=$.find((G)=>G.id===Z.sectionId);if(!X)return;return(Z.itemId===void 0?X.content.actions:X.content.items?.find((G)=>G.id===Z.itemId)?.actions)?.find((G)=>G.id===Z.actionId)}function _1($){let Z=$.logger??a("commands"),X=B3($.redaction),J={logger:Z,redact:X},G=$.now??Date.now,z=$.extras??[],B=$.replace??{},Q=Y3.filter((j)=>!B[j]);for(let j of Y3)if(B[j]&&$[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let Y=$.store;if(Q.length>0&&!Y)throw Error(`a store is required for the built-in ${Q.join(", ")} section${Q.length>1?"s":""}`);let H=new Set;for(let j of z){if(QJ.has(j.id)||H.has(j.id))throw Error(`extra section id ${j.id} is taken`);H.add(j.id)}async function W(j,D,U,N){try{return{id:j,slot:D,title:U.title,content:await U.build(N)}}catch(K){return Z.warn("command menu section failed to build",{command:$.command,section:j,error:X(K instanceof Error?K.message:String(K))}),{id:j,slot:D,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let D=Y&&Q.length>0?await T4({store:Y,now:G,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],U=[];for(let N of Y3){let K=B[N];if(K)U.push(await W(N,N,K,j));else{let M=D.find((P)=>P.slot===N);if(M)U.push(M)}}if($.cache)U.push(await W("cache","cache",$.cache,j));if($.diagnostics)U.push(await W("diagnostics","diagnostics",$.diagnostics,j));for(let N of z)U.push(await W(N.id,"extra",N,j));return U}return{command:$.command,async open(j){let D=A4(j,X);return F4($.command,$.title,await V(D),J)},async apply(j,D){let U=A4(D,X),N=async(F)=>L4($.command,$.title,await V(U),F,J),K=j.command===$.command?WJ(await V(U),j):void 0;if(!K)return N({ok:!1,code:"unavailable",text:"That action is no longer available."});let M=Q3(K);if(M&&j.confirmed!==!0)return N({ok:!1,code:"needs-confirmation",text:M.message,needsConfirmation:!0});let P=HJ(K.knobs??[],j.values);if("problem"in P)return N({ok:!1,code:"invalid-input",text:P.problem});let E;try{let F=await K.run({values:P.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:U});E=typeof F==="string"?{ok:!0,text:F}:{ok:F.ok,text:F.text,...F.ok?{}:{code:F.code??"refused"}}}catch(F){let q=L$(F);Z.warn("command menu action failed",{command:$.command,section:j.sectionId,action:j.actionId,code:q.code,error:X(F instanceof Error?F.message:String(F))}),E={ok:!1,...q}}return N(E)}}}async function O$($,Z,X){let J=new Map,G=[];for(let B of X){let Q=B.label;for(let Y=2;J.has(Q);Y++)Q=`${B.label} (${Y})`;J.set(Q,B.value),G.push(Q)}let z=await $.select(Z,G);return z===void 0?void 0:J.get(z)}function S4($,Z){return Z.length>0?`${$}
1
+ import{createRequire as M5}from"node:module";var F5=M5(import.meta.url);import{createAssistantMessageEventStream as WB}from"@earendil-works/pi-ai";import{streamSimple as VB}from"@earendil-works/pi-ai/compat";var a="all",UZ=Object.freeze(["primary"]);function u8($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function k1($,Z){return JSON.stringify([$,Z])}function K1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j0($){return typeof $==="number"&&Number.isFinite($)}function p8($){return typeof $==="string"&&$.length>0}function O0($,Z,X){return $[Z]===void 0||X($[Z])}function L5($){return j0($)&&$>0}function VZ($){return typeof $==="string"}function _5($){if(!K1($)||!p8($.scope)||!p8($.label))return!1;switch($.kind){case"reading":return j0($.checkedAt)&&j0($.usedPercent)&&O0($,"resetsAt",VZ)&&O0($,"windowMinutes",L5);case"retired":return j0($.retiredAt);case"absent":return j0($.checkedAt);default:return!1}}function O5($){if(!K1($)||!j0($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&O0($,"remainingPercent",j0)&&O0($,"usedPercent",j0)&&O0($,"resetsAt",VZ)&&O0($,"limit",j0)&&O0($,"used",j0)&&O0($,"remaining",j0)&&O0($,"unit",VZ)}function l8($){return K1($)&&j0($.value)&&Number.isInteger($.value)&&$.value>=0&&j0($.checkedAt)}function jZ($){return K1($)&&Object.values($).every(l8)}function DZ($){if(!K1($))return;let Z=Object.entries($).filter(([,X])=>l8(X));return Z.length===0?void 0:Object.fromEntries(Z)}function q1($){if(B0($))return $;if(!K1($))return;let{counters:Z,...X}=$;if(!B0(X))return;let J=DZ(Z);return{...X,...J===void 0?{}:{counters:J}}}function B0($){if(!K1($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!_5(X))return!1;let J=k1(X.scope,X.label);if(Z.has(J))return!1;Z.add(J)}return O0($,"budget",O5)&&O0($,"counters",jZ)}class e$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function Z6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function $6($){return typeof $==="number"&&Number.isFinite($)}function d8($){return $===void 0||typeof $==="string"&&$!==""}function c8($){return typeof $==="string"&&$!==""}function Y$($,Z){return $[Z]===void 0||$6($[Z])}function KZ($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function C5($){return Z6($)&&d8($.scope)&&c8($.label)&&$6($.usedPercent)&&KZ($,"resetsAt")&&($.windowMinutes===void 0||$6($.windowMinutes)&&$.windowMinutes>0)}function P5($){return Z6($)&&d8($.scope)&&c8($.label)}function T5($){if(!Z6($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&Y$($,"remainingPercent")&&Y$($,"usedPercent")&&KZ($,"resetsAt")&&Y$($,"limit")&&Y$($,"used")&&Y$($,"remaining")&&KZ($,"unit")}function s8($){if(!Z6($)||!$6($.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(!C5(z))return!1;let G=k1(z.scope??a,z.label);if(J.has(G))return!1;J.add(G)}if(!X.every(P5))return!1;return($.budget===void 0||T5($.budget))&&($.counters===void 0||jZ($.counters))}function A5($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function S5($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function R5($,Z){let X=new Map(Object.entries($??{}));for(let[J,z]of Object.entries(Z??{})){let G=X.get(J);if(G===void 0||z.checkedAt>=G.checkedAt)X.set(J,z)}return X.size===0?void 0:Object.fromEntries(X)}function E0($,Z){let X=$===void 0?void 0:q1($);if($!==void 0&&X===void 0)throw new e$("stored quota map is malformed");if(!s8(Z))throw new e$("quota observation is malformed");let J=X??{limits:[]},z=Z.checkedAt,G=new Map;for(let U of J.limits)G.set(k1(U.scope,U.label),U);let Q=(U)=>{let N=G.get(U);return N===void 0||z>=u8(N)},B=new Set;for(let U of Z.readings??[]){let N=U.scope??a,K=k1(N,U.label);if(B.add(K),!Q(K))continue;G.set(K,{scope:N,label:U.label,kind:"reading",checkedAt:z,usedPercent:U.usedPercent,...U.resetsAt===void 0?{}:{resetsAt:U.resetsAt},...U.windowMinutes===void 0?{}:{windowMinutes:U.windowMinutes}})}for(let U of Z.coverage??[]){let N=U.scope??a,K=k1(N,U.label);if(B.has(K)||!Q(K))continue;let M=G.get(K);G.set(K,M===void 0||M.kind==="absent"?{scope:N,label:U.label,kind:"absent",checkedAt:z}:{scope:N,label:U.label,kind:"retired",retiredAt:z})}let{limits:Y,budget:H,counters:V,...W}=J,j=S5(J.budget,Z.budget,z),D=R5(J.counters,Z.counters);return{...W,limits:[...G.values()].sort(A5),...j===void 0?{}:{budget:j},...D===void 0?{}:{counters:D}}}var qZ=Object.freeze({validate:B0,decode:q1,merge:E0});var r8=900000,o8="no quota reading yet",t8="no limits reported";function e8($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let z=Math.floor(Z/60),G=Z%60;return G===0?`${z}h`:`${z}h${G}m`}let X=Math.floor(Z/1440),J=Math.floor(Z%1440/60);return J===0?`${X}d`:`${X}d${J}h`}function E5($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function X6($){if($.scope!==a||$.windowMinutes===void 0)return $.label;return E5($.windowMinutes)}function NZ($){return Math.min(100,Math.max(0,$))}function MZ($){return Math.round(NZ($))}function i8($){return`${MZ($)}% left`}function a8($,Z,X){let J=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(J)&&J>X?{resetIn:e8(J-X)}:{},resetSinceReading:Number.isFinite(J)&&J>Z&&J<=X}}function I5($,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===a)return-1;if(Z.scope===a)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function $9($,Z){let{windows:X,age:J}=Z9($,Z),z=X.map(({part:G})=>G);return J===void 0?{windows:z}:{windows:z,age:J}}function Z9($,Z){if(!$)return{windows:[]};let{now:X}=Z,z=$.limits.filter((Q)=>Q.kind==="reading"&&Q.remainingPercent!==void 0).sort(I5).map((Q)=>{let B=NZ(Q.remainingPercent??0);return{scope:Q.scope,part:{kind:"window",name:X6(Q),figure:i8(Q.remainingPercent??0),remainingPercent:B,checkedAt:Q.checkedAt,...a8(Q.resetsAt,Q.checkedAt,X)}}}),G=$.budget;if(G){let Q=G.remainingPercent,B=G.reached?"credits spent":Q!==void 0?`credits ${i8(Q)}`:"credits available";z.push({scope:a,spent:G.reached,part:{kind:"budget",name:"credits",figure:B,...Q===void 0?{}:{remainingPercent:NZ(Q)},checkedAt:G.checkedAt,...a8(G.resetsAt,G.checkedAt,X)}})}if(z.length>0){let Q=X-Math.min(...z.map(({part:B})=>B.checkedAt));if(Q>(Z.staleAfterMs??r8))return{windows:z,age:`checked ${e8(Q)} ago`}}return{windows:z}}function n8($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function b5($){let Z=[...new Set($.map(n8))],X=new Map(Z.map((z)=>[z,2])),J=(z)=>z.slice(0,X.get(z));for(;;){let z=new Map;for(let Q of Z)z.set(J(Q),[...z.get(J(Q))??[],Q]);let G=!1;for(let Q of z.values()){if(Q.length<2)continue;for(let B of Q){let Y=X.get(B)??2;if(Y<B.length)X.set(B,Y+1),G=!0}}if(!G)break}return new Map($.map((z)=>[z,J(n8(z))]))}function x5($,Z){let{windows:X}=Z9($,Z),J=X.filter(({part:W,scope:j})=>W.kind==="window"&&j===a),z=X.filter(({part:W,scope:j})=>W.kind==="window"&&j!==a),G=b5(z.map(({scope:W})=>W)),Q=X.find(({part:W})=>W.kind==="budget"),B=Q?.spent?0:Q?.part.remainingPercent,H=[...z.map(({scope:W,part:j})=>({label:G.get(W)??W,remaining:j.remainingPercent??0})),...B===void 0?[]:[{label:"cr",remaining:B}]].reduce((W,j)=>W===void 0||j.remaining<W.remaining?j:W,void 0),V=J.map(({part:W})=>`${W.name} ${MZ(W.remainingPercent??0)}%`);if(H)V.push(`${H.label} ${MZ(H.remaining)}%`);if(V.length===0)return X.map(({part:W})=>W.figure);return V.map((W,j)=>j===V.length-1?`${W} left`:W)}function y1($,Z){if(Z.form==="narrow")return x5($,Z);let X=$9($,Z),J=(Z.form??"full")==="full",z=X.windows.map((G)=>{let Q=J&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${Q}`});return X.age===void 0?z:[...z,X.age]}function C0($,Z){let X=y1($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?t8:o8}function k5($){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 y5($,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 f5($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function s($,Z=a){let X=new Map;for(let H of $?.limits??[]){if(H.scope!==Z&&H.scope!==a)continue;let V=X.get(H.label);if(V===void 0){X.set(H.label,H);continue}let W=H.scope===a?V:H,j=H.scope===a?H:V;X.set(H.label,W.kind==="reading"?W:j)}let J=[...X.values()].map(k5).sort(y5),z=J.filter((H)=>H.kind==="reading"),G=z.length>0?z:J,Q=G.length>0?Math.min(...G.map((H)=>H.checkedAt)):void 0,B=$?.budget?.kind==="reading"?f5($.budget):void 0,Y=DZ($?.counters);return{scope:Z,limits:J,...Q===void 0?{}:{checkedAt:Q},...B===void 0?{}:{budget:B},...Y===void 0?{}:{counters:Y}}}function H$($,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 FZ($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function J6($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}function X9($,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 g5($,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(FZ);for(let G of z)if(J6(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=J6(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 h0($){let Z=$.scope??a,X=$.requiredLabels??UZ,J=[],z=[],G=[];for(let j of $.rows){let D=X9(j.id,$,$.now);if(D){J.push(D);continue}if(j.kind==="api-key"){G.push({id:j.id,kind:j.kind});continue}let U=s(j.quota,Z),N=g5(j.id,U,X,$.now);if(N){z.push(N);continue}G.push({id:j.id,kind:j.kind,projection:U})}let Q=new Map(G.flatMap((j)=>{let D=H$(j.projection,$.now);return D?[[j.id,D]]:[]})),B=Q.size>0&&Q.size===G.length,Y=[];for(let j of G){let D=Q.get(j.id);if(D===void 0)Y.push(j);else if(B)Y.push({...j,lastPath:!0});else z.push({id:j.id,stage:2,reason:"budget-spent",...D})}let H=new Map($.rows.map((j,D)=>[j.id,D])),V=(j,D)=>(H.get(j.id)??0)-(H.get(D.id)??0);z.sort(V);let W=z.filter((j)=>("pullRequested"in j)).map((j)=>j.id);for(let j of W)$.requestPull?.(j);return{admitted:Y,refused:z,excluded:J,pulls:W}}var z6="main";function LZ($){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 f1($,Z,X=z6){if(Z==="roster"||!$.includes(X))return[...$];let J=$.filter((z)=>z!==X);return Z==="main-first"?[X,...J]:[...J,X]}function _Z($){let Z=h0($),X=new Set(Z.admitted.map((z)=>z.id));return{order:f1($.rows.map((z)=>z.id),$.placement??"roster",$.formerMainId).filter((z)=>X.has(z)&&$.killswitch?.get(z)!==!1),admission:Z}}function OZ($,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 W$($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function CZ($,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 AZ=900000,z9=0.016666666666666666,PZ=0.000001;function G6($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function G9($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function Q9($){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 SZ($){let Z=($.classifyStatus??G9)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=G6($.quota,$.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||$.now-X>AZ)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let z of Q9($.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=H$($.quota,$.now);if(J)return{action:"migrate",reason:"exhausted",resetsAt:J.resetsAt};return{action:"retain",reason:Z}}function TZ($,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,z9);return J/G}function J9($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function h5($,Z){if(!$.quota)return;let X=G6($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>AZ)return;let J=Q9($.quota).map((Q)=>TZ({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(TZ({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 B9($){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)=>h5(z,$.now)).filter((z)=>z!==void 0);if(X.length>0){X.sort((G,Q)=>{let B=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,PZ),Y=(($.pendingBytes.get(Q.candidate.accountId)??0)+$.requestBytes)/Math.max(Q.weight,PZ);return B-Y||G.candidate.configuredOrder-Q.candidate.configuredOrder||J9(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||J9(z.accountId,G.accountId)})[0];if(!J)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:J.accountId,quotaCheckedAt:G6(J.quota,J.quotaCheckedAt),source:"mode-fallback"}}function RZ($){let Z=h0($),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&&W$($.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 B=$.pin?J.get($.pin.accountId):void 0,Y=Q&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),H=(U)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(U):$.rowReservePercent?.get(U.id))??$.reservePercent??{}},V=$.scope,W=$.rows.map((U,N)=>({row:U,configuredOrder:N})).filter(({row:U})=>!z.has(U.id)).map(({row:U,configuredOrder:N})=>{let K=$.killswitch?.get(U.id),M=$.resetCreditsApplicable?.get(U.id);return{accountId:U.id,quota:U.kind==="api-key"?void 0:X.get(U.id)?.projection??s(U.quota,V),reservePercent:H(U),configuredOrder:N,...M===void 0?{}:{resetCreditsApplicable:M},...K===void 0?{}:{killswitchPasses:K}}}),j=[],D=Q?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(W.length>0){let U=B9({candidates:W,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!U)break;let N=J.get(U.accountId);if(N){j.push(N),W=W.filter((M)=>M.accountId!==U.accountId);continue}let K=$.identities?.get(U.accountId);return{outcome:"dispatch",accountId:U.accountId,source:U.source,...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt},pin:Q&&!Y?{action:"retain"}:{action:"assign",pin:{accountId:U.accountId,inputBytes:$.requestBytes,...K===void 0?{}:{wireIdentity:K},...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt}}},refusedSelections:j,admission:Z}}return{outcome:"no-admissible-account",pin:D,refusedSelections:j,admission:Z}}import{appendFileSync as s5,chmodSync as i5,existsSync as xZ,renameSync as K9,statSync as a5}from"node:fs";import{open as n5}from"node:fs/promises";import{dirname as r5,resolve as o5}from"node:path";import{randomUUID as v5}from"node:crypto";import{lstat as V9,readFile as U9,rename as m5,unlink as Y9}from"node:fs/promises";import{dirname as i0,resolve as N0}from"node:path";var I=process.platform==="win32",H9=new Set;function EZ($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var W9;function g1(){return W9??=import("@cortexkit/private-files"),W9}class d extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,X){let J=X;super(`Private file refused at ${Z}: ${$} (${J?.reason??J?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:X});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=EZ(J),this.win32Code=J?.win32Code,this.reason=J?.reason}}async function D0($,Z,X){try{return await X()}catch(J){if(J instanceof d)throw J;throw new d($,Z,J)}}var w5;async function v0($,Z){$=N0($),Z??=w5,await D0($,"safe-parent",async()=>{let X=await(await g1()).verifySafeParent($,Z);if(X.ok===!1){if(X.reason==="io-error"||X.reason==="wrong-kind")await V9($);throw new d(X.level??X.path,"safe-parent",{...X,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function J0($,Z,X=!1){if($=N0($),Z==="directory")return v0($);await D0($,"verify",async()=>{let J=await g1(),z=await J.verifyOwnerOnly($),G=!1;if(!z.ok){let{reason:Q}=z.refusal;if(Q==="io-error")await J.verifyPrivatePath($,Z);if(X&&[J.EXTRA_ACE,J.NOT_PROTECTED,J.NULL_DACL,J.EMPTY_DACL].includes(Q))await v0(i0($)),await J.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:Q,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await J.verifyPrivatePath($,Z),G&&!H9.has($))H9.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function K0($,Z=!1,X){$=N0($),await D0($,"directory",async()=>{let J=await g1();try{return await V9($),await v0($,X)}catch(G){if(EZ(G)!=="ENOENT")throw G}let z=i0($);if(z===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await K0(z,!1,X);try{await J.createOwnerOnly($,{kind:"dir"})}catch(G){if(EZ(G)!=="EEXIST")throw G}await v0($,X)})}async function M0($,Z=!1){if(!I)return U9($,"utf8");return(await IZ($,Z)).toString("utf8")}async function IZ($,Z=!1){if(!I)return U9($);if($=N0($),Z)await v0(i0($)),await J0($,"file",!0);return D0($,"read",async()=>(await g1()).readOwnerOnly($))}async function h1($,Z){await v0(i0(N0($))),await D0($,"create",async()=>{await(await g1()).createPrivateFile(N0($),Z)})}async function j9($){await v0(i0(N0($))),await D0($,"directory-create",async()=>{await(await g1()).createOwnerOnly(N0($),{kind:"dir"})})}async function bZ($,Z,X={}){$=N0($),Z=N0(Z);let J=X.now??(()=>performance.now()),z=J(),G=Math.min(z+500,X.deadline??1/0),Q=[0,10,20,40,80,100],B,Y=0;for(let V of Q){if(J()>=G)break;if(V)await(X.sleep??((W)=>new Promise((j)=>setTimeout(j,W))))(Math.min(V,Math.max(0,G-J())));if(J()>=G)break;if(await X.beforeRename?.(),J()>=G)break;Y++;try{return await(X.rename??m5)($,Z),{attempts:Y,elapsedMs:J()-z}}catch(W){B??=W;let j=W;if(!(j.win32Code!==void 0?j.win32Code===32||j.win32Code===33:["EBUSY","EPERM","EACCES"].includes(j.code??"")&&!j.reason))break}}let H=new d(Z,"rename",B??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw H.attempts=Y,H.elapsedMs=J()-z,H}async function v1($,Z,X={}){$=N0($),await K0(i0($));try{await J0($,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}let J=N0(X.stagePath??`${$}.${v5()}.tmp`);if(i0(J)!==i0($))throw new d($,"stage-directory",{code:"EXDEV"});let z=!1,G=!1,Q={attempts:0,elapsedMs:0},B="stage-create",Y=(H)=>{try{X.onOutcome?.({path:$,stage:H?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:H?.attempts??Q.attempts,elapsedMs:H?.elapsedMs??Q.elapsedMs,...H&&{code:H.code,win32Code:H.win32Code}})}catch{}};try{if(await h1(J,Z),z=!0,B="before-rename",Q=await bZ(J,$,X),z=!1,G=!0,B="published-callback",X.onRenamed?.(),B="published-verify",await J0($,"file"),X.durable&&X.durability!=="file-only-on-windows")throw new d($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(H){let V=H instanceof d?H:new d($,B,H);if(V.published=G,V.fileDurable=G,G)Object.assign(V,Q);if(z){try{await Y9(J)}catch{V.orphanPath=J}z=!1}throw Y(V),V}finally{if(z)await Y9(J).catch(()=>{})}}var p5=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,u5=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function l5($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function I0($={}){let Z=[u5,...$.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 p5.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,B=[["name",G.name],["message",G.message],["stack",G.stack]];for(let H of["code","status","cause"])if(Q[H]!==void 0)B.push([H,Q[H]]);let Y=new Set(B.map(([H])=>H));for(let H of Object.entries(G))if(!Y.has(H[0]))B.push(H);return B}function z(G,Q,B,Y=0){if(typeof G==="string")return Z.reduce((H,V)=>H.replace(V,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(B.has(G))return"[Circular]";B.add(G);try{if(Array.isArray(G))return G.map((W)=>z(W,Q,B,Y));let H=l5(G);if(H&&Y>=8)return"[Truncated]";let V=H?Y+1:Y;return Object.fromEntries((H?J(G):Object.entries(G)).map(([W,j])=>[W,Q&&X(W)?"***REDACTED***":z(j,Q,B,V)]))}finally{B.delete(G)}}return{redact:(G)=>z(G,!0,new WeakSet),redactStrings:(G)=>z(G,!1,new WeakSet)}}var D9=I0(),d5=D9.redact,c5=D9.redactStrings;var Q6={error:0,warn:1,info:2,debug:3,trace:4},N9=5242880,M9=3;function kZ($){try{i5($,384)}catch{}}function t5($){try{if(!(xZ($)&&a5($).size>=N9))return;for(let X=M9-1;X>=1;X--)if(xZ(`${$}.${X}`)){let J=`${$}.${X+1}`;K9(`${$}.${X}`,J),kZ(J)}let Z=`${$}.1`;K9($,Z),kZ(Z)}catch{}}async function m0($){let{file:Z,handle:X}=$;if($.file=void 0,$.handle=void 0,Z&&X)await D0(Z,"log-close",()=>X.close())}async function q9($,Z){await K0(r5(Z));try{await J0(Z,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X;try{await h1(Z,"")}catch(J){if(J.code!=="EEXIST")throw J;await J0(Z,"file",!0)}}return $.handle=await D0(Z,"log-open",()=>n5(Z,"a")),$.file=Z,$.handle}async function e5($,Z,X){Z=o5(Z);try{if($.file!==Z)await m0($);let J=$.handle??await q9($,Z);if((await D0(Z,"log-stat",()=>J.stat())).size>=N9){await m0($);for(let G=M9-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,B=`${Z}.${G+1}`;try{await J0(Q,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await J0(B,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await bZ(Q,B),await J0(B,"file")}J=await q9($,Z)}await D0(Z,"log-append",()=>J.appendFile(X,"utf8"))}catch(J){throw await m0($).catch(()=>{}),J}}function $X($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function ZX($){let Z,X,J,z=I0(),G,Q=[],B,Y=Promise.resolve(),H,V={};function W(q){let L=Y.then(q);return Y=L.catch((S)=>{H=S}),L}function j(q){if(I&&q.file!==Z)W(()=>m0(V)).catch(()=>{});Z=q.file,X=q.level,z=I0(q),G=q.captureSink}function D(q){if(q===void 0||q in Q6)J=q}function U(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function N(){if(J)return J;let q=typeof X==="function"?X():X;if(q&&q in Q6)return q;return"info"}function K(q=!0){if(B)clearTimeout(B),B=void 0;if(!Q.length){if(I)return W(async()=>{if(q)await m0(V);if(H)throw H});return}let L;try{L=U()}catch{if(Q=[],I&&q)return W(()=>m0(V));return}let S=Q.join("");if(Q=[],!L){if(I&&q)return W(()=>m0(V));return}if(I)return W(async()=>{try{await e5(V,L,S)}finally{if(q)await m0(V)}});try{if(t5(L),xZ(L))kZ(L);s5(L,S,{encoding:"utf8",mode:384})}catch{}}function M(){if(!B)B=setTimeout(()=>{B=void 0;let q=K(!1);if(q instanceof Promise)q.catch(()=>{})},500)}function P(q,L,S,A){if(Z===void 0&&G===void 0)return;try{if(Q6[L]>Q6[N()])return;let x=z.redactStrings(S),w;try{w=z.redact(A)}catch{w="[unserializable]"}let y=`[${new Date().toISOString()}] ${L.toUpperCase()} [${q}] ${x}`+(A===void 0?"":$X(w))+`
2
+ `;try{G?.({channel:q,level:L,message:x,data:w})}catch{}if(Z===void 0)return;if(Q.push(y),Q.length>=50){let f=K(!1);if(f instanceof Promise)f.catch(()=>{})}else M()}catch{}}function E(q){return{error:(L,S)=>P(q,"error",L,S),warn:(L,S)=>P(q,"warn",L,S),info:(L,S)=>P(q,"info",L,S),debug:(L,S)=>P(q,"debug",L,S),trace:(L,S)=>P(q,"trace",L,S)}}function F(){if(I)W(()=>m0(V)).catch(()=>{});if(H=void 0,Q=[],B)clearTimeout(B),B=void 0;Z=void 0,X=void 0,J=void 0,z=I0(),G=void 0}if($)j($);return{configure:j,createLogger:E,setLogLevel:D,flushLogs:K,reset:F}}var XX=ZX();function n($){return XX.createLogger($)}class g 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 B6 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 m1="identity-contradicted: ",yZ="duplicate-identity";function a0($,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 V$($,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 w1($,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))a0($,z.id,"duplicate-identity"),J.push(z.id);return J}function N1($,Z,X){let J=$.rosterRow(Z);if(!J)return[];return J.accountId=X,w1($,X)}import{setTimeout as bX}from"node:timers/promises";import{randomUUID as F9}from"node:crypto";import{mkdir as YX,open as Y6,rename as HX,rm as WX}from"node:fs/promises";import{dirname as fZ}from"node:path";class U$ extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function F0($,Z,X={}){await gZ($,Z,X)}async function gZ($,Z,X,J){if(I)return v1($,X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
3
+ `,{beforeRename:X.beforeRename,stagePath:`${$}.${(X.stageName??F9)()}.tmp`,onRenamed:J,durable:X.durable,durability:X.durability,onOutcome:X.onOutcome});await YX(fZ($),{recursive:!0});let z=`${$}.${(X.stageName??F9)()}.tmp`,G,Q=!1;try{if(G=await Y6(z,"wx",384),Q=!0,await G.writeFile(X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
4
+ `,"utf8"),await G.chmod(384),X.durable)try{await G.sync()}catch(B){throw new U$(B)}if(await G.close(),G=void 0,await X.beforeRename?.(),await HX(z,$),Q=!1,J?.(),X.durable){let B=await Y6(fZ($),"r");try{await B.sync()}catch(Y){throw new U$(Y)}finally{await B.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await WX(z,{force:!0}).catch(()=>{})}}async function hZ($){if(I){await J0($,"file");let J=new d($,"directory-sync-unsupported",{code:"ENOTSUP"});throw J.published=!0,J}let Z=await Y6($,"r");try{await Z.sync()}finally{await Z.close()}let X=await Y6(fZ($),"r");try{await X.sync()}finally{await X.close()}}import{randomUUID as H6}from"node:crypto";import{mkdir as L9,open as A9,readFile as _9,rename as O9,rm as W6,stat as C9}from"node:fs/promises";import{dirname as vZ,join as P9}from"node:path";async function T9($,Z){let X=await A9($,"wx",384);try{await X.writeFile(Z,"utf8")}finally{await X.close()}}var VX=globalThis.setTimeout.bind(globalThis),UX=globalThis.clearTimeout.bind(globalThis);function mZ($){let Z=$?.code;return Z==="ENOENT"||!I&&(Z==="EINVAL"||Z==="ENOTDIR")}function $0($){return jX({...$,now:Date.now})}async function jX($){let Z=wZ($.path,$.name),X=P9(Z,"owner.json"),J=H6(),z=$.now??Date.now,G=null,Q=!1,B=!1,Y,H,V=new Promise((C)=>{H=C});function W(C){try{let T=$.onRenewalTimer?.(C);if(T&&(typeof T==="object"||typeof T==="function")&&"then"in T&&typeof T.then==="function")Promise.resolve(T).catch(()=>{})}catch{}}function j(){if(!G)return;UX(G),G=null,W("cancelled")}function D(C,T){if(Y||Q)return;Y=Object.freeze({reason:C,expectedOwnerId:J,...typeof T?.ownerId==="string"?{observedOwnerId:T.ownerId}:{},...typeof T?.expiresAt==="number"?{observedExpiresAt:T.expiresAt}:{}}),j(),H(Y)}let U,N=null,K=`${Z}.evicting`,M=P9(K,"owner.json"),P=H6(),E=5000,F=8;async function q(){if(I)try{return JSON.parse(await M0(Z,!0))}catch(C){if(C.code!=="EISDIR"&&C.reason!=="wrong-kind")throw C;return await J0(Z,"directory",!0),JSON.parse(await M0(X,!0))}try{return JSON.parse(await _9(Z,"utf8"))}catch(C){if(C.code!=="EISDIR")throw C;return JSON.parse(await _9(X,"utf8"))}}async function L(){if(I){let u=await q(),t=Number(u?.expiresAt)-z();await v1(Z,`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
5
+ `,{deadline:performance.now()+Math.max(0,t),beforeRename:async()=>{let t$=await q();if(t$?.ownerId!==J||!(Number(t$?.expiresAt)>z())||!await h())throw new n0({target:$.path,name:$.name})}});return}let C=`${Z}.${H6()}.tmp`,T,b=!1;try{T=await A9(C,"wx",384),b=!0,await T.writeFile(`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
6
+ `,"utf8"),await T.chmod(384),await T.close(),T=void 0;let u=await q();if(u?.ownerId!==J||!(Number(u?.expiresAt)>z())||!await h())throw new n0({target:$.path,name:$.name});await O9(C,Z),b=!1}finally{if(await T?.close().catch(()=>{}),b)await W6(C,{force:!0}).catch(()=>{})}}async function S(){let C=`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
7
+ `;if(I)await h1(Z,C);else await T9(Z,C)}async function A(C){let T=C.code;if(T==="EEXIST"){if(I)await q();return!0}if(T==="EISDIR"){if(I)await J0(Z,"directory",!0),await M0(X,!0);return!0}return!1}async function x(){if(I)await K0(vZ(Z));try{return await S(),!0}catch(C){let T=C.code;if(await A(C))return!1;if(T==="ENOENT"){if(I)await K0(vZ(Z));else await L9(vZ(Z),{recursive:!0});try{return await S(),!0}catch(b){if(await A(b))return!1;throw b}}throw C}}async function w(){await new Promise((C)=>setTimeout(C,Math.floor(Math.random()*4)))}async function y(C=!0){if(C&&$.onStep)await $.onStep("lock-read-ready");let T;try{T=await q()}catch(u){if(I&&u.code!=="ENOENT")throw u}let b=Number(T?.expiresAt);if(Number.isFinite(b)&&b>z())return{status:"live"};if(typeof T?.ownerId==="string"&&Number.isFinite(b))return{status:"stale",identity:{kind:"owner",ownerId:T.ownerId,expiresAt:b}};try{let u=await C9(Z),t=Number.isFinite(b)?b:u.mtimeMs+$.ttlMs;if(t>z())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:u.dev,ino:u.ino,mtimeMs:u.mtimeMs,expiresAt:t}}}catch(u){if(u.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw u}}function f(C,T){if(T.status!=="stale")return!1;let b=T.identity;if(C.kind==="owner"&&b.kind==="owner")return C.ownerId===b.ownerId&&C.expiresAt===b.expiresAt;return C.kind==="stat"&&b.kind==="stat"&&C.dev===b.dev&&C.ino===b.ino&&C.mtimeMs===b.mtimeMs&&C.expiresAt===b.expiresAt}async function h(){try{return JSON.parse(await M0(M,I))?.ownerId===P}catch(C){if(I&&C.code!=="ENOENT")throw C;return!1}}async function o(C){if(I)await D0(C,"remove",()=>W6(C,{recursive:!0,force:!0}));else await W6(C,{recursive:!0,force:!0}).catch(()=>{})}async function c(){if(await h())await o(K)}async function r$(){if(I)await j9(K);else await L9(K);try{let C=`${JSON.stringify({ownerId:P,createdAt:z()})}
8
+ `;if(I)await h1(M,C);else await T9(M,C)}catch(C){if(mZ(C))return!1;throw await c(),C}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function x1(){let C;try{C=await C9(K)}catch(b){if(b.code==="ENOENT")return"missing";throw b}if(I)await J0(K,"directory",!0);if(C.mtimeMs+E>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let T=`${K}.${H6()}`;try{await O9(K,T)}catch(b){if(b.code==="ENOENT")return"missing";throw b}if($.onStep)await $.onStep("stale-marker-claimed");return await o(T),"recovered"}async function o$(C){try{if(!await r$())return!1}catch(T){if(T.code==="EEXIST"){if(I){await J0(K,"directory",!0);try{await M0(M,!0)}catch(b){if(b.code!=="ENOENT")throw b}}return!1}throw T}try{await C()}finally{await c()}return!0}async function v(){for(let C=0;C<F;C++){if($.onStep)await $.onStep("relinquish-read");let T;try{T=await q()}catch(b){if(I)throw b;return}if(T?.ownerId!==J)return;try{await W6(Z,{recursive:!0,force:!0});return}catch(b){if(I)throw b;await w()}}}function g0(){if(!$.renew||Q||Y)return;let C=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=VX(()=>{G=null;let T=(async()=>{let b=!Q;try{if(!await o$(async()=>{let t=await q(),t$=z();if(Q||Y){b=!1;return}if(t?.ownerId!==J){D("taken-over",t),b=!1;return}if(!(Number(t?.expiresAt)>t$)){D("expired",t),b=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||Y){b=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||Y){b=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||Y){b=!1;return}if(await L(),$.onStep)await $.onStep("renewal-write-finished");if(!await h()){D("marker-lost"),b=!1,await v();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(u){if(I&&u instanceof d)U=u,D("renewal-failed"),b=!1;try{let t=await q();if(t?.ownerId!==J)D("taken-over",t);else if(!(Number(t?.expiresAt)>z()))D("expired",t)}catch{D("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(b&&!Q&&!Y)g0()}})();N=T,T.finally(()=>{if(N===T)N=null})},C),"unref"in G)G.unref();W("scheduled")}function w8(){try{let C=$.onContended?.();if(C&&(typeof C==="object"||typeof C==="function")&&"then"in C&&typeof C.then==="function")Promise.resolve(C).catch(()=>{})}catch{}return null}let D1=await x();if(!D1)for(let C=0;C<F;C++){if(D1=await x(),D1)break;let T=await y();if(T.status==="live")return w8();if(T.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await r$()){await w();continue}}catch(b){if(b.code!=="EEXIST")throw b;if(await x1()==="fresh")return null;await w();continue}try{let b=await y();if(b.status==="live")return w8();if(!f(T.identity,b))continue;if(!await h())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await h())return null;let u=await y(!1);if(!f(T.identity,u))continue;if(await o(Z),!await h())return null;if($.onStep)await $.onStep("stale-lock-removed");if(D1=await x(),!D1)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await h())return await v(),D1=!1,null;break}finally{await c()}}if(!D1)return null;return g0(),{ownerId:J,whenLost:()=>V,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(U)throw U;let C;try{let T=await q();if(C=T,!Q&&!Y&&T?.ownerId===J&&Number(T?.expiresAt)>z())return;D(T?.ownerId!==J?"taken-over":"expired",T)}catch(T){if(D("unreadable"),I&&T instanceof d)throw T}throw new n0({target:$.path,name:$.name,expectedOwnerId:J,...typeof C?.ownerId==="string"?{observedOwnerId:C.ownerId}:{},...typeof C?.expiresAt==="number"?{observedExpiresAt:C.expiresAt}:{}})},release:async()=>{if(I&&B)return;Q=!0,j(),await N;for(let C=0;C<F;C++){try{let T=!1;if(await o$(async()=>{let u;try{u=await q()}catch(t){if(I&&t.code==="ENOENT"){T=!0;return}throw t}if(u?.ownerId!==J){T=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await h())return;await o(Z),T=!0})){if(I&&!T)throw new d(Z,"release-not-confirmed",{code:"EIO"});B=T;return}await x1()}catch(T){if(I)throw T;return}await w()}if(I)throw new d(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}function wZ($,Z){return`${$}.${Z}.lock`}class M1 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class n0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function pZ($,Z,X){let J=performance.now();for(;;){let z=await $0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(z)try{return await X(z)}finally{await z.release()}let G=Z.timeoutMs-(performance.now()-J);if(G<=0)throw new M1({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(G))))}}import{AsyncLocalStorage as DX}from"node:async_hooks";var S9=new DX;function z0($){if(S9.getStore()!==void 0)throw new B6($)}function b0($,Z){return S9.run($,async()=>await Z())}async function R9($,Z,X,J,z){if(!Z)return;try{await b0($,()=>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 uZ=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function KX($,Z,X){let J=(Q)=>{try{let B=X.onLockEvent?.({type:Q,name:$.name,path:$.path});if(B&&(typeof B==="object"||typeof B==="function")&&"then"in B&&typeof B.then==="function")Promise.resolve(B).catch(()=>{})}catch{}},z={...Z,...qX($)},G=performance.now();for(;;){let Q=await $0({name:$.name,path:$.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(H)=>X.onRenewalTimer?.({name:$.name,path:$.path},H)}:{},...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(V){throw await H.release(),V}return H}let B=z.timeoutMs-(performance.now()-G);if(B<=0)throw new M1({target:$.path,name:$.name,timeoutMs:z.timeoutMs});let Y=Math.floor(Math.random()*(z.retryMs+1));await new Promise((H)=>setTimeout(H,Math.min(z.retryMs+Y,B)))}}function qX($){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 r0{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await KX($,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 F1($,Z,X){if(X!==void 0)throw new g({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 j$}from"node:crypto";var p="commonAuthPool",o0=1,P0="rows",V6="retiredEpochs",D$=1,lZ=300000,m=p;function NX($){let Z=JSON.parse(JSON.stringify($)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(O(J))return`{${Object.keys(J).sort().map((z)=>`${JSON.stringify(z)}:${X(J[z])}`).join(",")}}`;return JSON.stringify(J)};return X(Z)}function L1($){return j$("sha256").update(NX($)).digest("hex")}function E9($){if(!O($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function MX($){if(!O($)||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 Y0="commonAuthProviderState";function O($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var FX=new Set(["__proto__","constructor","prototype"]);function p1($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(FX.has($))return"id is a reserved object key";return}function dZ($){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 I9($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function t0($){return j$("sha256").update(I9($)).digest("hex")}function x0($){return j$("sha256").update(`credential-stamp\x00${I9($)}`).digest("hex")}function w0($){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 j$("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function cZ($,Z,X,J={}){return{credentialEpoch:Z,digest:x0($),dispatch:w0($),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function u1($,Z){let X=$?.credentialBound?$.credentialBound(Z):Z;return j$("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function K$($,Z,X,J){if(!Z||X===void 0)return;if(!O($)||!Object.hasOwn($,Y0))return;let z=V0($[m]);if(!z||z.providerState===void 0||z.digest!==x0(Z)||z.credentialEpoch!==X||z.binding?.identity!==J)return;return z.providerState}function Z0($){return Number.isSafeInteger($)&&$>=1}function V0($){if(!O($))return;let Z=$.credentialEpoch;if(!Z0(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 $?MX($.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(!O(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!dZ(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 LX($,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 _X($,Z,X,J){if(!$)return"none";if(!O(J)||!Object.hasOwn(J,m))return"missing";let z=V0(J[m]);if(!z)return"malformed";if(z.digest!==x0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!LX(z.binding,$,X))return"mismatched";if(z.dispatch!==w0($))return"mismatched";return"bound"}function b9($){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(!O(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(!(p in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let X=Z[p];if(!O(X))return{status:"error",reason:`${p} is not an object`};let J=X.schemaVersion;if(typeof J!=="number"||!Number.isInteger(J)||J<1)return{status:"error",reason:`${p}.schemaVersion is invalid`};if(J>o0)return{status:"error",reason:`${p}.schemaVersion ${J} is newer than ${o0}`};if(P0 in X&&!O(X[P0]))return{status:"error",reason:`${p}.${P0} is not an object`};return{status:"ready",exists:!0,config:Z}}function x9($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!O($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!O($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function l1($){return Array.isArray($.accounts)?$.accounts:[]}function k9($){let Z=$[p];if(!O(Z))return{};let X=Z[P0];return O(X)?X:{}}function OX($){return O($.accounts)?$.accounts:{}}function CX($){if(!O($))return"not an object";let Z=p1($.id);if(Z)return Z;if($.type==="api")return dZ($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function PX($,Z){if(!O($))return;let X=$.credentialEpoch;if(!Z0(X))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let J="quota"in $&&Z.decode?Z.decode($.quota):$.quota;if("quota"in $&&!Z.validate(J))return;if("staged"in $&&!E9($.staged))return;return{credentialEpoch:X,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:J}:{}}}function TX($,Z){if(!O(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 U6($,Z){return l1($).find((X)=>O(X)&&X.id===Z)}function y9($){if(!O($[p]))$[p]={};return $[p]}function sZ($){let Z=y9($);if(!O(Z[P0]))Z[P0]={};return Z[P0]}function e0($,Z){let X=k9($),J=Object.hasOwn(X,Z)?X[Z]:void 0;return O(J)?J:void 0}function j6($,Z,X){Object.defineProperty(sZ($),Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function f9($,Z){let X=$[p];if(!O(X))return;let J=X[V6];if(!O(J)||!Object.hasOwn(J,Z))return;let z=J[Z];return Z0(z)?z:void 0}function g9($,Z){let X=e0($,Z)?.credentialEpoch;return Z0(X)?X:void 0}function D6($,Z){return Math.max(f9($,Z)??0,g9($,Z)??0)+1}function h9($,Z){let X=[...Z];if(X.length===0)return;let J=y9($),z=O(J[V6])?J[V6]:{},G={},Q=(B,Y)=>Object.defineProperty(G,B,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[B,Y]of Object.entries(z))if(Z0(Y))Q(B,Y);for(let B of X)Q(B,Math.max(f9($,B)??0,g9($,B)??1));J[V6]=G}function $1($,Z,X,J){let z=k9($),G=OX(Z),Q=new Set,B=[];for(let Y of l1($)){let H=CX(Y),V=O(Y)&&typeof Y.id==="string"?Y.id:void 0,W=V===void 0?void 0:z[V],j=O(W)&&Object.hasOwn(W,"staged"),D=j?E9(W.staged):void 0;if(H||!O(Y)||V===void 0||Q.has(V)){if(V!==void 0&&!Q.has(V))Q.add(V);if(V!==void 0)B.push({id:V,type:O(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,V),candidate:!1,invalid:"roster",stamp:"none",...D?{staged:D}:{}});continue}Q.add(V);let U=Y.type==="api"?"api":"oauth",N=Object.hasOwn(z,V),K=N?PX(z[V],X):void 0,M=TX(Y,G[V]),P=Y.enabled!==!1,E=K?K.credentialEpoch:N?void 0:1,F=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,q={id:V,type:U,enabled:P,needsFirstReading:K?K.needsFirstReading:U==="oauth",hasEntry:N,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},...F!==void 0?{identity:F}:{},...M?{credential:M,fingerprint:t0(M)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...D?{staged:D}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...AX(G[V],M,E,F,J),stamp:_X(M,E,F,G[V])};if(N&&!K)q.invalid="entry";else q.candidate=P&&M!==void 0&&!j;B.push(q)}return B}function AX($,Z,X,J,z){if(!O($)||!Object.hasOwn($,Y0))return{};let G=K$($,Z,X,J);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=$[Y0];if(!z?.validate(Q))return{providerStateDropped:"invalid"};if(u1(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function l($){return $.identity??$.id}function q$($,Z){if($===void 0||$>Z+lZ)return Z;return Math.max(Z,$+1)}function iZ($,Z){return q$($,Z)>Z+lZ}function d1($){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 v9($,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 m9($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function w9($,Z={}){if(!O($))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)&&!dZ($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var K6="transition",p9="transitionMark";function SX($){if(!O($))return;let Z=$[K6];if(!O(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 N$($,Z,X){if(X.enabled)V$($,Z);else a0($,Z,X.reason??"");if(!$.rosterRow(Z))return;let J=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...J,[p9]:X.mark}),!X.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)w1($,z.identity)}function RX($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function EX($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function IX($,Z,X,J={}){let z=O(Z.accounts)?Z.accounts:{},G=new Map;for(let Q of $1($,Z,X)){if(Q.invalid||Q.staged||!Q.credential)continue;let B=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!O(B))continue;let Y=V0(B[m]);if(!Y?.binding)continue;if(Y.digest!==x0(Q.credential))continue;let H=Q.credentialEpoch??1;if(Y.credentialEpoch>H){if(!EX(Y))continue;if(J.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==w0(RX(Q.credential,Y.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===H&&Y.dispatch!==void 0&&Y.dispatch===w0(Q.credential)&&Y.binding.identity!==void 0&&Q.identity===void 0)G.set(Q.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===H&&Y.binding.identity===Q.identity){if(J.requireCredentialStamps&&Y.dispatch!==w0(Q.credential))continue;let V=SX(B[m]);if(V&&e0($,Q.id)?.[p9]!==V.mark)G.set(Q.id,{kind:"transition",transition:V})}}return G}function aZ($,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(m1))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 nZ($,Z,X,J={}){let z=IX($,Z,X,J);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),Q={rows:()=>$1(G,Z,X),rosterRow:(B)=>U6(G,B),entry:(B)=>e0(G,B),setEntry:(B,Y)=>j6(G,B,Y)};for(let[B,Y]of z)if(Y.kind==="replace")aZ(Q,B,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[B,Y]of z)if(Y.kind==="identity")N1(Q,B,Y.identity);else if(Y.kind==="transition")N$(Q,B,Y.transition);else if(Y.stamp.binding.identity!==void 0)w1(Q,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function rZ($,Z,X,J={}){let{config:z,torn:G}=nZ($,Z,X,J),Q=$1(z,Z,X,J.providerState);for(let B of Q){if(G.includes(B.id))B.torn=!0,B.candidate=!1;if(J.requireCredentialStamps&&B.stamp!=="bound")B.unbound=!0,B.candidate=!1}return Q}async function oZ($){try{return await M0($,I)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function u9($){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 oZ($.configPath),J=await oZ($.statePath),z=await oZ($.configPath);if(X!==z){if(Z<2)await bX(2+Math.floor(Math.random()*4));continue}let G=b9(u9(X));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=x9(u9(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:rZ(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 T0($,Z,X,J="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:J,kind:"snapshot-contended",retryable:!0,message:$.reason});return new g({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 l9{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 rZ(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($)?.[m];return O(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){F1(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),U6(this.config,$)}dropRosterRows($){let Z=this.roster(),X=Z.filter((J)=>!(O(J)&&J.id===$));return this.config.accounts=X,Z.length-X.length}entries(){return sZ(this.config)}entry($){return this.entries(),e0(this.config,$)}setEntry($,Z){j6(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=nZ(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=O(this.state.accounts)?this.state.accounts:{},X=Object.hasOwn(Z,$)?Z[$]:void 0;return O(X)?X:void 0}dropStateAccount($){if(O(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!O(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 Y of Z)if(O(Y)&&typeof Y.id==="string")X.add(Y.id);let J=new Set;for(let Y of l1(this.snapshot.config))if(O(Y)&&typeof Y.id==="string"&&!X.has(Y.id))J.add(Y.id);for(let Y of Object.keys(this.entries()))if(!X.has(Y))J.add(Y);h9(this.config,J);let z=this.entries(),G={};for(let[Y,H]of Object.entries(z))if(X.has(Y))Object.defineProperty(G,Y,{value:H,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[p],B={...this.config,version:D$,accounts:Z,[p]:{...Q,schemaVersion:o0,[P0]:G}};await this.write(this.ctx.configPath,B,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let Y of J)this.ctx.removedIds.add(Y);this.config=B}),this.config=B}async commitState($,Z={}){let X={...this.state,version:D$,accounts:O(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 hZ(this.ctx.statePath)}catch($){throw new g({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 hZ(this.ctx.configPath)}async write($,Z,X,J=!0,z=!1,G){await gZ($,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 d9($,Z){let X=new r0($.lockDefaults,$.lockEnv),J={writes:0};try{for(let B of $.storeLocks)await X.acquire(B);let z=await H0($);if(z.status==="error")throw T0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[B,Y]of Object.entries(z.config))if(!Z.includes(B))G[B]=Y;G.version=D$,G[p]={schemaVersion:o0,[P0]:{}};let Q={operation:"initialize",rowId:void 0};return await F0($.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 c1(z,"initialize",void 0,J)}finally{await X.releaseAll()}}async function r($,Z,X,J,z,G={}){let Q=Z.held.length;try{for(let H of $.storeLocks)await Z.acquire(H);let B=await H0($);if(B.status!=="ready")throw T0(B,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let Y=new l9($,B,Z,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))Y.assertNotStaged(J.rowId);if(G.completeTorn??!0)await Y.completeTorn();return await z(Y)}finally{await Z.releaseTo(Q)}}function c1($,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 g({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 U$)return new g({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 g){if($.phase===z&&$.rowId===X&&$.operation===Z&&$.committed===G)return $;return new g({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 n0)return new g({...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 M1)return new g({...Q,retryable:!0,kind:"lock-contention",message:$.message});return new g({...Q,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function G0($,Z,X,J,z){let G=new r0($.lockDefaults,$.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(B){let Y=c1(B,Z,X,Q);if(Y.kind!=="after-persist-hook")await R9(Z,J,X,Y,$.logger);throw Y}finally{await G.releaseAll()}}function q0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(l(Z))}`,path:$.ctx.statePath}}async function p0($,Z,X){let J=await H0($.ctx);if(J.status!=="ready")throw T0(J,Z,X);let z=J.rows.find((H)=>H.id===X),G=e0(J.config,X),Q=J.state.accounts,B=O(Q)&&Object.hasOwn(Q,X)?Q[X]:void 0,Y=O(B)?B[m]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))F1(Z,X,G.staged);if(!z&&O(Y)&&Object.hasOwn(Y,"staged"))F1(Z,X,Y.staged);if(!z)throw A0(Z,X);return{result:J,row:z}}function A0($,Z){return new g({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function W0($,Z){if(Z.unbound)throw _($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function _($,Z,X,J,z=!1){return new g({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:X,message:J})}async function q6($,Z,X,J){let{ctx:z}=$,G=new r0(z.lockDefaults,z.lockEnv),Q={writes:0};try{if(!Z0(X?.credentialEpoch))throw _("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await r(z,G,Q,{operation:"pull",rowId:Z},async(B)=>{B.assertNotStaged(Z);let Y=B.row(Z);if(!Y)throw A0("pull",Z);if(Y.invalid)throw _("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!Y.credential)throw _("pull",Z,"no-credential",`row ${Z} holds no credential`);W0("pull",Y);let H=B.entry(Z);if(Y.torn||!H||H.credentialEpoch!==X.credentialEpoch||Y.identity!==X.identity)throw new g({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 V=z.codec.merge(H.quota,J);if(!z.codec.validate(V))throw _("pull",Z,"invalid-quota","the quota codec rejected the merged map");B.setEntry(Z,{...H,quota:V,needsFirstReading:!1}),await B.commitConfig()},{completeTorn:!1})}catch(B){throw c1(B,"pull",Z,Q)}finally{await G.releaseAll()}}function u0($,Z,X,J,z="the provider state"){if(!$)throw _(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 _(Z,X,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!$.validate(G))throw _(Z,X,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function M$($,Z,X,J,z){if(J===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:u0($,Z,X,$.merge(structuredClone(J),structuredClone(z)),"the merged provider state")}}function c9($,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:u0($,"replace",Z.id,Q,"the provider state onReplace returned")}}function s9($,Z,X,J,z){if(Z.kind==="set")return u1($,Z.value);if(Z.kind==="clear")return;return K$(X,J?.credential,z,J?.identity)}async function i9($,Z,X,J,z={}){z0("updateProviderState");let{ctx:G}=$,Q="updateProviderState";return G0(G,Q,Z,z.onFailure,async(B,Y)=>{let H=G.providerState;if(!H)throw _(Q,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw _(Q,Z,"invalid-input","a mutator is required");let V=O(X)?X.credentialEpoch:void 0;if(!Z0(V))throw _(Q,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:W}=await p0($,Q,Z);await B.acquire(q0($,W));for(let j of z.extraLocks??[])await B.acquire(j);return r(G,B,Y,{operation:Q,rowId:Z},async(j)=>{let D=j.row(Z);if(!D)throw A0(Q,Z);if(l(D)!==l(W))throw _(Q,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(D.invalid)throw _(Q,Z,"invalid-row",`row ${Z} failed validation`);if(!D.credential)throw _(Q,Z,"no-credential",`row ${Z} holds no credential`);if(W0(Q,D),(D.credentialEpoch??1)!==V||D.identity!==X.identity)throw _(Q,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let N=await tZ(j,H,Q,D,J);if(N.kind!=="changed")return{id:Z,outcome:"unchanged",...N.kind==="unchanged"&&N.value!==void 0?{providerState:N.value}:{}};return j.setStateAccount(Z,N.account),await j.commitState(),N.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:N.value}})})}var a9=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function tZ($,Z,X,J,z,G=!1){let{id:Q,credential:B}=J;if(!B)throw _(X,Q,"no-credential",`row ${Q} holds no credential`);let Y=J.credentialEpoch??1,H=$.stateAccount(Q),V=H?.[m],W=V0(V);if(!O(V)||!W?.binding||W.digest!==x0(B)||W.credentialEpoch!==Y||W.binding.identity!==J.identity)throw _(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),D=await b0(X,()=>z(j,J));if(G&&D===a9)return{kind:"declined"};let U=D===void 0?void 0:u0(Z,X,Q,D,"the provider state the mutator returned"),N=H!==void 0&&Object.hasOwn(H,Y0);if(U===void 0?!N:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let K={...H};if(U===void 0){delete K[Y0];let M={...V};delete M.providerState,K[m]=M}else{K[Y0]=U;let M=u1(Z,U);if(W.providerState!==M)K[m]={...V,providerState:M}}return{kind:"changed",...U!==void 0?{value:U}:{},account:K}}import{randomUUID as n9}from"node:crypto";async function L6($,Z,X){if(!X)return;let J=$.rows().map((G)=>{let{id:Q,type:B,label:Y,enabled:H,disabledReason:V,identity:W,credentialEpoch:j,stamp:D,staged:U,torn:N,invalid:K}=G;return{id:Q,type:B,label:Y,enabled:H,disabledReason:V,identity:W,credentialEpoch:j,stamp:D,staged:U,torn:N,invalid:K}}),z=await b0($.info.operation,()=>X({id:Z,row:J.find((G)=>G.id===Z),rows:J,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw _($.info.operation,Z,"row-protected",z)}var xX=["access","refresh","expires","lastRefreshedAt","apiKey"];function kX($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function yX($,Z,X){if(X.type!=="api")return X;let J=$.rosterRow(Z);if(!O(J)){if(X.baseURL===void 0)throw _($.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"}:kX(J),Q=X.baseURL?.trim()??G.baseURL,B=X.authHeader??G.authHeader;if(Q!==G.baseURL||B!==G.authHeader)throw _($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...X,baseURL:Q,authHeader:B}}function r9($,Z,X,J){let z=$.rosterRow(Z),G=$.row(Z),Q=J??(G?G.identity:O(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 N6($,Z,X,J,z={}){let G=yX(Z,X,J),Q=Z.stateAccount(X),B=z.providerState??{kind:"keep"},Y=Z.row(X)?.credentialEpoch??Z.entry(X)?.credentialEpoch,H=typeof Y==="number"?Y:1,V=s9($.ctx.providerState,B,Q,Q&&Object.hasOwn(Q,Y0)?Z.row(X):void 0,H),W=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??q$(W,$.ctx.now()):void 0,D={...Q??{}};for(let K of xX)delete D[K];if(z.clearErrors)delete D.lastRefreshError,delete D.lastQuotaRefreshError,delete D.quota;if(B.kind==="clear")delete D[Y0];else if(B.kind==="set")D[Y0]=B.value;let U=m9(G,j),N={...D,...v9(G,j),[m]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[K6]:z.transition}:{},...cZ(U,H,z.binding??r9(Z,X,U,z.identity),{replace:z.binding!==void 0,...V!==void 0?{providerState:V}:{}})}};return{stored:U,account:N}}async function M6($,Z,X){return $.setStateAccount(Z,X.account),await $.commitState(X.stored),X.stored}async function _6($,Z,X,J,z={}){return M6(Z,X,N6($,Z,X,J,z))}async function fX($,Z,X){if(!Z.credential||Z.stamp!=="bound")return;let J=$.stateAccount(Z.id),z=K$(J,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...J??{},[m]:cZ(Z.credential,Z.credentialEpoch??1,r9($,Z.id,Z.credential,X),z!==void 0?{providerState:z}:{})}),await $.commitState()}function $3($,Z,X){let J=$==="add"?p1(Z):void 0;if(J)throw _($,Z,"invalid-input",J);let z=w9(X,{baseURLOptional:$==="rotate"});if(z)throw _($,Z,"invalid-input",z)}function O6($,Z,X,J){if(!X)throw A0($,Z);if(X.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if(J&&J.type!==X.type)throw _($,Z,"type-mismatch",`row ${Z} holds a ${X.type} credential`);return X}function i1($,Z,X){if(X!==void 0&&!Z0(O(X)?X.credentialEpoch:void 0))throw _($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function C6($,Z,X,J){if(!X)throw A0($,Z);if(X.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw _($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function F6($,Z){return _($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function F$($,Z){return _($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function gX($,Z,X,J){let{id:z,credential:G,identity:Q}=X;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!s1(Z.state,z))return;let B=()=>{throw _("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=Z.stateAccount(z),H=V0(Y?.[m]);if(!H?.binding||H.dispatch===void 0||H.replace)return B();if(G.type==="api"&&(H.binding.baseURL===void 0||H.binding.authHeader===void 0))return B();let V=G.type==="api"?{...G,baseURL:H.binding.baseURL,authHeader:H.binding.authHeader}:G,[W]=$1({accounts:[d1({id:z,credential:V,identity:H.binding.identity,addedAt:0})],[p]:{rows:{[z]:{credentialEpoch:D6(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!W?.credential||W.invalid||W.stamp!=="bound")return B();if(Q!==void 0&&Q!==W.identity)return B();if(x0(G)!==H.digest)return B();if(G.type==="api"){if(G.baseURL.trim()!==H.binding.baseURL)return B();if((G.authHeader??"authorization-bearer")!==H.binding.authHeader)return B()}else if(w0(G)!==H.dispatch)return B();if(H.providerState!==void 0&&W.providerState===void 0)return B();if(J!==void 0&&u1($.ctx.providerState,J)!==H.providerState)return B();return W}function hX($,Z,X,J){let{id:z,credential:G,identity:Q,label:B}=X,Y=Z.rosterRow(z),H=()=>{throw _("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},V=Z.stateAccount(z),W=V0(V?.[m]),j=W?.staged;if(!W?.binding||!j||W.replace||W.dispatch===void 0)return H();if(Y&&(Y.type!==G.type||Y.label!==B||Y.accountId!==Q))return H();if(j.reservation!==X.stage?.reservation||j.label!==B||j.disabledReason!==X.disabled?.reason||W.binding.identity!==Q)return H();let D=J===void 0?void 0:L1(J),U=V?.[Y0],N=U===void 0?void 0:L1(U);if(j.providerState!==D||j.providerState!==N)return H();if(x0(G)!==W.digest||w0(G)!==W.dispatch)return H();let K=Y?Z.config:{accounts:[{...d1({id:z,credential:G.type==="api"?{...G,baseURL:W.binding.baseURL??"",authHeader:W.binding.authHeader}:G,identity:W.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[p]:{rows:{[z]:{credentialEpoch:W.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},M=$1(K,Z.state,$.ctx.codec,$.ctx.providerState).find((P)=>P.id===z);if(!M?.credential||M.invalid||M.stamp!=="bound"||M.type!==G.type||M.enabled||M.label!==j.label||M.identity!==W.binding.identity||M.disabledReason!==j.disabledReason||M.staged?.reservation!==j.reservation)return H();if(Y)return{id:z,outcome:"exists",credential:M.credential,credentialEpoch:W.credentialEpoch};if(D6(Z.config,z)!==W.credentialEpoch)return H();return Z.roster().push({...d1({id:z,credential:G,identity:Q,label:B,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:W.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:M.credential,credentialEpoch:W.credentialEpoch}))}async function o9($,Z,X={}){z0("add");let{ctx:J}=$,{id:z,credential:G,identity:Q,label:B}=Z,Y=Z.stage!==void 0||Z.disabled!==void 0,H=await G0(J,"add",z,X.onFailure,async(V,W)=>{$3("add",z,G);let j=X.onExisting??"rotate";if(Z.stage!==void 0&&j==="rotate")throw _("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||Z.stage!==void 0&&(B!==void 0&&typeof B!=="string"||Q!==void 0&&(typeof Q!=="string"||!Q))||Z.disabled!==void 0&&(!O(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!O(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||j==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw _("add",z,"invalid-input","staging requires a reservation and a disabled reason");let D=Z.providerState===void 0?void 0:u0(J.providerState,"add",z,Z.providerState);if(await V.acquire(q0($,{id:z,identity:Q})),G.type==="oauth")await V.acquire(X.providerLock??$.providerLock);for(let U of X.extraLocks??[])await V.acquire(U);return r(J,V,W,{operation:"add",rowId:z},async(U)=>{await L6(U,z,X.protect);let N=O(U.state.accounts)?U.state.accounts:{},K=Object.entries(N).find(([y,f])=>{if(y===z||U.rosterRow(y)||!O(f))return!1;let h=f[m];if(!O(h)||!Object.hasOwn(h,"staged"))return!1;return G.type==="oauth"?f.refresh===G.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===G.apiKey.trim()});if(K)throw _("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(J.removedIds.has(z))throw _("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&j!=="rotate"&&(U.rosterRow(z)||s1(U.state,z)))return hX($,U,Z,D);if(j==="rotate"){U.assertNotStaged(z);let y=U.rows().find((f)=>f.fingerprint===t0(G));if(y)U.assertNotStaged(y.id)}if(j==="refuse"){let y=U.rows().find((c)=>c.fingerprint===t0(G)||c.id===z&&c.credential),f=O(U.state.accounts)?U.state.accounts:{},h=Object.entries(f).find(([,c])=>{if(!O(c))return!1;if(G.type==="oauth")return c.refresh===G.refresh;return typeof c.apiKey==="string"&&c.apiKey.trim()===G.apiKey.trim()})?.[0],o=y?.id??h??z;if(y||h!==void 0||s1(U.state,z))throw _("add",o,"credential-exists",`row ${o} already holds this secret or id`)}if(j==="stage-duplicate"&&(U.rosterRow(z)||s1(U.state,z)))throw _("add",z,"id-exists",`row ${z} already exists`);let M=gX($,U,Z,D),P=U.rows(),E=t0(G),F=j==="rotate"&&!M&&P.find((y)=>y.invalid===void 0&&y.fingerprint===E);if(F){if(U.assertNotStaged(F.id),W0("add",F),Q!==void 0&&F.identity!==void 0&&Q!==F.identity)throw F6("add",F.id);let y=N6($,U,F.id,G,{...D!==void 0?{providerState:M$(J.providerState,"add",F.id,F.providerState,D)}:{}});await U.completeTorn(),U.assertNotStaged(F.id);let f=await M6(U,F.id,y);return{id:F.id,outcome:"rotated",credential:f,credentialEpoch:F.credentialEpoch??1}}let q=P.find((y)=>y.id===z);if(q){if(q.invalid)throw _("add",z,"invalid-row",`row ${z} is invalid`);if(q.credential)throw _("add",z,"id-exists",`row ${z} already holds a credential`);if(W0("add",q),q.type!==G.type)throw _("add",z,"type-mismatch",`row ${z} is a ${q.type} row`);if(Q!==void 0&&q.identity!==void 0&&Q!==q.identity)throw F6("add",z);if(!q.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let y=N6($,U,z,G,{clearErrors:!0,...D!==void 0?{providerState:{kind:"set",value:D}}:{}});await U.completeTorn();let f=await M6(U,z,y);if(!q.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:f,credentialEpoch:q.credentialEpoch??1}}let L=D6(U.config,z);if(!Z0(L))throw _("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let S=M?.identity??Q;U.roster().push(d1({id:z,credential:G,...S!==void 0?{identity:S}:{},...B!==void 0?{label:B}:{},addedAt:J.now()})),U.setEntry(z,{credentialEpoch:L,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let A="added";if(Z.disabled)a0(U,z,Z.disabled.reason),A="added-disabled";if(!Z.disabled&&S!==void 0&&G.type==="oauth"){if(P.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===S))a0(U,z,yZ),A="added-disabled"}if(M?.credential)return await U.commitConfig(),{id:z,outcome:A,credential:M.credential,credentialEpoch:M.credentialEpoch??L};U.dropStateAccount(z);let x=N6($,U,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...B!==void 0?{label:B}:{},...D!==void 0?{providerState:L1(D)}:{}}}:{},...D!==void 0?{providerState:{kind:"set",value:D}}:{}});if(j==="rotate")await U.completeTorn();let w=await M6(U,z,x);return await U.commitConfig(),{id:z,outcome:A,credential:w,credentialEpoch:L}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(H.outcome==="added"||H.outcome==="completed"))$.firePull(H.id,"add");return H}async function t9($,Z,X,J={},z={}){z0("replace");let{ctx:G}=$,Q=await G0(G,"replace",Z,z.onFailure,async(B,Y)=>{$3("replace",Z,X),i1("replace",Z,z.attribution);let H=J.providerState===void 0?void 0:u0(G.providerState,"replace",Z,J.providerState),{row:V}=await p0($,"replace",Z);if(await B.acquire(q0($,V)),X.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await B.acquire(W);return r(G,B,Y,{operation:"replace",rowId:Z},async(W)=>{if(z.attribution!==void 0)C6("replace",Z,W.row(Z),z.attribution),await W.completeTorn();let j=O6("replace",Z,W.row(Z),X);if(l(j)!==l(V))throw F$("replace",Z);let D=W.entry(Z)?.credentialEpoch,U=(typeof D==="number"?D:1)+1;if(!Z0(U))throw _("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let N=c9(G.providerState,j,U,J.identity,H),K={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(aZ(W,Z,U,K),J.identity!==void 0)w1(W,J.identity);let M=await _6($,W,Z,X,{clearErrors:!0,binding:K,providerState:N});return await W.commitConfig(),{id:Z,credential:M,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(X.type==="oauth")$.firePull(Z,"replace");return Q}async function e9($,Z,X,J={},z={}){z0("rotate");let{ctx:G}=$;return G0(G,"rotate",Z,z.onFailure,async(Q,B)=>{$3("rotate",Z,X),i1("rotate",Z,z.attribution);let Y=J.providerState===void 0?void 0:u0(G.providerState,"rotate",Z,J.providerState),{row:H}=await p0($,"rotate",Z);if(await Q.acquire(q0($,H)),J.identity!==void 0&&X.type==="oauth")await Q.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await Q.acquire(V);return r(G,Q,B,{operation:"rotate",rowId:Z},async(V)=>{if(z.attribution!==void 0)C6("rotate",Z,V.row(Z),z.attribution),await V.completeTorn();let W=O6("rotate",Z,V.row(Z),X);if(l(W)!==l(H))throw F$("rotate",Z);if(W0("rotate",W),J.identity!==void 0&&W.identity!==void 0&&J.identity!==W.identity)throw F6("rotate",Z);let j=J.identity!==void 0&&W.identity===void 0?J.identity:void 0,D=await _6($,V,Z,X,{identity:j,...Y!==void 0?{providerState:M$(G.providerState,"rotate",Z,W.providerState,Y)}:{}}),U=!1;if(!W.hasEntry)V.setEntry(Z,{credentialEpoch:1,needsFirstReading:W.type==="oauth"}),U=!0;if(J.identity!==void 0&&W.identity!==J.identity)N1(V,Z,J.identity),U=!0;if(U)await V.commitConfig();return{id:Z,credential:D}},{completeTorn:z.attribution===void 0})})}async function $2($,Z,X,J,z){z0(Z);let{ctx:G}=$,Q=G.providerState,B=z.attribution,Y=z.providerState;return G0(G,Z,X,z.onFailure,async(H,V)=>{if(i1(Z,X,B),Y!==void 0){if(typeof Y!=="function")throw _(Z,X,"invalid-input","the provider-state mutator must be a function");if(B===void 0)throw _(Z,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!Q)throw _(Z,X,"invalid-input","the store was opened without a provider-state codec")}let{row:W}=await p0($,Z,X);await H.acquire(q0($,W));for(let j of z.extraLocks??[])await H.acquire(j);return r(G,H,V,{operation:Z,rowId:X},async(j)=>{await L6(j,X,z.protect),j.assertNotStaged(X);let D=j.row(X),U=J.enabled?O6("enable",X,D):D;if(!U||!j.rosterRow(X))throw A0(Z,X);if(l(U)!==l(W))throw F$(Z,X);if(B!==void 0)C6(Z,X,U,B);if(J.enabled&&U.disabledReason?.startsWith(m1))throw _("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let N=!J.enabled||!U.enabled||U.disabledReason!==void 0;if(J.enabled&&N&&U.type==="oauth"){let F=U.identity===void 0?void 0:j.rows().find((q)=>q.id!==X&&q.invalid===void 0&&q.type==="oauth"&&q.enabled&&q.identity===U.identity);if(F)throw _("enable",X,"duplicate-identity",`row ${F.id} is enabled with the same identity as row ${X}`)}if(Y===void 0||Q===void 0){if(await j.completeTorn(),!N)return{id:X};if(J.enabled)V$(j,X);else a0(j,X,J.reason);return await j.commitConfig(),{id:X}}if(!U.credential)throw _(Z,X,"no-credential",`row ${X} holds no credential`);W0(Z,U);let K=await tZ(j,Q,Z,U,Y,!0);if(K.kind==="declined")return{id:X,declined:!0};await j.completeTorn();let M={id:X,providerStateOutcome:K.kind==="unchanged"?"unchanged":K.value===void 0?"cleared":"updated",...K.value!==void 0?{providerState:K.value}:{}};if(K.kind==="unchanged"){if(N){if(J.enabled)V$(j,X);else a0(j,X,J.reason);await j.commitConfig()}return M}if(!N)return j.setStateAccount(X,K.account),await j.commitState(),M;let P=J.enabled?{mark:n9(),enabled:!0}:{mark:n9(),enabled:!1,reason:J.reason},E=K.account[m];return j.setStateAccount(X,{...K.account,[m]:{...E,[K6]:P}}),await j.commitState(),N$(j,X,P),await j.commitConfig(),M},{completeTorn:!1})})}function Z2($,Z,X,J={}){return $2($,"disable",Z,{enabled:!1,reason:X},J)}function X2($,Z,X={}){return $2($,"enable",Z,{enabled:!0},X)}async function J2($,Z,X={}){z0("remove");let{ctx:J}=$;return G0(J,"remove",Z,X.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw _("remove",Z,"invalid-input","id must be non-empty");let Q=X.attribution;if(i1("remove",Z,Q),X.staged!==void 0&&(!O(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw _("remove",Z,"invalid-input","a staged removal needs a reservation");let B=await H0(J);if(B.status!=="ready")throw T0(B,"remove",Z);let Y=B.rows.find((V)=>V.id===Z);if(!Y&&!s1(B.state,Z))throw A0("remove",Z);let H=l(Y??{id:Z});await z.acquire(q0($,Y??{id:Z}));for(let V of X.extraLocks??[])await z.acquire(V);return r(J,z,G,{operation:"remove",rowId:Z},async(V)=>{let W=V.reservation(Z);if(W!==void 0){if(!O(W)||!X.staged||W.reservation!==X.staged.reservation)throw _("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(X.staged)throw _("remove",Z,"attribution",`row ${Z} is no longer reserved`);let j=V.row(Z),D=s1(V.state,Z);if(!j&&!D)throw A0("remove",Z);if(l(j??{id:Z})!==H)throw F$("remove",Z);if(Q!==void 0)if(j)P6(Z,j,Q);else vX($,V,Z,Q);let U=X.protect;if(U){let N={row:j,config:V.snapshot.config,state:V.snapshot.state},K=await b0("remove",()=>U(Z,N));if(K!==void 0)throw _("remove",Z,"row-protected",K)}if(j){if(Q===void 0)await V.completeTorn();V.dropRosterRows(Z),await V.commitConfig()}if(D)V.dropStateAccount(Z),await V.commitState();return{id:Z,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function P6($,Z,X,J="remove"){if(C6(J,$,Z,X),Z.torn)throw _(J,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw _(J,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function vX($,Z,X,J){let z=()=>_("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=V0(G?.[m]);if(!G||!Q?.binding||Q.dispatch===void 0||Q.replace)throw z();let B;if(typeof G.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw z();B={type:"api",apiKey:G.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof G.refresh==="string")B={type:"oauth",refresh:G.refresh};else throw z();let[Y]=$1({accounts:[d1({id:X,credential:B,identity:Q.binding.identity,addedAt:0})],[p]:{rows:{[X]:{credentialEpoch:Q.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(Q.credentialEpoch!==J.credentialEpoch||Q.binding.identity!==J.identity)throw _("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function s1($,Z){let X=$.accounts;return O(X)&&Object.hasOwn(X,Z)}function eZ($){return O($)&&typeof $.id==="string"?$.id:void 0}function mX($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let X=new Set;for(let G of $){let Q=eZ(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 wX($,Z){let X=new Map;for(let G of $){let Q=eZ(G);if(Q===void 0)continue;let B=X.get(Q);if(B)B.push(G);else X.set(Q,[G])}let J=Z.flatMap((G)=>X.get(G)??[]),z=0;return $.map((G)=>eZ(G)===void 0?G:J[z++])}async function z2($,Z,X={}){z0("reorder");let{ctx:J}=$,z=X.onFailure;return G0(J,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of X.extraLocks??[])await G.acquire(B);return r(J,G,Q,{operation:"reorder",rowId:void 0},async(B)=>{let Y=B.roster(),H=mX(Y,Z);if(H)throw new g({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:H});let V=[...Z],W=wX(Y,V);if(W.every((j,D)=>j===Y[D]))return{ids:V,outcome:"unchanged"};return B.config.accounts=W,await B.commitConfig(),{ids:V,outcome:"reordered"}},{completeTorn:!1})})}async function G2($,Z,X,J,z={}){return z0("recordIdentity"),G0($.ctx,"recordIdentity",Z,z.onFailure,async(G,Q)=>{if(typeof X!=="string"||X.length===0)throw _("recordIdentity",Z,"invalid-input","identity must be non-empty");let B=O(J)?J.credentialEpoch:void 0;if(!Z0(B))throw _("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await p0($,"recordIdentity",Z);await G.acquire(q0($,Y)),await G.acquire(z.providerLock??$.providerLock);for(let H of z.extraLocks??[])await G.acquire(H);return r($.ctx,G,Q,{operation:"recordIdentity",rowId:Z},async(H)=>{let V=O6("recordIdentity",Z,H.row(Z));if(l(V)!==l(Y))throw F$("recordIdentity",Z);if(W0("recordIdentity",V),(V.credentialEpoch??1)!==B)throw _("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(V.identity!==void 0&&V.identity!==X)throw F6("recordIdentity",Z);if(V.identity===void 0)await fX(H,V,X);let W=N1(H,Z,X);return await H.commitConfig(),{id:Z,disabled:W}})})}function B2($){let Z=$[p];return O(Z)&&O(Z.publications)?Z.publications:{}}function Y2($,Z){let X=B2($);if(!Object.hasOwn(X,Z))return;let J=X[Z];if(!O(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)=>!O(z)||typeof z.id!=="string"||!Z0(z.credentialEpoch))||J.finalized.some((z)=>!O(z)||typeof z.id!=="string"||!Z0(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw _("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function H2($,Z){let X=await H0($.ctx);if(X.status!=="ready")throw T0(X,"publishRoster",Z);return Y2(X.config,Z)}function pX($,Z){let X=()=>{throw _("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!O(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(!O(z)||typeof z.id!=="string"||p1(z.id)||J.has(z.id)||!z.attribution)X();if(J.add(z.id),i1("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"||p1(z))||new Set(Z.order).size!==Z.order.length)X()}function W2($,Z){$.entries();let X=$.config[p],J={...B2($.config)};Object.defineProperty(J,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function uX($,Z,X){let J=new Set;for(let Q of l1($.config)){if(!O(Q)||typeof Q.id!=="string")continue;if(J.has(Q.id))throw _("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((B)=>B.id===Q))||G.some((Q)=>!Z.order.includes(Q.id)))throw _("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function Q2($,Z){await $.assertAll();for(let J of Z.removed)if(V0($.stateAccount(J.id)?.[m])?.credentialEpoch===J.credentialEpoch&&!$.rosterRow(J.id))$.dropStateAccount(J.id);for(let J of Z.finalized){let z=$.stateAccount(J.id),G=V0(z?.[m]);if(z&&G?.credentialEpoch===J.credentialEpoch&&G.staged?.reservation===J.reservation){let Q={...z[m]};delete Q.staged,$.setStateAccount(J.id,{...z,[m]:Q})}}await $.commitState(void 0,{durable:!0});let X={...Z,phase:"cleaned"};return W2($,X),await $.commitConfig({durable:!0}),X}async function V2($,Z,X={}){return z0("publishRoster"),G0($.ctx,"publishRoster",Z?.operationId??"",X.onFailure,async(J,z)=>{if(!O(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw _("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=L1(Z),Q=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((B)=>O(B)&&typeof B.id==="string");for(let B=0;;B++){let Y=await H0($.ctx);if(Y.status!=="ready")throw T0(Y,"publishRoster",Z.operationId);let H=new Map(Q.map(({id:W})=>[W,l(Y.rows.find((j)=>j.id===W)??{id:W})]));for(let W of[...new Set(H.values())].sort())await J.acquire(q0($,{id:W}));await J.acquire(X.providerLock??$.providerLock);for(let W of X.extraLocks??[])await J.acquire(W);let V=await r($.ctx,J,z,{operation:"publishRoster",rowId:Z.operationId},async(W)=>{let j=W.rows();if(Q.some(({id:q})=>l(j.find((L)=>L.id===q)??{id:q})!==H.get(q)))return;let D=Y2(W.config,Z.operationId);if(D){if(D.planDigest!==G)throw _("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(D.phase==="cleaned")return{outcome:"already-cleaned",receipt:D};return W.markPublicationDecision(),await W.syncConfig(),{outcome:"cleaned",receipt:await Q2(W,D)}}pX($,Z);let U=uX(W,Z,j),N=[];for(let q of Z.remove){W.assertNotStaged(q.id);let L=j.find((S)=>S.id===q.id);if(!L)throw _("publishRoster",q.id,"attribution","the removed row no longer exists");if(P6(q.id,L,q.attribution,"publishRoster"),!L.credential||q.fingerprint!==void 0&&t0(L.credential)!==q.fingerprint)throw _("publishRoster",q.id,"attribution","the removed secret no longer matches");N.push(L)}let K=[];for(let q of Z.finalize){let L=j.find((f)=>f.id===q.id),S=V0(W.stateAccount(q.id)?.[m]);if(!L||L.staged?.reservation!==q.reservation||S?.staged?.reservation!==q.reservation||L.enabled)throw _("publishRoster",q.id,"row-staged","the finalized row is not disabled under this reservation");let A=W.stateAccount(q.id),x=W.rosterRow(q.id),w=A?.[Y0],y=w===void 0?void 0:L1(w);if(!S?.staged||S.staged.label!==x?.label||S.staged.disabledReason!==L.disabledReason||S.staged.providerState!==y)throw _("publishRoster",q.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");P6(q.id,L,q.attribution,"publishRoster"),K.push(L)}let M=U.find((q)=>q.torn);if(M)throw _("publishRoster",Z.operationId,"attribution",`Row ${M.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let P=new Set;for(let q of U){if(!(Z.finalize.find((S)=>S.id===q.id)?.enabled??q.enabled)||q.type!=="oauth"||q.identity===void 0)continue;if(P.has(q.identity))throw _("publishRoster",q.id,"invalid-input","the final enabled roster repeats a known identity");P.add(q.identity)}for(let q of U)if(q.identity!==void 0&&q.fingerprint!==void 0&&U.some((L)=>L.id!==q.id&&L.identity!==void 0&&L.identity!==q.identity&&L.fingerprint===q.fingerprint))throw _("publishRoster",q.id,"attribution","the resulting pool gives the same secret different known identities");for(let q of K)if(q.identity!==void 0&&N.some((L)=>L.identity!==void 0&&L.identity!==q.identity&&L.fingerprint===q.fingerprint))throw _("publishRoster",q.id,"attribution","the staged secret belonged to a different known identity");await L6(W,Z.operationId,X.protect);let E={operationId:Z.operationId,planDigest:G,phase:"committed",removed:N.map((q)=>({id:q.id,credentialEpoch:q.credentialEpoch??1})),finalized:Z.finalize.map((q,L)=>({id:q.id,credentialEpoch:K[L]?.credentialEpoch??1,reservation:q.reservation,enabled:q.enabled}))};for(let q of Z.remove)W.dropRosterRows(q.id);for(let q of Z.finalize){let L=W.rosterRow(q.id);L.enabled=q.enabled;let S={...W.entry(q.id)};if(delete S.staged,q.enabled)delete S.disabledReason;else S.disabledReason=q.disabledReason;W.setEntry(q.id,S)}let F=W.roster().filter((q)=>!O(q)||typeof q.id!=="string"||j.find((L)=>L.id===q.id)?.invalid==="roster");return W.config.accounts=[...Z.order.map((q)=>W.rosterRow(q)),...F],W2(W,E),await W.syncState(),await W.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await Q2(W,E)}},{completeTorn:!1});if(V)return V;if(await J.releaseAll(),B>=1)throw _("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class Z3{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 r0(J.lockDefaults,J.lockEnv),G={writes:0};try{let Q=await r(J,z,G,{operation:"pull",rowId:$},async(Y)=>{if(Y.reservation($)!==void 0)return;await Y.completeTorn();let H=Y.row($);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)W0("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.hasEntry)Y.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await Y.commitConfig();let V=Y.row($);if(!V?.credential||V.credentialEpoch===void 0)return;return{id:$,credential:V.credential,credentialEpoch:V.credentialEpoch,...V.identity!==void 0?{identity:V.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!Q){this.firedAtLoad.delete($);return}await J.hold?.("pull-before-request",$);let B;try{B=await this.hook?.(Q)}catch(Y){throw new g({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Y})}await q6(X,$,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},B)}catch(Q){this.firedAtLoad.delete($);let B=c1(Q,"pull",$,G);if(this.onFailure)try{await this.onFailure($,B)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:$,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:B.kind})}finally{await z.releaseAll()}}}import{randomUUID as lX}from"node:crypto";function X3($,Z){if(F1("refresh",$,Z?.staged),!Z)throw _("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw _("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw _("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw _("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function U2($){return _("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function j2($,Z,X,J={}){z0("refresh");let{ctx:z}=$;return G0(z,"refresh",Z,J.onFailure,async(G,Q)=>{let{row:B}=await p0($,"refresh",Z);X3(Z,B);let Y=await J.refuse?.(B);if(Y!==void 0)return{status:"refused",rowId:Z,reason:Y};let H=l(B),V;for(let U=0;;U++){await G.acquire(q0($,{id:Z,identity:H===Z?void 0:H})),await G.acquire(J.providerLock??$.providerLock);for(let M of J.extraLocks??[])await G.acquire(M);let K=await r(z,G,{writes:0},{operation:"refresh",rowId:Z},async(M)=>{let P=X3(Z,M.row(Z));if(W0("refresh",P),!P.hasEntry)M.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await M.commitConfig(),P=X3(Z,M.row(Z));if(l(P)!==H)return{keyNow:l(P)};let E=await J.refuse?.(P);if(E!==void 0)return{refused:E};return{row:P,credential:P.credential,credentialEpoch:P.credentialEpoch,identity:P.identity}});if("refused"in K)return{status:"refused",rowId:Z,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),U>=1)throw _("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);H=K.keyNow;continue}V=K;break}if(iZ(V.credential.lastRefreshedAt,z.now()))throw U2(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let W;try{W=await X(V.credential,V.row)}catch(U){throw new g({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof W?.refresh!=="string"||!W.refresh.trim())throw _("refresh",Z,"provider","the provider returned no refresh token",!0);let j=W.providerState===void 0?void 0:u0(z.providerState,"refresh",Z,W.providerState,"the provider state the provider returned"),D=await r(z,G,Q,{operation:"refresh",rowId:Z},async(U)=>{let N=U.row(Z),K=U.entry(Z);if(!N||N.invalid||!K||K.credentialEpoch!==V.credentialEpoch||N.identity!==V.identity)throw new g({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`});W0("refresh",N);let M=await J.refuse?.(N);if(M!==void 0)return{refused:M};let P=z.now(),E=N.credential?.type==="oauth"?N.credential.lastRefreshedAt:void 0;if(iZ(E,P))throw U2(Z);let F={type:"oauth",access:W.access,refresh:W.refresh,expires:W.expires},q=N.identity!==void 0&&W.identity!==void 0&&N.identity!==W.identity?{expectedIdentity:N.identity,returnedIdentity:W.identity}:void 0,L=q?{mark:lX(),enabled:!1,reason:`${m1}${JSON.stringify(q)}`}:void 0,S=N.identity===void 0&&W.identity?W.identity:void 0,A=await _6($,U,Z,F,{stamp:q$(E,P),transition:L,identity:S,...j!==void 0?{providerState:M$(z.providerState,"refresh",Z,N.providerState,j)}:{}});if(L!==void 0)N$(U,Z,L),await U.commitConfig();let x=N.identity;if(S!==void 0)N1(U,Z,S),x=S,await U.commitConfig();return{stored:A,identity:x,contradiction:q,refused:void 0}});if(D.refused!==void 0)return{status:"refused",rowId:Z,reason:D.refused};if(D.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...D.contradiction,credential:D.stored};if(J.onPersisted)try{let U=J.onPersisted;await b0("refresh",()=>U(Z,D.stored))}catch(U){throw new g({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:D.stored,message:"the after-persist hook threw; the rotation stays committed",cause:U})}return{status:"rotated",rowId:Z,credential:D.stored,...D.identity!==void 0?{identity:D.identity}:{}}})}import{isDeepStrictEqual as dX}from"node:util";var A6=Object.freeze(["version","accounts",p]);function J3($){let Z={};for(let[X,J]of Object.entries($))if(!A6.includes(X))T6(Z,X,J);return Z}function T6($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function cX($,Z){let X={};for(let[J,z]of Object.entries($))if(A6.includes(J))T6(X,J,z);else if(Object.hasOwn(Z,J))T6(X,J,Z[J]);for(let[J,z]of Object.entries(Z))if(!Object.hasOwn($,J))T6(X,J,z);return X}function D2($){return new g({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}async function K2($){let Z=await H0($.ctx);if(Z.status==="error")return Z;return{status:Z.status,settings:J3(Z.config)}}async function q2($,Z,X={}){z0("updateSettings");let{ctx:J}=$,z=X.onFailure;return G0(J,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let Y of X.extraLocks??[])await G.acquire(Y);let B=G.held.length;try{for(let K of J.storeLocks)await G.acquire(K);let Y=await H0(J);if(Y.status!=="ready")throw T0(Y,"updateSettings",void 0);let H=J3(Y.config),V=structuredClone(H),W=await b0("updateSettings",()=>Z(V)),j=W===void 0?V:W;if(!O(j))throw D2("the settings mutator must produce an object");let D=A6.filter((K)=>Object.hasOwn(j,K));if(D.length>0)throw D2(`settings cannot set the pool-owned key(s) ${D.join(", ")}`);if(dX(j,H))return{settings:H,outcome:"unchanged"};let U=cX(Y.config,j),N={operation:"updateSettings",rowId:void 0};return await F0(J.configPath,U,{beforeRename:async()=>{await J.onStep?.("before-config-write",N),await G.assertAll()}}),Q.writes++,await J.onStep?.("after-config-write",N),{settings:J3(U),outcome:"updated"}}finally{await G.releaseTo(B)}})}var N2=new Map;function sX($){let Z=N2.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},N2.set($,Z);return Z}function M2($){if($.status==="ready")return{status:"ready",schemaVersion:o0,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function z3($){let Z=sX($.configPath),X={...uZ,...$.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:{...$.onLockEvent?{onLockEvent:$.onLockEvent}:{},...$.onLockStep?{onLockStep:$.onLockStep}:{},...$.onRenewalTimer?{onRenewalTimer:$.onRenewalTimer}:{}},removedIds:Z.removedIds,requireCredentialStamps:$.requireCredentialStamps===!0,requireRemovedFingerprint:$.requireRemovedFingerprint===!0,...$.logger?{logger:$.logger}:{},...$.onStep?{onStep:$.onStep}:{},...$.hold?{hold:$.hold}:{}},z=new Z3(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:J,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(Q,B)=>z.fire(Q,B)};return{async load(){let Q=await H0(J);if(Q.status==="ready"){for(let B of Q.rows)if((B.candidate||B.torn&&B.enabled)&&B.type==="oauth"&&B.needsFirstReading)z.fire(B.id,"load")}return M2(Q)},async read(){return M2(await H0(J))},async initialize(Q={}){return{status:await d9(J,Q.dropKeys??[])}},add:(Q,B)=>o9(G,Q,B),publishRoster:(Q,B)=>V2(G,Q,B),publication:(Q)=>H2(G,Q),replace:(Q,B,Y,H)=>t9(G,Q,B,Y,H),rotate:(Q,B,Y,H)=>e9(G,Q,B,Y,H),updateProviderState:(Q,B,Y,H)=>i9(G,Q,B,Y,H),disable:(Q,B,Y)=>Z2(G,Q,B,Y),enable:(Q,B)=>X2(G,Q,B),remove:(Q,B)=>J2(G,Q,B),reorder:(Q,B)=>z2(G,Q,B),readSettings:()=>K2(G),updateSettings:(Q,B)=>q2(G,Q,B),recordIdentity:(Q,B,Y,H)=>G2(G,Q,B,Y,H),refresh:(Q,B,Y)=>j2(G,Q,B,Y),recordQuota:(Q,B,Y)=>q6(G,Q,B,Y),requestReading:(Q)=>z.fire(Q,"admission"),pullsSettled:()=>z.settled()}}var iX=[/\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 B3($={}){let{redactStrings:Z}=I0({...$,extraValuePatterns:[...iX,...$.extraValuePatterns??[]]});return(X)=>Z(X)}class Q0 extends Error{code;constructor($,Z,X){super(Z,X);this.name="CommandError",this.code=$}}var F2=/^[a-z][a-z0-9-]{0,63}$/,G3={code:"action-failed",text:"That action failed."},aX=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 L$($){if($ instanceof Q0)return{code:F2.test($.code)?$.code:G3.code,text:$.message};if($ instanceof g)return{code:`pool-${$.kind}`,text:aX.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return G3}var L2="This cannot be undone. Continue?",nX=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function rX($){let Z=$.toLowerCase().replace(/[-_]/g,"");return nX.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function oX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Q3($,Z,X){if(typeof $==="string"){let z=X.redact($);if(z!==$)X.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>Q3(z,`${Z}[${G}]`,X));if(!oX($))return $;let J={};for(let[z,G]of Object.entries($)){if(rX(z)){X.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(J,z,{value:Q3(G,`${Z}.${z}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function _2($,Z,X){let J={redact:X.redact,dropped:[],redacted:[]},z=Q3($,"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 tX($){return{value:String($.value),label:String($.label)}}function eX($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(tX),...$.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 Y3($){if($.irreversible===!0)return{message:$.confirm||L2,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function O2($){let Z=Y3($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(eX),...Z?{confirm:Z}:{}}}function $J($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function ZJ($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:$J($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(O2)}}function XJ($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(ZJ),actions:(Z.actions??[]).map(O2),...Z.facts!==void 0?{facts:Z.facts}:{}}}function C2($,Z,X){return{command:$,title:Z,sections:X.map(XJ)}}function P2($,Z,X,J){return _2({command:$,menu:C2($,Z,X)},$,J)}function T2($,Z,X,J,z){return _2({command:$,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:F2.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:C2($,Z,X)},$,z)}var R2="disabled from the command menu";function JJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function l0($){return JJ($)?{...$}:{}}function zJ($){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 GJ($,Z){return $.label??Z??$.id}function S6($,Z){return B0($.quota)?s($.quota,Z):void 0}function E2($,Z){return`${$} ${Z}${$===1?"":"s"}`}var _$="Actions";function QJ($){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 A2($,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 S2($){return L$($).text}async function BJ($){let Z=await $.read(),X=await $.readSettings();return{load:Z,rows:zJ(Z),settings:X.status==="error"?{}:X.settings}}function R6($,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:GJ($,X)}}function YJ($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=Z.rows.map((W)=>W.id),Q=QJ(Z.load),B=Z.rows.filter((W)=>W.enabled).length,Y=Z.rows.map((W,j)=>{let{account:D,name:U}=R6(W,$),N=[W.type==="api"?"API key":"OAuth",...D.identity!==void 0?[D.identity]:[],...!W.invalid&&!W.enabled&&W.disabledReason?[`disabled: ${W.disabledReason}`]:[]].join(" · "),K=W.invalid?"invalid":W.enabled?"enabled":"disabled",M=[];if(!W.invalid&&W.enabled)M.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(W.id,R2,z),`Disabled ${U}.`}});if(!W.invalid&&!W.enabled)M.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(W.id,z),`Enabled ${U}.`}});if(G.length>1)M.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((P,E)=>({value:String(E+1),label:String(E+1)})),value:String(j+1)}],run:async({values:P})=>{let E=Number(P.position),F=G.filter((L)=>L!==W.id);return F.splice(E-1,0,W.id),(await X.reorder(F,z)).outcome==="unchanged"?`${U} is already at position ${E}.`:`Moved ${U} to position ${E}.`}});return M.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await X.remove(W.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${U}.`}}),{id:W.id,label:U,detail:N,group:"Accounts",status:K,account:D,actions:M}}),H=$.accounts?.login,V=[];if(H&&!Q)V.push({id:"add",label:H.label??"Add account",group:_$,knobs:H.knobs??[],run:async({values:W,invocation:j})=>{let D=await H.run(W,j);if(D.status==="cancelled")return{ok:!1,text:D.message??"Login cancelled."};if(D.status==="ready"){let U=await X.add(D.account,z);return A2(D.account.label??U.id,U)}return D.completion.then(async(U)=>{if(!U){j.notify("Login cancelled.","warning");return}let N=await X.add(U,z);j.notify(A2(U.label??N.id,N))},(U)=>{j.notify(`Adding the account failed: ${S2(U)}`,"error")}).catch((U)=>{j.notify(`Adding the account failed: ${S2(U)}`,"error")}),D.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[Z.rows.length===0?"No accounts yet":`${E2(Z.rows.length,"account")}, ${B} enabled`],items:Q?[]:Y,actions:V}}}function HJ($,Z){let X=$.quota?.scope??"all",J=$.now(),z=X==="all"?"Accounts":`Accounts · ${X}`,G=async(V,W)=>{if($.quota?.check)await $.quota.check(V,W);else{for(let j of V)$.store.requestReading(j);await $.store.pullsSettled()}},Q=Z.rows.filter((V)=>V.candidate),B=Q.map((V)=>{let{account:W,name:j}=R6(V,$),D=S6(V,X);return{id:V.id,label:j,group:z,status:C0(D,{now:J,form:"compact"}),detail:C0(D,{now:J,form:"full"}),account:W,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([V.id],U),`Checked quota for ${j}.`}}]}}),Y=Z.rows.filter((V)=>!V.candidate).map((V)=>{let{name:W}=R6(V,$),j=V.invalid?"invalid":!V.enabled?"disabled":V.credential===void 0?"no credential":"unavailable",D=C0(S6(V,X),{now:J,form:"compact"});return`${W} (${j}): ${D}`}),H=[];if(Q.length>0)H.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:_$,run:async({invocation:V})=>{let W=Q.map((j)=>j.id);return await G(W,V),`Checked quota for ${E2(W.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Y,items:B,actions:H}}}function WJ($,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=l0(Z.settings.routing).mode,B=typeof Q==="string"&&G.some((U)=>U.value===Q)?Q:"ordered",Y=LZ(B),H=Z.rows.map((U)=>U.id),V=f1(H,Y.placement,$.routing?.formerMainId??z6),j=[`Mode: ${G.find((U)=>U.value===B)?.label??B}`];if(H.length>0)j.push(`Roster order: ${H.join(", ")}`);if(Y.mode==="ordered"&&V.join()!==H.join())j.push(`Tried in order: ${V.join(", ")}`);let D=[{id:"mode",label:"Change mode",group:_$,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:B}],run:async({values:U})=>{let N=String(U.mode);return await X.updateSettings((K)=>{K.routing={...l0(K.routing),mode:N};return},z),`Routing mode set to ${G.find((K)=>K.value===N)?.label??N}.`}}];if(H.length>1)D.push({id:"order",label:"Set order",group:_$,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:H.join(", "),required:!0}],run:async({values:U})=>{let N=String(U.order).split(/[\s,]+/).filter((M)=>M.length>0),K=await X.reorder(N,z);return K.outcome==="unchanged"?"The order is unchanged.":`Order set to ${K.ids.join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:D}}}function VJ($,Z){if($.limits?.labels)return[...$.limits.labels];let X=$.quota?.scope??"all",J=[];for(let z of Z.rows)for(let G of S6(z,X)?.limits??[])if(!J.includes(G.label))J.push(G.label);return J.length>0?J:["primary"]}function UJ($,Z){let X=$.quota?.scope??"all",J=new Map;for(let z of Z.rows)for(let G of S6(z,X)?.limits??[])if(G.windowMinutes!==void 0&&!J.has(G.label))J.set(G.label,X6(G));return(z)=>J.get(z)??z}function jJ($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=l0(Z.settings.killswitch),Q=G.enabled===!0,B=l0(G.accounts),Y=VJ($,Z),H=UJ($,Z),V=Q?"on":"off",W=Z.rows.map((j)=>{let{account:D,name:U}=R6(j,$),N=l0(B[j.id]),K=Y.filter((M)=>typeof N[M]==="number");return{id:j.id,label:U,group:`Floors · killswitch ${V}`,status:K.length===0?"no floors":K.map((M)=>`${H(M)} ≥${N[M]}%`).join(" · "),account:D,actions:[{id:"floors",label:"Set floors",knobs:Y.map((M)=>({kind:"number",id:M,label:`Minimum % left for ${H(M)}`,min:0,max:100,...typeof N[M]==="number"?{value:N[M]}:{}})),run:async({values:M})=>{return await X.updateSettings((P)=>{let E=l0(P.killswitch),F=l0(E.accounts),q=l0(F[j.id]);for(let L of Y){let S=M[L];if(typeof S==="number")q[L]=S;else if(S===null)delete q[L]}if(Object.keys(q).length>0)F[j.id]=q;else delete F[j.id];if(Object.keys(F).length>0)E.accounts=F;else delete E.accounts;P.killswitch=E;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${V}`],items:W,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:_$,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!Q}],run:async({values:j})=>{let D=j.enabled===!0;return await X.updateSettings((U)=>{U.killswitch={...l0(U.killswitch),enabled:D};return},z),`Killswitch ${D?"on":"off"}.`}}]}}}async function I2($){let Z=await BJ($.store);return[YJ($,Z),HJ($,Z),WJ($,Z),jJ($,Z)]}var DJ=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),H3=["accounts","quota","routing","limits"];function b2($,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 KJ($,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 qJ($,Z){let X={};for(let J of $){let z=Z&&Object.hasOwn(Z,J.id)?Z[J.id]:void 0,G=KJ(J,z);if("problem"in G)return G;X[J.id]=G.value}return{values:X}}function NJ($,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 _1($){let Z=$.logger??n("commands"),X=B3($.redaction),J={logger:Z,redact:X},z=$.now??Date.now,G=$.extras??[],Q=$.replace??{},B=H3.filter((j)=>!Q[j]);for(let j of H3)if(Q[j]&&$[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let Y=$.store;if(B.length>0&&!Y)throw Error(`a store is required for the built-in ${B.join(", ")} section${B.length>1?"s":""}`);let H=new Set;for(let j of G){if(DJ.has(j.id)||H.has(j.id))throw Error(`extra section id ${j.id} is taken`);H.add(j.id)}async function V(j,D,U,N){try{return{id:j,slot:D,title:U.title,content:await U.build(N)}}catch(K){return Z.warn("command menu section failed to build",{command:$.command,section:j,error:X(K instanceof Error?K.message:String(K))}),{id:j,slot:D,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function W(j){let D=Y&&B.length>0?await I2({store:Y,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],U=[];for(let N of H3){let K=Q[N];if(K)U.push(await V(N,N,K,j));else{let M=D.find((P)=>P.slot===N);if(M)U.push(M)}}if($.cache)U.push(await V("cache","cache",$.cache,j));if($.diagnostics)U.push(await V("diagnostics","diagnostics",$.diagnostics,j));for(let N of G)U.push(await V(N.id,"extra",N,j));return U}return{command:$.command,async open(j){let D=b2(j,X);return P2($.command,$.title,await W(D),J)},async apply(j,D){let U=b2(D,X),N=async(F)=>T2($.command,$.title,await W(U),F,J),K=j.command===$.command?NJ(await W(U),j):void 0;if(!K)return N({ok:!1,code:"unavailable",text:"That action is no longer available."});let M=Y3(K);if(M&&j.confirmed!==!0)return N({ok:!1,code:"needs-confirmation",text:M.message,needsConfirmation:!0});let P=qJ(K.knobs??[],j.values);if("problem"in P)return N({ok:!1,code:"invalid-input",text:P.problem});let E;try{let F=await K.run({values:P.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:U});E=typeof F==="string"?{ok:!0,text:F}:{ok:F.ok,text:F.text,...F.ok?{}:{code:F.code??"refused"}}}catch(F){let q=L$(F);Z.warn("command menu action failed",{command:$.command,section:j.sectionId,action:j.actionId,code:q.code,error:X(F instanceof Error?F.message:String(F))}),E={ok:!1,...q}}return N(E)}}}async function O$($,Z,X){let J=new Map,z=[];for(let Q of X){let B=Q.label;for(let Y=2;J.has(B);Y++)B=`${Q.label} (${Y})`;J.set(B,Q.value),z.push(B)}let G=await $.select(Z,z);return G===void 0?void 0:J.get(G)}function x2($,Z){return Z.length>0?`${$}
9
9
  ${Z.join(`
10
- `)}`:$}function E6($){return $.status?`${$.label} · ${$.status}`:$.label}function VJ($){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?` ${E6(J)}`:E6(J))}return Z}function UJ($){let Z=$.detail?[$.detail]:[];for(let[X,J]of Object.entries($.facts??{}))Z.push(`${X}: ${String(J)}`);return S4(E6($),Z)}async function jJ($,Z){switch(Z.kind){case"choice":{let X=await O$($,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 O$($,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 G=J.trim();if(G==="")return Z.required&&Z.value!==void 0?{value:Z.value}:{value:null};let z=Number(G);if(!Number.isFinite(z)){$.notify(`${Z.label} needs a number.`,"error");return}return{value:z}}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 DJ($,Z){let X={};for(let J of Z.knobs){let G=await jJ($,J);if(!G)return;X[J.id]=G.value}return X}async function H3($,Z,X={}){let J={...X.sessionId!==void 0?{sessionId:X.sessionId}:{},notify:(z,B)=>Z.notify(z,B)},G=(await $.open(J)).menu;for(;;){let z=await O$(Z,G.title,G.sections.map((B)=>({label:B.lines[0]?`${B.title}: ${B.lines[0]}`:B.title,value:B.id})));if(z===void 0)return;for(;;){let B=G.sections.find((U)=>U.id===z);if(!B)break;let Q=[...B.items.filter((U)=>U.actions.length>0).map((U)=>({label:E6(U),value:{kind:"item",item:U}})),...B.actions.map((U)=>({label:U.label,value:{kind:"action",action:U}}))],Y=VJ(B);if(Q.length===0&&Y.length===0){Z.notify("Nothing to do here.");break}let H=await O$(Z,S4(B.title,Y),[...Q,{label:"Back",value:{kind:"back"}}]);if(!H||H.kind==="back")break;let W,V;if(H.kind==="item"){if(V=H.item,W=await O$(Z,UJ(V),V.actions.map((U)=>({label:U.label,value:U}))),!W)continue}else W=H.action;let j=await DJ(Z,W);if(!j)continue;if(W.confirm){if(!await Z.confirm(W.label,W.confirm.message)){Z.notify("Cancelled.");continue}}let D=await $.apply({command:G.command,sectionId:B.id,...V?{itemId:V.id}:{},actionId:W.id,values:j,...W.confirm?{confirmed:!0}:{},...X.sessionId!==void 0?{sessionId:X.sessionId}:{}},J);Z.notify(D.text,D.ok?"info":"error"),G=D.menu}}}import{createHash as kG,randomUUID as yG}from"node:crypto";import{setTimeout as fG}from"node:timers/promises";var KJ=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 qJ}from"node:crypto";var NJ=86400000,MJ=300000,FJ=3600000,LJ=60000,_J=900000,OJ=300000;function W3($){return $ instanceof Error?$.message:String($)}function V3($){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 U3($){let Z=W3($),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 a1($){return qJ("sha256").update($).digest("hex")}function I6($){let Z=a1($.refreshToken),J=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,G,z=$.error?.retryAfter;if(typeof z==="number"&&z>0)G=z*1000;else if(V3($.error))G=Math.min(FJ,MJ*2**Math.min(J-1,6));else G=NJ;return{message:W3($.error),checkedAt:$.now,nextRetryAt:$.now+G,retryCount:J,tokenHash:Z}}function Z1($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===a1(Z)}function C$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function P$($){let X=($.previous?.retryCount??0)+1,J,G=$.error?.retryAfter;if(typeof G==="number"&&G>0)J=G*1000;else if(U3($.error))J=Math.min(_J,LJ*2**Math.min(X-1,6));else J=OJ;return{message:W3($.error),checkedAt:$.now,nextRetryAt:$.now+J,retryCount:X}}function n1($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function j3($){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 CJ($){return $==="chatgptaccountid"||$==="email"||$==="orgname"||$==="organizationname"}var R4=I0({extraSecretKeys:CJ}),cW=R4.redact,E4=R4.redactStrings;import{createServer as I4}from"node:http";import{setTimeout as PJ}from"node:timers/promises";var k6="app_EMoamEEZ73f0CkXaXp7hrann",P1="https://auth.openai.com",A$=1455,TJ=3000,AJ="cortexkit-opencode-openai-auth";function x4($){return`${AJ}/${$}`}var k4="main",SJ=`"${k4}" is a reserved account id; choose a different label.`;function y4($){let Z=new Uint8Array($),X=String.fromCharCode(...Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function RJ(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[J%66]).join(""),X=y4(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function r1($){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 o1($){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 G=J[0];if(G&&typeof G==="object"&&!Array.isArray(G)&&typeof G.id==="string"&&G.id.length>0)return G.id}return}function S$($){if($.id_token){let Z=r1($.id_token),X=Z&&o1(Z);if(X)return X}if($.access_token){let Z=r1($.access_token);return Z?o1(Z):void 0}return}function EJ($){return typeof $==="string"&&$.toLowerCase()===k4}function D3($){if(EJ($))throw Error(SJ);return $}function IJ($,Z,X){let J=new URLSearchParams({response_type:"code",client_id:k6,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`${P1}/oauth/authorize?${J.toString()}`}async function bJ($,Z,X){let J=await fetch(`${P1}/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:k6,code_verifier:X.verifier}).toString()});if(!J.ok)throw Error(`Token exchange failed: ${J.status}`);return await J.json()}function xJ($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var kJ=`<!doctype html>
10
+ `)}`:$}function E6($){return $.status?`${$.label} · ${$.status}`:$.label}function MJ($){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?` ${E6(J)}`:E6(J))}return Z}function FJ($){let Z=$.detail?[$.detail]:[];for(let[X,J]of Object.entries($.facts??{}))Z.push(`${X}: ${String(J)}`);return x2(E6($),Z)}async function LJ($,Z){switch(Z.kind){case"choice":{let X=await O$($,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 O$($,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 _J($,Z){let X={};for(let J of Z.knobs){let z=await LJ($,J);if(!z)return;X[J.id]=z.value}return X}async function W3($,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 O$(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 B=[...Q.items.filter((U)=>U.actions.length>0).map((U)=>({label:E6(U),value:{kind:"item",item:U}})),...Q.actions.map((U)=>({label:U.label,value:{kind:"action",action:U}}))],Y=MJ(Q);if(B.length===0&&Y.length===0){Z.notify("Nothing to do here.");break}let H=await O$(Z,x2(Q.title,Y),[...B,{label:"Back",value:{kind:"back"}}]);if(!H||H.kind==="back")break;let V,W;if(H.kind==="item"){if(W=H.item,V=await O$(Z,FJ(W),W.actions.map((U)=>({label:U.label,value:U}))),!V)continue}else V=H.action;let j=await _J(Z,V);if(!j)continue;if(V.confirm){if(!await Z.confirm(V.label,V.confirm.message)){Z.notify("Cancelled.");continue}}let D=await $.apply({command:z.command,sectionId:Q.id,...W?{itemId:W.id}:{},actionId:V.id,values:j,...V.confirm?{confirmed:!0}:{},...X.sessionId!==void 0?{sessionId:X.sessionId}:{}},J);Z.notify(D.text,D.ok?"info":"error"),z=D.menu}}}import{createHash as pz,randomUUID as uz}from"node:crypto";import{setTimeout as lz}from"node:timers/promises";var OJ=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 CJ}from"node:crypto";var PJ=86400000,TJ=300000,AJ=3600000,SJ=60000,RJ=900000,EJ=300000;function V3($){return $ instanceof Error?$.message:String($)}function U3($){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 j3($){let Z=V3($),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 a1($){return CJ("sha256").update($).digest("hex")}function I6($){let Z=a1($.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(U3($.error))z=Math.min(AJ,TJ*2**Math.min(J-1,6));else z=PJ;return{message:V3($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:J,tokenHash:Z}}function Z1($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===a1(Z)}function C$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function P$($){let X=($.previous?.retryCount??0)+1,J,z=$.error?.retryAfter;if(typeof z==="number"&&z>0)J=z*1000;else if(j3($.error))J=Math.min(RJ,SJ*2**Math.min(X-1,6));else J=EJ;return{message:V3($.error),checkedAt:$.now,nextRetryAt:$.now+J,retryCount:X}}function n1($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function D3($){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 IJ($){return $==="chatgptaccountid"||$==="email"||$==="orgname"||$==="organizationname"}var k2=I0({extraSecretKeys:IJ}),ZV=k2.redact,y2=k2.redactStrings;import{createServer as f2}from"node:http";import{setTimeout as bJ}from"node:timers/promises";var k6="app_EMoamEEZ73f0CkXaXp7hrann",P1="https://auth.openai.com",A$=1455,xJ=3000,kJ="cortexkit-opencode-openai-auth";function h2($){return`${kJ}/${$}`}var v2="main",yJ=`"${v2}" is a reserved account id; choose a different label.`;function m2($){let Z=new Uint8Array($),X=String.fromCharCode(...Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function fJ(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[J%66]).join(""),X=m2(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function r1($){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 o1($){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 S$($){if($.id_token){let Z=r1($.id_token),X=Z&&o1(Z);if(X)return X}if($.access_token){let Z=r1($.access_token);return Z?o1(Z):void 0}return}function gJ($){return typeof $==="string"&&$.toLowerCase()===v2}function K3($){if(gJ($))throw Error(yJ);return $}function hJ($,Z,X){let J=new URLSearchParams({response_type:"code",client_id:k6,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`${P1}/oauth/authorize?${J.toString()}`}async function vJ($,Z,X){let J=await fetch(`${P1}/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:k6,code_verifier:X.verifier}).toString()});if(!J.ok)throw Error(`Token exchange failed: ${J.status}`);return await J.json()}function mJ($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var wJ=`<!doctype html>
11
11
  <html>
12
12
  <head>
13
13
  <title>CortexKit OpenAI Auth - Authorization Successful</title>
@@ -90,33 +90,33 @@ ${Z.join(`
90
90
  <div class="container">
91
91
  <h1>Authorization Failed</h1>
92
92
  <p>An error occurred during authorization.</p>
93
- <div class="error">${xJ($)}</div>
93
+ <div class="error">${mJ($)}</div>
94
94
  </div>
95
95
  </body>
96
- </html>`,x6=[],T$,d0=new Map;function b4($,Z){return new Promise((X,J)=>{let G=(B)=>{$.off("listening",z),J(B)},z=()=>{$.off("error",G),X()};$.once("error",G),$.once("listening",z),$.listen(A$,Z)})}function f4($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function O1(){return d0.size}function T1($){if(d0.delete($),O1()===0)C1()}async function yJ(){let $=`http://localhost:${A$}/auth/callback`;if(x6.length>0)return{port:A$,redirectUri:$};if(T$)return T$;T$=(async()=>{let Z=(z,B)=>{let Q=new URL(z.url||"/",`http://127.0.0.1:${A$}`);if(Q.pathname==="/auth/callback"){let Y=Q.searchParams.get("code"),H=Q.searchParams.get("state"),W=Q.searchParams.get("error"),V=Q.searchParams.get("error_description");if(W){let D=V||W;if(H){let U=d0.get(H);if(U)U.reject(Error(D)),T1(H);else if(O1()===0)C1()}else if(O1()===0)C1();B.writeHead(200,{"Content-Type":"text/html"}),B.end(b6(D));return}if(!H){if(O1()===0)C1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(b6("Missing state parameter"));return}if(!Y){if(O1()===0)C1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(b6("Missing authorization code"));return}let j=d0.get(H);if(!j){if(O1()===0)C1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(b6("Unknown state — authorization may have expired"));return}T1(H),bJ(Y,$,j.pkce).then((D)=>j.resolve(D)).catch((D)=>j.reject(D)),B.writeHead(200,{"Content-Type":"text/html"}),B.end(kJ);return}if(Q.pathname==="/cancel"){let Y=Q.searchParams.get("state"),H=Y?[Y]:[...d0.keys()];B.writeHead(200),B.end("Login cancelled");for(let W of H){let V=d0.get(W);if(!V)continue;V.reject(Error("Login cancelled")),T1(W)}if(O1()===0)C1();return}B.writeHead(404),B.end("Not found")},X=I4(Z);await b4(X,"127.0.0.1");let J=[X],G=I4(Z);try{await b4(G,"::1"),J.push(G)}catch(z){let B=z.code;if(B!=="EADDRNOTAVAIL"&&B!=="EAFNOSUPPORT")throw f4(X),z}return x6=J,{port:A$,redirectUri:$}})();try{return await T$}finally{T$=void 0}}function C1(){let $=x6;x6=[];for(let Z of $)f4(Z)}function fJ($,Z,X=300000,J){return new Promise((G,z)=>{if(J?.aborted){T1(Z),z(Error("Login cancelled"));return}let B=setTimeout(()=>{if(d0.get(Z))T1(Z),z(Error("OAuth callback timeout — authorization took too long"))},X),Q=()=>{if(clearTimeout(B),d0.get(Z))T1(Z),z(Error("Login cancelled"))};if(J)J.addEventListener("abort",Q);d0.set(Z,{pkce:$,state:Z,resolve:(Y)=>{if(clearTimeout(B),J)J.removeEventListener("abort",Q);G(Y)},reject:(Y)=>{if(clearTimeout(B),J)J.removeEventListener("abort",Q);z(Y)}})})}async function gJ($){let Z=await fetch(`${P1}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":x4($)},body:JSON.stringify({client_id:k6})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${P1}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function hJ($,Z,X){let J=Math.max(parseInt($.interval,10)||5,1)*1000,G=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),z=!Number.isNaN(G)&&G>0?G*1000:900000,B=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-B>z)throw Error("Device authorization expired");let Q=await fetch(`${P1}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":x4(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(Q.ok){let W=await Q.json(),V=await fetch(`${P1}/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:`${P1}/deviceauth/callback`,client_id:k6,code_verifier:W.code_verifier}).toString()});if(!V.ok)throw Error(`Token exchange failed: ${V.status}`);return await V.json()}if(Q.status!==403&&Q.status!==404)throw Error(`Device authorization failed: ${Q.status}`);let Y=z-(Date.now()-B);if(Y<=0)throw Error("Device authorization expired");let H=Math.min(J+TJ,Y);try{await PJ(H,void 0,{signal:X})}catch(W){if(W instanceof Error&&W.name==="AbortError")throw Error("Device authorization cancelled");throw W}}}async function g4($){let{label:Z,headless:X=!1,signal:J,version:G}=$;if(D3(Z),X){let{deviceData:W,url:V,instructions:j}=await gJ(G),D=(async()=>{let U=await hJ(W,G,J),N=Date.now(),K=S$(U);return{id:D3(Z||K||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:U.access_token,refresh:U.refresh_token,expires:N+(U.expires_in??3600)*1000,enabled:!0,addedAt:N,lastUsed:N,lastRefreshedAt:N,accountId:K}})();return{url:V,instructions:j,completion:D}}let{redirectUri:z}=await yJ(),B=await RJ(),Q=y4(crypto.getRandomValues(new Uint8Array(32)).buffer),Y=IJ(z,B,Q),H=(async()=>{try{if(J?.aborted)throw Error("Login cancelled");let W=await fJ(B,Q,void 0,J),V=Date.now(),j=S$(W);return{id:D3(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{T1(Q)}})();return{url:Y,instructions:"Complete authorization in your browser. This window will close automatically.",completion:H}}import{basename as vJ,dirname as mJ,join as wJ}from"node:path";var y6="openai-auth.json",h4="openai-auth-state.json";function K3($){return vJ($)===y6?wJ(mJ($),h4):`${$}.state.json`}function f6($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let J=Z<100000000000?Z*1000:Z,G=new Date(J);return Number.isNaN(G.getTime())?void 0:G.toISOString()}let X=new Date($);return Number.isNaN(X.getTime())?void 0:X.toISOString()}function q3($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function v4($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function m4($,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 G=Z.slice(0,-13),z=q3($.get(`${G}-window-minutes`)),B=f6($.get(`${G}-reset-at`)??void 0);if(J===0&&$.get(`${G}-window-minutes`)==="0"&&!B)return;return{usedPercent:J,remainingPercent:100-J,resetsAt:B,checkedAt:Date.now(),...z!==void 0?{windowMinutes:z}:{}}}var u4=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function l4($,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 d4($){if(u4.some((G)=>l4($,G)==="invalid"))return{};let Z={},X=m4($,"x-codex-primary-used-percent");if(X)Z.primary=X;let J=m4($,"x-codex-secondary-used-percent");if(J)Z.secondary=J;return Z}function c4($){let Z=u4.map((X)=>l4($,X));return Z.includes("valid")&&!Z.includes("invalid")}function w4($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=q3($.window_minutes),X=f6($.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 s4($){let Z={},X=w4($.rate_limits?.primary);if(X)Z.primary=X;let J=w4($.rate_limits?.secondary);if(J)Z.secondary=J;return Z}function t1($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function p4($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=q3($.limit_window_seconds),X=f6($.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 i4($){let Z={},X=p4($.rate_limit?.primary_window);if(X)Z.primary=X;let J=p4($.rate_limit?.secondary_window);if(J)Z.secondary=J;let G=v4($.rate_limit_reset_credits?.available_count);if(G!==void 0)Z.resetCreditsAvailable=G;let z=v4($.rate_limit_reset_credits?.applicable_available_count);if(z!==void 0)Z.resetCreditsApplicable=z;let B=$.spend_control?.individual_limit;if($.spend_control===null||B===null)Z.spendControlCleared=!0;if(B&&typeof $.spend_control?.reached==="boolean"){let Y=t1(B.limit),H=t1(B.used),W=t1(B.remaining),V=t1(B.used_percent),j=t1(B.remaining_percent);if(Y!==void 0&&H!==void 0&&W!==void 0&&V!==void 0&&j!==void 0)Z.spendControl={limit:Y,used:H,remaining:W,usedPercent:V,remainingPercent:j,resetsAt:f6(B.reset_at),unit:B.unit,source:B.source,reached:$.spend_control.reached}}let Q=$.credits;if(Q&&typeof Q.has_credits==="boolean"&&typeof Q.unlimited==="boolean"&&typeof Q.overage_limit_reached==="boolean"){let Y=t1(Q.balance);Z.credits={hasCredits:Q.has_credits,unlimited:Q.unlimited,overageLimitReached:Q.overage_limit_reached,...Y!==void 0?{balance:Y}:{}}}return Z}import{ClaustrumClient as MG}from"@cortexkit/claustrum-client";import{resolve as a4}from"node:path";import{storeIdentity as pJ}from"@cortexkit/claustrum-client";import{SubcClient as uJ}from"@cortexkit/subc-client";function n4($){let Z=$.identity??pJ($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let X,J=!1,G,z=new Promise((Q,Y)=>{G=setTimeout(()=>Y(Error("insula usage timeout")),3000),G.unref?.()}),B=(async()=>{if(X=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await uJ.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),J)throw X.close(),Error("insula usage timeout");let Q=await X.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await X.request(Q,{method:"usage.get",params:{}})})();try{return await Promise.race([B,z])}finally{J=!0,clearTimeout(G),X?.close()}}}}var F3=60000,lJ=4*F3,N3=new Map,g6=new Map;function M3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class r4{transport;key;#$=[];#Z;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Z)return this.#Z;for(let[X,J]of g6)if($-J>=F3)g6.delete(X);let Z=g6.get(this.key);if(Z!==void 0&&$-Z<F3)return Promise.resolve();return g6.set(this.key,$),this.#Z=(async()=>{try{let X=await this.transport.getUsage();if(!M3(X)||!Array.isArray(X.result)||X.error!==void 0)throw Error("unavailable insula usage");this.#$=X.result.filter((J)=>M3(J)&&typeof J.provider==="string")}catch{this.#$=[]}})().finally(()=>{this.#Z=void 0}),this.#Z}current($,Z,X){for(let J of this.#$){if(J.provider!==$||typeof J.account!=="string"||J.account.trim()!==Z)continue;if(J.stale!==void 0||J.errorClass!==void 0||!M3(J.usage))continue;let G=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!Number.isFinite(G)||X-G>=lJ)continue;return{entry:J,context:{fetchedAt:G,...typeof J.source==="string"&&{source:J.source}}}}return}}function o4($,Z){let X=JSON.stringify([a4($.connectionFile),a4(Z)]),J=N3.get(X);if(!J)J={source:new r4($,X),refs:0},N3.set(X,J);J.refs++;let G=!1;return{source:J.source,release(){if(G)return;if(G=!0,--J.refs===0)N3.delete(X)}}}import{ClaustrumCredentialError as iV}from"@cortexkit/claustrum-client";function L3($){let Z=new AbortController,X=[],J=!1,G=()=>{if(J)return;J=!0;for(let{source:Q,listener:Y}of X)Q.removeEventListener("abort",Y);X.length=0},z=(Q)=>{if(J||Z.signal.aborted)return;Z.abort(Q),G()},B=$.find((Q)=>Q.aborted);if(B)return Z.abort(B.reason),{signal:Z.signal,dispose:G};for(let Q of $){if(Z.signal.aborted)break;let Y=()=>z(Q.reason);if(X.push({source:Q,listener:Y}),Q.addEventListener("abort",Y,{once:!0}),Q.aborted)z(Q.reason)}return{signal:Z.signal,dispose:G}}import{ClaustrumCredentialError as GG}from"@cortexkit/claustrum-client";import{createHash as dJ,randomBytes as cJ,randomUUID as sJ}from"node:crypto";import{constants as t4}from"node:fs";import{chmod as iJ,mkdir as aJ,open as J2,readFile as _3,realpath as nJ,rename as rJ,stat as G2,unlink as z2}from"node:fs/promises";import{basename as B2,dirname as J1,extname as e4,isAbsolute as $2,join as C3,resolve as oJ}from"node:path";import{ClaustrumCredentialError as tJ,ClaustrumClient as eJ,writeEnrollmentTokenFile as $G}from"@cortexkit/claustrum-client";class R extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var ZG=1,v6=16384,Q2=30000,P3=/^[0-9a-f]{64}$/,Y2=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),H2=new Set(["pending_queue_full"]);function O3($){if(!($ instanceof tJ))return;if(Y2.has($.code))return{code:$.code,disposition:"terminal"};if(H2.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function T3($,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 A3($){return eJ.connect($)}function W2($){let Z=e4($)||".json",X=B2($,e4($));return{statePath:C3(J1($),`${X}-state${Z}`),tokenPath:$}}function S3($){let Z=$.override?.trim();if(Z&&!$2(Z)&&!$.cwd)throw new R("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?$2(Z)?Z:oJ($.cwd,Z):C3($.stateDir,`${$.host}-enrollment.json`);return W2(X)}function V2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function h6($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function U2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function R$(){return new R("invalid-state","invalid Claustrum enrollment state")}function w6($){if(!V2($)||$.version!==ZG||typeof $.proposedName!=="string"||$.proposedName.length===0)throw R$();if($.phase==="pending"){if(!P3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!h6($.createdAt)||!h6($.updatedAt))throw R$();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)||!U2($.tokenGeneration)||!h6($.updatedAt))throw R$();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"||!h6($.updatedAt))throw R$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw R$()}function R3($){if(!V2($)||!P3.test(String($.token??""))||!U2($.token_generation))throw new R("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function XG($){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 Z2($){try{return JSON.parse($)}catch{throw new R("invalid-state","Claustrum enrollment file is not valid JSON")}}async function G1($){if(I)try{await K0(J1($));let X=await M0($,!0);if(Buffer.byteLength(X)>v6)throw new R("unsafe-file","Claustrum enrollment file is too large");return Z2(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await J2($,t4.O_RDONLY|t4.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new R("unsafe-file","Claustrum enrollment file could not be opened safely")}try{XG(await Z.stat());let X=Buffer.alloc(v6+1),{bytesRead:J}=await Z.read(X,0,X.byteLength,0);if(J>v6)throw new R("unsafe-file","Claustrum enrollment file is too large");return Z2(X.subarray(0,J).toString("utf8"))}finally{await Z.close()}}function X2($,Z){let X=[];for(let J of $.split(`
97
- `)){if(J.trim()===""||J.startsWith("#"))continue;let G=J.split(":");if(G.length!==Z||!/^[^\s:,]+$/.test(G[0]??"")||!/^\d+$/.test(G[2]??"")||!Number.isSafeInteger(Number(G[2]))||Z===7&&(!/^\d+$/.test(G[3]??"")||!Number.isSafeInteger(Number(G[3])))||Z===4&&G[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(G[3]??""))return;X.push(G)}return X}async function JG($,Z,X){try{let[J,G]=await Promise.all([_3(X.passwdPath??"/etc/passwd","utf8"),_3(X.groupPath??"/etc/group","utf8")]),z=X2(J,7),B=X2(G,4);if(!z||!B)return!1;let Q=z.filter((V)=>Number(V[2])===$),Y=B.filter((V)=>Number(V[2])===Z);if(Q.length!==1||Y.length!==1)return!1;let H=Q[0]?.[0],W=Y[0]?.[3]??"";return(W===""||W.split(",").every((V)=>V===H))&&!z.some((V)=>Number(V[2])!==$&&Number(V[3])===Z)}catch{return!1}}function j2($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>_3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function D2($,Z={}){if(!I){let X=process.geteuid?.();if(X===void 0)return;let J=process.getegid?.(),G;try{G=await nJ($)}catch{return}let z;for(;;){let B=await G2(G).catch(()=>{return});if(B&&(B.mode&18)!==0&&(B.mode&512)===0){if(z===void 0)z=J!==void 0&&await JG(X,J,Z);if((B.mode&2)!==0||B.uid!==X||B.gid!==J||!z)throw new R("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${G}. Another user could replace it. Run: chmod g-w,o-w ${G}`)}let Q=J1(G);if(Q===G)return;G=Q}}try{await v0($,j2(Z))}catch(X){if(!(X instanceof d))throw X;throw new R("unsafe-file",`Claustrum enrollment parent refused: ${X.path} (${X.reason??X.code}). Use a folder that other users cannot write or replace.`)}}async function m6($,Z={}){if(I){await K0($,!1,j2(Z));return}await aJ($,{recursive:!0,mode:448});let X=await G2($),J=process.geteuid?.();if(J!==void 0&&X.uid!==J)throw new R("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((X.mode&63)!==0)await iJ($,448)}async function A1($,Z,X={}){let J=J1($);await m6(J,X),await D2(J,X);let G=`${JSON.stringify(Z)}
98
- `;if(Buffer.byteLength(G)>v6)throw new R("invalid-state","Claustrum enrollment state is too large");if(I)return v1($,G);let z=C3(J,`.${B2($)}.${process.pid}.${sJ()}.tmp`),B,Q=!1;try{B=await J2(z,"wx",384),Q=!0,await B.writeFile(G,"utf8"),await B.chmod(384),await B.sync(),await B.close(),B=void 0,await rJ(z,$),Q=!1}finally{if(await B?.close().catch(()=>{}),Q)await z2(z).catch(()=>{})}}async function E$($,Z){let X=await G1($.tokenPath),J=X===void 0?void 0:R3(X),G=await G1($.statePath),z=G===void 0?void 0:w6(G);if(J)return{state:"approved",proposedName:z?.proposedName??Z,...z?.phase==="approved"&&z.approvedName!==void 0&&{approvedName:z.approvedName},tokenGeneration:J.token_generation};if(!z)return{state:"idle"};if(z.phase==="approved")return{state:"blocked",proposedName:z.proposedName,code:"missing_token"};return X1(z)}async function E3($,Z){let X;try{X=await E$($,Z)}catch(J){if(!(J instanceof R)||J.kind!=="invalid-state"&&J.kind!=="invalid-token")return"unreadable";try{let G=await G1($.statePath);if(G===void 0)return"unreadable";let z=w6(G);return z.phase==="approved"&&z.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 S1($){let Z=await G1($);if(Z===void 0)throw new R("not-enrolled","Claustrum enrollment is not configured");return R3(Z)}function X1($){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 K2(){return new R("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class p6{#$;#Z;#z;#J;#W;#Q;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#z=$.proposedName,this.#J=$.now??Date.now,this.#W=$.mintSecret??(()=>cJ(32).toString("hex")),this.#Q=$.writeTokenFile??$G}async status(){return E$(this.#Z,this.#z)}async resetTerminal(){return q2(this.#Z,this.#z)}async#B($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#J()};return await A1(this.#Z.statePath,X,this.#X),X1(X)}async reconcile(){await m6(J1(this.#Z.statePath),this.#X);let $=await e({name:"ceremony",path:this.#Z.statePath,ttlMs:Q2,renew:!0});if(!$)return{state:"busy"};try{let Z=await G1(this.#Z.tokenPath),X=Z===void 0?void 0:R3(Z),J=await G1(this.#Z.statePath),G=J===void 0?void 0:w6(J);if(G&&G.proposedName!==this.#z)throw K2();if(X){if(!G||G.phase==="pending"){let B={version:1,phase:"approved",proposedName:G?.proposedName??this.#z,tokenGeneration:X.token_generation,updatedAt:this.#J()};await A1(this.#Z.statePath,B,this.#X),G=B}return{state:"approved",proposedName:G.proposedName,...G.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:X.token_generation}}if(G?.phase==="approved"){let B={version:1,phase:"blocked",proposedName:G.proposedName,errorCode:"missing_token",updatedAt:this.#J()};return await A1(this.#Z.statePath,B,this.#X),X1(B)}if(G&&G.phase!=="pending")return X1(G);if(!G){let B=this.#J();if(G={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#W(),createdAt:B,updatedAt:B},!P3.test(G.requestSecret))throw new R("invalid-state","invalid minted Claustrum enrollment secret");await A1(this.#Z.statePath,G,this.#X)}if(!G.requestId)try{let B=dJ("sha256").update(Buffer.from(G.requestSecret,"hex")).digest("hex"),Q=await this.#$.enrollPropose({name:G.proposedName,requestSecretHash:B});G={...G,requestId:Q.requestId,updatedAt:this.#J()},await A1(this.#Z.statePath,G,this.#X)}catch(B){let Q=O3(B);if(!Q)throw B;if(Q.disposition==="retry")return{state:"pending",proposedName:G.proposedName,retryCode:Q.code};return this.#B(G,Q.code)}let z=G.requestId;if(!z)return X1(G);try{let B=await this.#$.enrollPoll({requestId:z,requestSecret:G.requestSecret});if(B.status==="pending")return X1(G);if(B.status==="denied"){let Y={version:1,phase:"denied",proposedName:G.proposedName,updatedAt:this.#J()};return await A1(this.#Z.statePath,Y,this.#X),X1(Y)}await m6(J1(this.#Z.tokenPath),this.#X),await D2(J1(this.#Z.tokenPath),this.#X),await this.#Q(this.#Z.tokenPath,{token:B.token,token_generation:B.tokenGeneration});let Q={version:1,phase:"approved",proposedName:G.proposedName,approvedName:B.name,tokenGeneration:B.tokenGeneration,updatedAt:this.#J()};return await A1(this.#Z.statePath,Q,this.#X),X1(Q)}catch(B){let Q=O3(B);if(!Q)throw B;if(Q.disposition==="retry")return{state:"pending",proposedName:G.proposedName,requestId:z,retryCode:Q.code};return this.#B(G,Q.code)}}finally{await $.release()}}}async function q2($,Z){await m6(J1($.statePath));let X=await e({name:"ceremony",path:$.statePath,ttlMs:Q2,renew:!0});if(!X)return"busy";try{if(await G1($.tokenPath)!==void 0)return"refused-approved";let J=await G1($.statePath);if(J===void 0)return"idle";let G=w6(J);if(G.proposedName!==Z)throw K2();if(G.phase==="pending")return"refused-pending";return await X.assertOwned(),await z2($.statePath),"reset"}finally{await X.release()}}var I$="claustrum-tombstone:v1:";function u6($){return`${I$}${$}`}function I3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function l6($){return typeof $==="string"&&$.startsWith(I$)}function N2($,Z){if(!I3($)||$.type!=="oauth")return!1;return $.refresh===u6(Z)}function M2($,Z){if(N2($,Z))return"placeholder";if(I3($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!l6($.refresh))return"login";if(I3($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function b3($){let Z=M2($.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 F2($,Z){return Z!==void 0&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function zG($,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 L2=a("claustrum");function y3($,Z,X,J=L2){let G=F2(Z,X);return J.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:G,reason:zG(Z,X)}),G}var k3=300000;function x3(){return new R("invalid-material","Claustrum returned invalid credential material")}function BG($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw x3()}if(!X||typeof X!=="object")throw x3();let J=X,G=J.access_token??J.access;Z=typeof G==="string"?G:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(I$))throw x3();return Z}function QG($,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 d6{#$;#Z;#z;#J;#W;#Q;#X;#B=new WeakMap;#V=new WeakMap;#Y=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>S1(Z);else throw new R("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#J=$.family,this.#W=$.parseIdentity,this.#Q=$.requireAssertion??!1,this.#z=$.now??Date.now,this.#X=$.logger??L2}#G($){if(this.#Y)throw new R("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#U($){this.#G($);let Z=await this.#Z();if(this.#G($),!/^[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#H($,Z){this.#G(Z);let X,J;try{let G=$();X=Z?await Promise.race([G,new Promise((z,B)=>{let Q=()=>B(Z.reason);if(Z.addEventListener("abort",Q,{once:!0}),J=()=>Z.removeEventListener("abort",Q),Z.aborted)Q()})]):await G}catch(G){if(this.#G(Z),G instanceof GG)throw G;throw new R("unavailable","Claustrum scoped operation unavailable")}finally{J?.()}return this.#G(Z),X}async discover($){let Z=await this.#U($),X=await this.#H(()=>this.#$.listScoped(Z),$),J=[],G=[],z=new Map;for(let Q of X.rows){let Y=QG(Q,this.#J);if(!Y)continue;G.push({row:Q,type:Y}),z.set(Q.id,(z.get(Q.id)??0)+1)}let B=[];for(let{row:Q,type:Y}of G){let H;if(!Q.id.trim())H="empty credential id";else if((z.get(Q.id)??0)>1)H="duplicate credential id";else if(Q.accountId!==void 0&&!Q.accountId.trim())H="blank account identity";else if(!Q.state.trim())H="empty state";if(H){J.push({...Q.id.trim()&&{credentialId:Q.id},reason:H});continue}B.push(Object.freeze({credentialId:Q.id,credentialType:Y,...Q.accountId!==void 0&&{accountIdentity:Q.accountId},state:Q.state,...Q.email!==void 0&&{email:Q.email},...Q.orgName!==void 0&&{orgName:Q.orgName}}))}for(let Q of J)this.#X.warn("skipped malformed vault record",Q);return{view:X.view,credentials:Object.freeze(B),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:G}=$;if(this.#Q&&G===void 0)throw new R("identity-unasserted","Claustrum dispatch requires a known account identity");let z=await this.#U(Z),B=await this.#H(()=>this.#$.getScoped({credentialId:X,enrollmentToken:z,...J==="oauth"&&{minTtlMs:k3}}),Z);if(B.credentialId!==void 0&&B.credentialId!==X)throw new R("identity-changed","Claustrum served credential identity changed");let Q=B.expiresAtMs;if(!Number.isSafeInteger(B.recordVersion)||B.recordVersion<0||Q===null&&J==="oauth"||Q!==null&&(!Number.isFinite(Q)||Q-this.#z()<k3))throw new R("insufficient-validity","Claustrum served credential has insufficient validity");let Y=BG(B.material),H=B.accountId?.trim()?B.accountId:void 0;if(this.#Q&&(B.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.#W?.(Y):void 0,V=H??W;if(G!==void 0&&V!==void 0&&V!==G)throw new R("identity-changed","Claustrum served credential identity changed");let j=V??G,U=Object.freeze(Object.defineProperty({credentialId:X,credentialType:J,...j!==void 0&&{accountIdentity:j},accountIdentitySource:H!==void 0?"asserted":W!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...B.credentialId!==void 0&&{assertedCredentialId:B.credentialId},...H!==void 0&&{assertedAccountIdentity:H},...B.projectId!==void 0&&{projectId:B.projectId},recordVersion:B.recordVersion,expiresAtMs:Q},"accessToken",{value:Y,enumerable:!1}));return this.#B.set(U,z),U}async reportFailure($,Z,X){if(Z!==401)return;this.#G();let J=this.#B.get($);if(!J)throw new R("no-receipt","Claustrum failure report requires an original dispatch receipt");let G=this.#V.get($);if(G)return G;let z=this.#H(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:J,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#V.set($,z);try{await z,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(B){throw this.#V.delete($),B}}close(){if(this.#Y)return;this.#Y=!0,this.#$.close()}}import{createHash as YG}from"node:crypto";function _2($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function f3($,Z,X){return $.some((J)=>_2(J,Z,X))}function g3($,Z,X){let J={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((G)=>G.credentialId!==Z||G.accountIdentity!==X),J]}function h3($,Z,X){return $.filter((J)=>!Z.some((G)=>_2(J,G,X)))}var C2="vault:";function HG($){return YG("sha256").update($).digest("hex")}function WG($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function VG($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function z1($){return[$.credentialId,...$.aliases??[]]}function P2($,Z,X={}){let J=X.now??Date.now(),G=X.routePrefix??C2,z=X.reservedRouteIds??new Set,B=$?.rows??[],Q=[...$?.declined??[]],Y=Z.skipped.length===0,H=new Set(Z.credentials.map((F)=>F.credentialId)),W=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),V=Z.skipped.some((F)=>F.credentialId===void 0),j=(F)=>!H.has(F)&&(W.has(F)||V),D=new Map;for(let F of B){if(F.accountIdentity===void 0)continue;for(let q of z1(F))if(!D.has(q))D.set(q,F.accountIdentity)}let U=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:D.get(F.credentialId),claimed:!1},L=VG(q),S=U.get(L)??[];S.push(q),U.set(L,S)}let N=new Set,K=new Set(z),M=[],P=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),E=[...U.values()].map((F)=>F.toSorted(P)).sort((F,q)=>F[0]&&q[0]?P(F[0],q[0]):0);for(let F of E){let q=F[0]?.identity,L=F.filter((v)=>v.credential.state==="active"),S=L.length?L:F,A=S.filter((v)=>v.claimed),x=A.length?A:S,w=new Set(F.map((v)=>v.credential.credentialId)),y=B.find((v)=>!N.has(v)&&z1(v).some((g0)=>w.has(g0))&&(v.accountIdentity===void 0||v.accountIdentity===q)),f=x.find((v)=>v.credential.credentialId===y?.credentialId)??x[0];if(!f)continue;let h=f.credential,r=y??(q===void 0?void 0:B.find((v)=>!N.has(v)&&v.accountIdentity===q));if(r)N.add(r);let c=r?.routeId;if(!c||z.has(c)){let v=`${G}${h.credentialId}${q===void 0?"":`~${HG(q).slice(0,10)}`}`;c=v;for(let g0=2;K.has(c);g0++)c=`${v}~${g0}`}K.add(c);let r$=r?z1(r).filter(j):[],x1=[...new Set([...F.map((v)=>v.credential.credentialId),...r$])].filter((v)=>v!==h.credentialId).sort((v,g0)=>v.localeCompare(g0)),o$=X.mapAccount?.(h)??{};M.push({previousIndex:r?B.indexOf(r):1/0,row:{routeId:c,credentialId:h.credentialId,credentialType:h.credentialType,...q!==void 0&&{accountIdentity:q},...x1.length&&{aliases:x1},state:h.state,label:o$.label?.trim()||WG(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...x1].some((v)=>f3(Q,v,q)),addedAt:r?.addedAt??J,...r?.quota!==void 0&&{quota:r.quota},...!f.claimed&&q!==void 0&&{unclaimed:!0}}})}return B.forEach((F,q)=>{if(N.has(F)||!z1(F).some(j))return;if(K.has(F.routeId))return;let[L,...S]=z1(F).filter((w)=>!H.has(w));if(L===void 0)return;K.add(F.routeId);let{aliases:A,...x}=F;M.push({previousIndex:q,row:{...x,credentialId:L,...S.length&&{aliases:S},stale:!0}})}),M.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,complete:Y,...!Y&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:M.map((F)=>F.row),declined:Q}}function v3($){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 b$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function e1($){return $===void 0||typeof $==="string"}function UG($){let Z=b$($)?q1($.quota):void 0;if(!b$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!e1($.accountIdentity)||!e1($.email)||!e1($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((X)=>typeof X==="string"))||$.quota!==void 0&&Z===void 0||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return{...$,...Z===void 0?{}:{quota:Z}}}var jG=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function O2($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!b$(X)||!e1(X.credentialId)||typeof X.reason!=="string"||!jG.has(X.reason))return;Z.push(X)}return Z}function DG($){if(!b$($)||$.version!==1||!e1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!O2($.rejected))throw new R("invalid-state","Claustrum roster file is not valid");let Z=[];for(let G of $.rows){let z=UG(G);if(!z)throw new R("invalid-state","Claustrum roster file is not valid");Z.push(z)}let X=[];for(let G of $.declined){if(!b$(G)||typeof G.credentialId!=="string"||!e1(G.accountIdentity))throw new R("invalid-state","Claustrum roster file is not valid");X.push(G)}let J=O2($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...J&&{rejected:J},rows:Z,declined:X}}async function L0($){let Z;try{Z=await M0($,I)}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 DG(X)}var KG={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},qG={name:"claustrum-roster",ttlMs:30000};async function $$($,Z,X={}){return wZ($,KG,async(J)=>{let G=await L0($),{next:z,result:B}=await Z(G,{assertOwned:()=>J.assertOwned()});if(z)await J.assertOwned(),await F0($,z,{beforeRename:async()=>{await X.beforePublish?.(),await J.assertOwned()}});return B})}function m3($,Z){return $$($,(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");let G=g3(X.declined,J.credentialId,J.accountIdentity);return{next:{...X,declined:G,rows:X.rows.map((z)=>z===J?{...z,enabled:!1}:z)},result:void 0}})}function w3($,Z){return $$($,(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");return{next:{...X,declined:h3(X.declined,z1(J),J.accountIdentity),rows:X.rows.map((G)=>G===J?{...G,enabled:!0}:G)},result:void 0}})}function NG($,Z){if(!z1($).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")&&z1($).length===1)return"bind";return"refuse"}function p3($,Z){return $$($,(X)=>{let J=X?.rows.find((Q)=>Q.routeId===Z.routeId),G=!X||!J?"refuse":NG(J,Z);if(!X||!J||G==="refuse")return{result:!1};let z=E0(J.quota,Z.observation),B=G==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...X,rows:X.rows.map((Q)=>Q===J?{...Q,...B,quota:z}:Q)},result:!0}})}function u3($,Z){return $$($,(X)=>{let J=X?.rows.find((z)=>z.routeId===Z.routeId);if(!X||!J||J.accountIdentity===void 0||J.accountIdentity!==Z.accountIdentity)return{result:!1};let G=E0(J.quota,Z.observation);return{next:{...X,rows:X.rows.map((z)=>z===J?{...z,quota:G}:z)},result:!0}})}async function l3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let X=await e({...qG,path:$.path,renew:!0});if(!X){let J=await L0($.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 $$($.path,async(G)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await X.assertOwned();let z=typeof $.projection==="function"?$.projection():$.projection,B=P2(G,J,z);return{...JSON.stringify(G)!==JSON.stringify(B)&&{next:B},result:B}})}finally{await X.release()}}class c6{#$;#Z=new AbortController;#z;#J;#W;#Q;#X;#B;#V=!1;#Y;constructor($){this.#$=$,this.#z=$.logger??a("claustrum")}#G($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}async#U(){return await this.#$.isCustodyActive?.()??!0}#H($,Z){let X=L3([this.#Z.signal,...Z?[Z]:[]]);return new Promise((J,G)=>{let z=()=>{X.signal.removeEventListener("abort",B),X.dispose()},B=()=>{z(),G(X.signal.reason)};if(X.signal.addEventListener("abort",B,{once:!0}),$.then((Q)=>{if(z(),X.signal.aborted)G(X.signal.reason);else J(Q)},(Q)=>{z(),G(Q)}),X.signal.aborted)B()})}async#D(){if(this.#G(),this.#J)return this.#J;if(!this.#W)this.#W=this.#$.connect().then(($)=>{if(this.#Z.signal.aborted)$.close(),this.#G();if(this.#J=new d6({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#z}),this.#$.insula&&$.insula)this.#Y=o4($.insula,this.#$.tokenPath);return this.#J}).finally(()=>{this.#W=void 0});return this.#H(this.#W)}snapshot(){return this.#X}routingRows(){return v3(this.#X)}refresh(){if(this.#G(),this.#Q)return this.#Q;return this.#Q=(async()=>{if(!await this.#U()){this.#X=void 0,this.#J?.close(),this.#J=void 0,this.#Y?.release(),this.#Y=void 0;return}let $=await this.#D(),Z=await l3({path:this.#$.rosterPath,custody:$,isActive:()=>this.#U(),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.#X?.view;if(this.#X=Z,Z&&X)this.#$.onRoster?.(Z);return Z})().finally(()=>{this.#Q=void 0}),this.#Q}start(){if(this.#V)return;this.#G(),this.#V=!0;let $=async()=>{try{await this.refresh(),await this.refreshInsulaQuota()}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.#B=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#B=void 0,$()},Z),this.#B.unref?.()};$()}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#U())return;try{await S1(this.#$.tokenPath),await this.#D(),await this.#Y?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#U())return;try{return await S1(this.#$.tokenPath),this.#K($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#U())return;try{await S1(this.#$.tokenPath);let X=(await L0(this.#$.rosterPath))?.rows.find((J)=>J.routeId===$);return this.#K(X?.accountIdentity)}catch{return}}#K($){if(!this.#$.insula||!$)return;let Z=this.#Y?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#G(Z);let X=this.#X??await this.#H(this.refresh(),Z);if(!X||!await this.#U())throw new R("not-active","Claustrum scoped custody is not active");let J=await L0(this.#$.rosterPath);this.#G(Z);let G=X.rows.find((Y)=>Y.routeId===$),z=J?.rows.find((Y)=>Y.routeId===$);if(z&&!z.enabled)throw new R("route-declined","Claustrum route is disabled");if(!G||!z||z.state!=="active"||z.credentialId!==G.credentialId||z.accountIdentity!==G.accountIdentity)throw new R("route-unavailable","Claustrum route is disabled, removed or changed");let B=await this.#H(this.#D(),Z),Q=L3([this.#Z.signal,...Z?[Z]:[]]);try{return await B.authorize({credentialId:z.credentialId,credentialType:z.credentialType,...z.accountIdentity!==void 0&&{accountIdentity:z.accountIdentity}},Q.signal)}finally{Q.dispose()}}async reportFailure($,Z,X){if(this.#G(),!this.#J)throw new R("no-receipt","Claustrum dispatch receipt has no active owner");await this.#J.reportFailure($,Z,X)}async send($,Z,X){let J=X.signal,G=await this.authorize($,J),z=await Z(G,J);if(z.status===401&&!J?.aborted){let B;try{B=await this.authorize($,J)}catch{}if(y3(X.site,G,B,this.#z))await z.body?.cancel().catch(()=>{}),G=B,z=await Z(B,J)}if(z.status===401)await this.reportFailure(G,401,X.reporterSource??"direct").catch((B)=>this.#$.onError?.(B)),Promise.resolve().then(()=>this.refresh()).catch((B)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(B)});return z}async decline($){this.#G(),await m3(this.#$.rosterPath,$),this.#X=await L0(this.#$.rosterPath)}async accept($){this.#G(),await w3(this.#$.rosterPath,$),this.#X=await L0(this.#$.rosterPath)}async recordQuota($,Z,X){this.#G();let J=await p3(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.#X=await L0(this.#$.rosterPath);return J}async recordAccountQuota($,Z,X){this.#G();let J=await u3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:X});if(J)this.#X=await L0(this.#$.rosterPath);return J}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new R("closed","Claustrum consumer is closed")),this.#B)(this.#$.clearTimeoutImpl??clearTimeout)(this.#B);this.#B=void 0,this.#J?.close(),this.#Y?.release(),this.#Y=void 0,this.#X=void 0}}async function T2($){let Z=await MG.connect($);return Object.assign(Z,{insula:n4($)})}var FG=u6("openai");function A2($){return l6($)}function k0($){if(!$||$.corrupt===!0)return!1;return A2($.refresh)}class x$ 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 s6($){if(A2($))throw new x$}function c0($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var LG=a("quota");var _G="app_EMoamEEZ73f0CkXaXp7hrann",OG="https://auth.openai.com";async function S2($){s6($.refreshToken);let Z=await $.fetchImpl(`${OG}/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:_G}).toString()});if(!Z.ok){let G=j3(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:G,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 CG="https://chatgpt.com/backend-api/wham/usage";async function Z$($){let Z=$.logger??LG,X=$.accountKey??"unknown",J=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let G=await $.fetchImpl(CG,{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(!G.ok){let B=j3(G.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${G.status}`),{status:G.status,retryAfter:B})}let z=i4(await G.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:X,status:G.status,elapsedMs:Date.now()-J}),z}catch(G){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:X,status:typeof G?.status==="number"?G.status:"error",elapsedMs:Date.now()-J,error:c0(G)}),G}}import{createHash as AG}from"node:crypto";var SG=globalThis.setTimeout,RG=5;function k$($){let Z=$?.quota?.checkIntervalMinutes??RG;return Math.max(1,Z)*60000}function EG($){return $?.quota?.enabled!==!1}function c3($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function IG($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function R2($,Z,X){if(!EG(Z))return X+k$(Z);let J=IG(Z),G=[];for(let z of["primary","secondary"]){let B=$?.[z];if(!B)continue;if(B.remainingPercent>=J[z])continue;let Q=B.resetsAt?Date.parse(B.resetsAt):Number.NaN;if(!Number.isFinite(Q)||Q<=X)return X+k$(Z);G.push(Q)}if(!G.length)return X+k$(Z);return Math.min(...G)+60000}function bG($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function xG($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function _0($){return AG("sha256").update($).digest("hex").slice(0,16)}class B1{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!==_0($))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($)!==_0(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return X}getAllFallbacks(){return this.fallbacks}setMain($,Z,X,J=!1){if(!J&&!E2(Z.quota))return;if(this.mainTokenFp=_0($),X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)this.clearRateLimited("main");if(X)this.mainQuotaAccountId=X;if(this.main=Z,d3(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,G){if(!J&&!E2(Z.quota))return;let z=this.fallbacks.get($)?.accountId;if(G&&z&&G!==z)this.clearRateLimited($);let B=G??z;if(this.fallbacks.set($,{...Z,accountId:B}),X)this.fallbackTokenFps.set($,_0(X));else this.fallbackTokenFps.delete($);if(d3(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=_0($);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=B1.fallbackInflightKey($,Z),J=this.inflightFallbacks.get(X);if(J)return J;if(this.isFallbackBackedOff($,Z)){let z=this.getFallback($,Z);if(z)return z.quota;throw Error("Quota API rate-limited — try again later")}let G=this._fetchFallback($,Z);return this.inflightFallbacks.set(X,G),G}async refreshAllFallbacks($){let Z=this.now();for(let X of $){if(X.enabled===!1)continue;if(k0(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=_0($);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=xG(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=bG($);if(!X)return;let J=Z?_0(Z):null;if(J&&X.tokenFingerprint&&X.tokenFingerprint!==J)return;let G={quota:X.quota,refreshAfter:R2(X.quota,$,X.checkedAt),checkedAt:X.checkedAt};if(this.main&&this.main.checkedAt>=G.checkedAt&&(!J||!this.mainTokenFp||this.mainTokenFp===J))return;if(this.main=G,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&&n1(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=k$(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 G=this.getFallback(X.id,X.access);if(G&&G.checkedAt>=J)continue;this.setFallback(X.id,{quota:X.quota,refreshAfter:J+Z,checkedAt:J},X.access,!1,X.accountId)}}isBackedOff(){return n1(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==_0(Z))return!1}return n1(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,_0(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<B1.API_CALL_GAP_MS)await new Promise((G)=>{let z=SG(G,B1.API_CALL_GAP_MS-J);if(typeof z==="object"&&"unref"in z)z.unref()});return this.lastApiCallAt=this.now(),$()},X=this.apiGate.then(Z,Z);return this.apiGate=X.catch(()=>{}),X}async _fetchMain($){let Z=_0($);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 e({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(),G=await this._fetchQuota($),z=this.now();if(this.mainTokenFp=_0($),this.main={quota:G,refreshAfter:R2(G,this.storage,z),checkedAt:z},d3(G))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(G,z,this.mainTokenFp,J),G}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 e({name:B1.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),G=this.now();return this.setFallback($,{quota:J,refreshAfter:G+k$(this.storage),checkedAt:G},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(B1.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(B1.isAuthError($))return;this.mainLastApiError=P$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(B1.isAuthError(X))return;let J=_0(Z),G=this.fallbackErrorTokenFps.get($)===J?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,P$({error:X,now:this.now(),previous:G})),this.fallbackErrorTokenFps.set($,J)}}function E2($){return Boolean($.primary||$.secondary)}function d3($){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 aG}from"node:fs/promises";var R1=a("refresh"),a3=a("accounts"),gG=1e4,hG=15000,s3=50;function Q1($){return $.type==="oauth"&&$.corrupt!==!0}function vG($){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 a6 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var mG=[401,403,429],I2={primary:0,secondary:0},wG=!1,Y1={primary:5,secondary:10};function k($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var pG=new Set(["__proto__","constructor","prototype"]);function t3($){return $.length>0&&!pG.has($)}function uG($){return $ instanceof a6||k($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function i6($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():yG(),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 b2($){if(!k($))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 lG($){if(!k($))return;let Z={};for(let G of["primary","secondary"]){let z=$[G];if(!k(z))continue;let B=Number(z.usedPercent),Q=Number(z.remainingPercent),Y=Number(z.checkedAt);if(!Number.isFinite(B)||!Number.isFinite(Q)||!Number.isFinite(Y))continue;let H=typeof z.windowMinutes==="number"?z.windowMinutes:Number.NaN;Z[G]={usedPercent:B,remainingPercent:Q,checkedAt:Y,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,...Number.isFinite(H)&&H>0?{windowMinutes:H}:{}}}for(let G of["resetCreditsAvailable","resetCreditsApplicable"]){let z=typeof $[G]==="number"?$[G]:Number.NaN;if(Number.isFinite(z)&&z>=0)Z[G]=z}let X=$.spendControl;if(k(X)){let G=Number(X.limit),z=Number(X.used),B=Number(X.remaining),Q=Number(X.usedPercent),Y=Number(X.remainingPercent);if(Number.isFinite(G)&&Number.isFinite(z)&&Number.isFinite(B)&&Number.isFinite(Q)&&Number.isFinite(Y)&&typeof X.reached==="boolean")Z.spendControl={limit:G,used:z,remaining:B,usedPercent:Q,remainingPercent:Y,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(k(J)&&typeof J.hasCredits==="boolean"&&typeof J.unlimited==="boolean"&&typeof J.overageLimitReached==="boolean"){let G=Number(J.balance);Z.credits={hasCredits:J.hasCredits,unlimited:J.unlimited,overageLimitReached:J.overageLimitReached,...Number.isFinite(G)?{balance:G}:{}}}return Object.keys(Z).length?Z:void 0}function dG($){if(!k($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!vG(Z))return null;let J=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...i6($),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{...i6($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...i6($),type:"oauth",corrupt:!0}}return{...i6($),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:b2($.lastRefreshError),lastQuotaRefreshError:b2($.lastQuotaRefreshError),quota:lG($.quota)}}function cG($){if(!k($))return;let Z=Object.create(null);for(let[X,J]of Object.entries($)){if(!t3(X)||!k(J))continue;let G={};if(k(J.inFlight))G.inFlight={...J.inFlight};if(k(J.lastOutcome)&&typeof J.lastOutcome.code==="string"&&J.lastOutcome.code.length>0&&typeof J.lastOutcome.at==="number"&&Number.isFinite(J.lastOutcome.at))G.lastOutcome={code:J.lastOutcome.code,at:J.lastOutcome.at,...k(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))G.cooldownUntil=J.cooldownUntil;if(Object.keys(G).length>0)Z[X]=G}return Object.keys(Z).length>0?Z:void 0}var x2=new Set;function sG($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(x2.has(Z))return;x2.add(Z),a3.warn("account load-dropped, preserved on disk",{droppedIds:$})}function iG($){if(!k($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(dG).filter((J)=>J!=null);if(X.length<Z.length){let J=new Set;for(let B of Z)if(k(B)&&typeof B.id==="string"&&B.id.trim())J.add(B.id.trim());let G=new Set(X.map((B)=>B.id)),z=[];for(let B of J)if(!G.has(B))z.push(B);sG(z)}return{version:1,main:{type:"opencode",provider:"openai"},routing:k($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:k($.refresh)?$.refresh:void 0,quota:k($.quota)?$.quota:void 0,reset:cG($.reset),dump:k($.dump)?$.dump:void 0,costZeroing:k($.costZeroing)?$.costZeroing:void 0,killswitch:k($.killswitch)?$.killswitch:void 0,logging:k($.logging)?$.logging:void 0,cachekeep:k($.cachekeep)?$.cachekeep:void 0,cacheKeep:k($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:X}}async function n6($){try{return{exists:!0,value:JSON.parse(await aG($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function r6($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function nG($){let Z;try{Z=(await n6($)).value}catch{return null}return zz(Z)}function rG($,Z){if(!k($))return $;let X=k(Z)?Z:{},J=k(X.main)?X.main:void 0,G=k(X.accounts)?X.accounts:{},z=k($.quota)?$.quota:{},B=k($.refresh)?$.refresh:{},Q=J??z,Y=J??B,W=B.mainRefreshLeaseId!==void 0?{id:B.mainRefreshLeaseId,until:B.mainRefreshLeaseUntil,tokenHash:B.mainRefreshLeaseTokenHash}:{id:Y.refreshLeaseId,until:Y.refreshLeaseUntil,tokenHash:Y.refreshLeaseTokenHash},j=Array.isArray($.accounts)?$.accounts.map((D)=>{if(!k(D))return D;let U=typeof D.id==="string"&&k(G[D.id])?G[D.id]:{};return{...D,...U}}):void 0;return oG({...$,refresh:r6({...B,mainLastRefreshError:B.mainLastRefreshError??Y.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:r6({...z,mainQuota:Q.quota,mainQuotaCheckedAt:Q.quotaCheckedAt,mainQuotaToken:Q.quotaToken,mainLastQuotaApiError:Q.lastQuotaApiError}),accounts:j})}async function e3($){let Z=await n6($.configPath);if(!Z.exists)return null;let X=await n6($.statePath);return iG(rG(Z.value,X.value))}function oG($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function tG($){if($.type==="api")return r6({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return r6({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function o6($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function y$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function eG($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function $z($,Z){if(!eG($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var Zz=300000;function k2($,Z){if($===void 0)return 0;return $>Z+Zz?0:$}function Xz($,Z,X){let J=Date.now(),G=k2(Z.lastRefreshedAt,J),z=k2(X.lastRefreshedAt,J),B=Z.expires??0,Q=X.expires??0,Y=z>G?X:G>z?Z:Q>B?X:B>Q?Z:$z(Z,X);y$($,Y,"access"),y$($,Y,"refresh"),y$($,Y,"expires"),y$($,Y,"lastRefreshedAt"),y$($,Y,"lastRefreshError")}function Jz($,Z){if(!k($))return Z;let X=$,J=o6(X.quota),G=o6(Z.quota),z=J>G,B=z?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!z&&!("lastQuotaRefreshError"in Z))delete B.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete B.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))B.lastUsed=X.lastUsed;return Xz(B,X,Z),B}async function Gz($,Z=!1){let X=Date.now(),J=X+hG,G=0;while(Date.now()<=J){G++;let Q=await e({name:"save",ttlMs:gG,path:$,renew:Z});if(Q)return Q;let Y=J-Date.now();if(Y<=0)break;await fG(Math.min(s3+w2(s3),Y))}let z=Date.now()-X,B=Math.round(z/Math.max(1,G));throw Error(`Timed out after ${z}ms waiting for the account store lock on ${$} (${G} attempts, ~${B}ms apart; retry interval is ${s3}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 zz($){if(!k($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let X of $.accounts){if(!k(X))continue;if(typeof X.id!=="string")continue;let J=X.id.trim();if(!J)continue;Z.add(J)}return Z}function Bz($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:o6($.main.quota),J=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:o6(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 Qz($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function n3($){if(Array.isArray($))return $.map(n3);if(!k($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,n3(X)]))}async function Yz($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},J){let G=Z.statePath,z=await Gz(G);try{let B=(await n6(G)).value,Q=k(B)?{...B,version:1}:{version:1};if(X.mainQuota)Bz(Q,$);if(X.mainRefresh)Qz(Q,$);if(X.accounts){let Y=X.accounts===!0?null:new Set(X.accounts),H=await nG(Z.configPath);Q.accounts={...k(Q.accounts)?Q.accounts:{}};for(let W of $.accounts){if(Y&&!Y.has(W.id))continue;if(H&&!H.has(W.id))continue;Q.accounts[W.id]=Jz(Q.accounts[W.id],tG(W))}if(Y){for(let W of Y)if(!$.accounts.some((V)=>V.id===W))delete Q.accounts[W]}if(H){for(let W of Object.keys(Q.accounts))if(!H.has(W))delete Q.accounts[W]}}if(J&&!J())return;await F0(G,n3(Q))}finally{await z.release()}}function v2($){return $?.fallbackOn?.length?$.fallbackOn:mG}function Hz($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??I2.primary,secondary:Z.secondary??Z["1w"]??I2.secondary}}function r3($){return $?.quota?.enabled!==!1}function g$($){return $?.quota?.failClosedOnUnknownQuota??wG}function t6($,Z,X=Date.now()){if(!r3(Z))return!0;if(!$)return!g$(Z);let J=Hz(Z),G=g$(Z);for(let z of["primary","secondary"]){let B=$[z];if(!B)continue;if(c3(B,X)){if(G)return!1;continue}if(B.remainingPercent<J[z])return!1}return!0}function $8($){return $?.killswitch?.enabled===!0}function y2($){return{primary:$?.primary??$?.["5h"]??Y1.primary,secondary:$?.secondary??$?.["1w"]??Y1.secondary}}function f2($){return typeof $==="number"&&Number.isFinite($)?$:0}function H1($,Z){if(!$?.killswitch)return Y1;if($.killswitch.schema===J$){let{accounts:X,defaults:J}=$.killswitch,G=Z??"main",z=k(X)&&Object.hasOwn(X,G)&&k(X[G])?X[G]:k(J)?J:void 0;return{primary:f2(z?.primary),secondary:f2(z?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return y2($.killswitch.accounts[Z]);return y2($.killswitch.main)}function m2($,Z,X,J=Date.now()){if(!$8(Z))return!0;if(!$)return!g$(Z);let G=H1(Z,X),z=g$(Z);for(let B of["primary","secondary"]){let Q=$[B];if(!Q)continue;if(c3(Q,J)){if(z)return!1;continue}if(Q.remainingPercent<G[B])return!1}return!0}function Wz($){return $?.refresh?.enabled!==!1}function Z8($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function w2($){return Math.floor(Math.random()*($+1))}function E1($,Z,X){return!$.access||!$.expires||$.expires-X<=Z8(Z)}function Vz($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function X$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class p2 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 U0($,Z){let X=$.accounts.findIndex((J)=>J.id===Z.id);if(X!==-1)$.accounts[X]=Z}function f$($){return $ instanceof Error?$.message:String($)}function o3($,Z,X){if(Z instanceof x$)return;$.lastRefreshError=I6({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function i3($,Z,X){if(Z instanceof x$)return;if($.lastQuotaRefreshError=P$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)o3($,Z,X)}function g2($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function Uz($,Z){if(!$)return!1;return g2($.primary,Z)||g2($.secondary,Z)}function jz($,Z,X){if(!$)return!1;let J=Z?.quota?.checkIntervalMinutes??5,G=Math.max(1,J)*60000,z=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return X-z<G}function h2($,Z,X){return!jz($.quota,Z,X)}function Dz($,Z,X,J){return U3(X)&&t6($.quota,Z,J)&&Uz($.quota,J)}function Kz($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var qz=60000,Nz=60000,Mz=600000;function Fz($){return`fallback-oauth-refresh-${kG("sha256").update($).digest("base64url").slice(0,16)}`}var Lz=1e4,_z=100;class Oz{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($)s6($.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+Kz(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return e3(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await Yz($,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(()=>{})},qz+w2(Nz)),"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 G of Z.accounts){if(G.enabled===!1||!Q1(G))continue;if(X$(Z,G))continue;if(k0(G))continue;let z=!1,B=G;try{if(E1(B,Z,this.now())){let Q=B.lastRefreshError;if(Q&&Z1(Q,B.refresh,this.now()))throw z=!0,Error(C$(Q,this.now()));try{B=await this.refreshAccount(B,Z),J=!0}catch(Y){if(uG(Y))continue;z=!0;let H=Z.accounts.find((W)=>W.id===G.id&&Q1(W));if(H&&!Z1(H.lastRefreshError,H.refresh,this.now()))o3(H,Y,this.now()),U0(Z,H),J=!0;throw Y}}if(this.seedFallbackQuota(B,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(B),Z))X.push(B)}catch(Q){let Y=Vz(B,this.now());if(z){if(!Y)continue}else if(!Y)continue;if(Dz(B,Z,Q,this.now()))R1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:B.id,error:f$(Q)}),X.push(B);else if(!g$(Z))X.push(B)}}if(J){let G=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(G)).catch((z)=>{a3.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:f$(z)})})}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){a3.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:f$(Z)})}}accountPassesQuotaPolicy($,Z){return t6($.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(!$||!Wz($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!Q1(X))continue;if(X$($,X))continue;if(k0(X))continue;if(!E1(X,$,this.now()))continue;if(Z1(X.lastRefreshError,X.refresh,this.now()))continue;try{R1.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){R1.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:f$(J)}),o3(X,J,this.now()),U0($,X),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!r3($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!Q1(X))continue;if(X$($,X))continue;if(k0(X))continue;let J=X;try{if(E1(J,$,this.now())){if(Z1(J.lastRefreshError,J.refresh,this.now()))continue;J=await this.refreshAccount(J,$),Z=!0}if(n1(J.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(J,$),!(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access):h2(J,$,this.now())))continue;await this.refreshAccountQuota(J,$),Z=!0}catch(G){i3(X,G,this.now()),U0($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!r3(Z))return{storage:Z,errors:X};if(!this.options.fetchQuotaFn)return{storage:Z,errors:X};let J=$.force??!1,G=!1;for(let z of Z.accounts){if(z.enabled===!1||!Q1(z))continue;if(X$(Z,z))continue;if(k0(z))continue;let B=z;try{if(E1(B,Z,this.now())){let Q=B.lastRefreshError;if(Q&&Z1(Q,B.refresh,this.now()))throw Error(C$(Q,this.now()));B=await this.refreshAccount(B,Z),G=!0}if(!J&&!h2(B,Z,this.now())){if(B.lastQuotaRefreshError)B.lastQuotaRefreshError=void 0,U0(Z,B),G=!0;continue}await this.refreshAccountQuota(B,Z),G=!0}catch(Q){i3(z,Q,this.now()),U0(Z,z),G=!0,X.push({accountId:z.id,message:f$(Q)})}}if(G)await this.save(Z);return{storage:Z,errors:X}}async refreshAccount($,Z,X={}){let J=this.refreshPromises.get($.id);if(J){let B=await J;return U0(Z,B),B}let G=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,G);let z=await G;return U0(Z,z),z}async waitForConcurrentFallbackRefresh($,Z,X,J){let G=Date.now()+Lz;while(Date.now()<G){await new Promise((H)=>setTimeout(H,_z));let z=await this.load(),B=z?.accounts.find((H)=>H.id===$.id&&Q1(H));if(!B)continue;if(this.assertNotTombstoned(B),(B.access!==X.access||B.refresh!==X.refresh||(B.expires??0)>(X.expires??0)+60000)&&(J.force||!E1(B,z,this.now())))return U0(Z,B),R1.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:B.id,expiresInMs:B.expires?B.expires-this.now():void 0}),B;let Y=B.lastRefreshError;if(Y&&Z1(Y,B.refresh,this.now()))throw U0(Z,B),Error(C$(Y,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(X$($,Z))throw new p2(Z.id)}async refreshAccountNow($,Z,X){let J=await this.load(),G=J?.accounts.find((Q)=>Q.id===$.id&&Q1(Q));if(this.assertNotTombstoned(G),this.assertNotShieldedMainRow(J,G,X),G&&!X.force&&!E1(G,J,this.now()))return U0(Z,G),G;let z=G??$,B=await e({name:Fz(z.id),ttlMs:Mz,path:this.paths.configPath,renew:!0});if(!B){R1.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:z.id});let Q=await this.waitForConcurrentFallbackRefresh($,Z,z,X);if(Q)return Q;throw Error("Fallback OAuth refresh is already in progress")}try{if(J=await this.load(),G=J?.accounts.find((W)=>W.id===$.id&&Q1(W)),this.assertNotTombstoned(G),this.assertNotShieldedMainRow(J,G,X),G&&!X.force&&!E1(G,J,this.now()))return U0(Z,G),G;if(!G)throw new a6($.id);z=G;let Q=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});R1.debug("fallback oauth refresh request start",{pid:process.pid,accountId:z.id,force:X.force===!0,expiresInMs:z.expires?z.expires-this.now():void 0});let Y=await Q({refreshToken:z.refresh,fetchImpl:this.fetchImpl,now:this.now});if(z.access=Y.access,z.refresh=Y.refresh,z.expires=Y.expires,z.lastRefreshedAt=Y.expires-Y.expiresIn*1000,z.lastRefreshError=void 0,U0(Z,z),await this.save(Z),!(await this.load())?.accounts.some((W)=>W.id===$.id))throw new a6($.id);return R1.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),z}finally{await B.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")}),G=(z)=>this.quotaManager?this.quotaManager.refreshFallback(X.id,z):J({accessToken:z,fetchImpl:this.fetchImpl,now:this.now});try{if(!X.access)throw Error(`Fallback account ${$.id} has no access token`);let z=await G(X.access);X.quota=z,X.lastQuotaRefreshError=void 0,U0(Z,X),await this.save(Z)}catch(z){throw i3($,z,this.now()),U0(Z,$),z}}}var u2="/backend-api/wham/rate-limit-reset-credits",EU=`https://chatgpt.com${u2}`,Cz=`${u2}/consume`,IU=`https://chatgpt.com${Cz}`;function Z0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as Sz}from"node:fs";import{rm as i2}from"node:fs/promises";import{dirname as Rz,join as a2}from"node:path";import{resolveClaustrumConnectionPath as Ez}from"@cortexkit/claustrum-client";function l2($,Z){if(!$)return;let X=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(X)||X<0||X>100)return;return{usedPercent:X,remainingPercent:100-X,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function d2($){if(!Z0($)||typeof $.minor!=="number"||!Number.isSafeInteger($.minor)||typeof $.exponent!=="number"||!Number.isInteger($.exponent))return;let Z=$.minor/10**$.exponent;return Number.isFinite(Z)?Z:void 0}function Pz($){let Z=d2($.total),X=d2($.remaining);if(Z===void 0||X===void 0||Z<0||X<0)return;let J=Z-X,G=$.spendable===!1,z=Z>0?J/Z*100:G?100:0;return{limit:Z,used:J,remaining:X,usedPercent:z,remainingPercent:100-z,reached:G,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...Z0($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function c2($,Z){let X=l2($.usage?.primary,Z.fetchedAt);if(!X||!Number.isFinite(Z.fetchedAt))return;let J=l2($.usage?.secondary,Z.fetchedAt),G=Array.isArray($.spend)?$.spend.find((Q)=>Z0(Q)&&Q.id==="individual_limit"):void 0,z=Z0(G)?Pz(G):void 0,B=Z0($.savedResets)?$.savedResets.availableCount:void 0;return{primary:X,...J&&{secondary:J},...typeof B==="number"&&Number.isFinite(B)&&B>=0&&{resetCreditsAvailable:B},...z&&{spendControl:z},...!G&&{spendControlCleared:!0}}}var s2=["primary","secondary"];function X8($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function h$($){return typeof $==="number"&&Number.isFinite($)}function Tz($,Z){if(!X8(Z))return;let X=Z.usedPercent;if(!h$(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...h$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function Az($){let Z=$.spendControl;if(X8(Z)&&typeof Z.reached==="boolean"){let X=(J)=>h$(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 S0($,Z,X){if(!X8($)||!h$(Z))return;let J=[],G=[];for(let Y of s2){let H=Tz(Y,$[Y]);if(H)J.push(H);else if(X)G.push({label:Y})}let z=Az($),B=$.resetCreditsAvailable,Q=typeof B==="number"&&Number.isSafeInteger(B)&&B>=0?{resetCredits:{value:B,checkedAt:Z}}:void 0;if(J.length===0&&G.length===0&&!z&&!Q)return;return{checkedAt:Z,...J.length>0?{readings:J}:{},...G.length>0?{coverage:G}:{},...z?{budget:z}:{},...Q?{counters:Q}:{}}}function G$($){if(!Q0($))return;let Z=s($),X={};for(let J of s2){let G=Z.limits.find((B)=>B.label===J&&B.kind==="reading");if(!G||!h$(G.usedPercent))continue;let z={usedPercent:G.usedPercent,remainingPercent:100-G.usedPercent,checkedAt:G.checkedAt,...G.resetsAt!==void 0?{resetsAt:G.resetsAt}:{},...G.windowMinutes!==void 0?{windowMinutes:G.windowMinutes}:{}};X[J]=z}return X.primary||X.secondary?X:void 0}var e6="No ChatGPT login in the vault has the `openai-native` category, or the grant is missing. Check `ck auth status` for categories and `ck auth grant` for the grant.";var y0=a("vault"),Iz="openai-auth",n2={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},bz={opencode:"OpenCode",pi:"Pi"};function xz($){return T3(Iz,$)}function $Z($){return a2(Rz($),"openai-auth-vault")}function kz($,Z){return{...S3({stateDir:$,host:Z}),rosterPath:a2($,`${Z}-roster.json`)}}var ZZ=2000,r2={"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 o2($){return $.snapshot()===void 0?"vault-unreachable":"vault-empty"}function yz($){let Z=r1($);return Z?o1(Z):void 0}class J8{host;name;paths;#$;#Z;#z=new Map;#J=new Map;#W=new Map;#Q;#X;#B;#V;#Y=!1;#G=!1;#U=Promise.withResolvers();#H;#D="unknown";#K;constructor($){this.#$=$,this.host=$.host,this.name=xz($.host),this.paths=kz($.stateDir,$.host),this.#Z=new c6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:n2,connect:()=>this.#_(),isCustodyActive:()=>this.enrolled(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:yz,insula:{provider:"codex",normalize:c2},...$.now?{now:$.now}:{},onRoster:()=>{this.#X=void 0},onError:(Z)=>this.#j("vault roster refresh failed",Z),logger:y0})}#F(){return(this.#$.connectionFile??Ez)()}#L(){return{connectionFile:this.#F(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>y0.debug("vault transport error",{errorClass:$})}}#_(){return(this.#$.connectScoped?.()??T2(this.#L())).then(($)=>{return this.#Q=$.insula!==void 0,$})}#q($,Z,X){if(this.#W.get($)===Z)return;this.#W.set($,Z),y0.info("vault background quota source changed",{routeId:$,source:Z,reason:X})}#O(){return this.#$.connectEnrollment?.()??A3(this.#L())}#j($,Z){this.#X=c0(Z),y0.warn($,{host:this.host,error:this.#X})}#N(){return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=Sz($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#N(),Z=await E3(this.paths,this.name);if($===this.#N())return this.#D=Z,this.#K=$,Z;return"unreadable"}enrolled(){return this.#K!==this.#N()||this.#D!=="local"}start(){if(this.#Y||this.#G)return;this.#Y=!0;let $=async()=>{try{await this.authority(),await this.#M(),await this.#Z.refreshInsulaQuota()}catch(X){if(!this.#G)this.#j("vault roster refresh failed",X)}if(this.#G)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#H=setTimeout(()=>{this.#H=void 0,$()},Z),this.#H.unref?.()};$()}#M(){return this.#V??=this.#Z.refresh().finally(()=>{this.#V=void 0,this.#U.resolve()}),this.#V}firstRoster(){return this.#U.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let $=this.#V;if($)await $.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#V??this.#M()).catch((X)=>{this.#j("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let $=this.#V;if($)await $.catch(()=>{return});let Z=await this.#M();return this.#X=void 0,Z}catch($){return this.#j("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,credentialId:$.get(Z.id)?.credentialId,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($,(G)=>{return J=!0,Z(G.accessToken,G)},{site:X.site,...X.signal?{signal:X.signal}:{}})}catch(G){if(J)throw G;this.#j("vault refused to serve an account",G);return}}async authorize($,Z={}){try{return await this.#Z.authorize($,Z.signal)}catch(X){this.#j("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.#j("vault failure report failed",X)}await this.refresh()}recordSnapshot($,Z,X,J){let G=S0(Z,(this.#$.now??Date.now)(),X);if(!G)return Promise.resolve();return this.#Z.recordQuota($,G,J).then(()=>{},(z)=>this.#j("vault quota write failed",z))}pollQuota($,Z=!0){let X=this.#J.get($);if(X)return X;let J=this.#C($,Z).finally(()=>{this.#J.delete($)});return this.#J.set($,J),J}async#C($,Z){if(Z){await this.authority(),await this.#Z.refreshInsulaQuota();let z=(await L0(this.paths.rosterPath))?.rows.find((Q)=>Q.routeId===$),B=await this.#Z.cachedInsulaQuotaForRoute($);if(B!==void 0&&z?.accountIdentity){let Q=S0(B,B.primary.checkedAt,!0);if(!Q)return this.#q($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota($,z.accountIdentity,Q))return this.#q($,"insula",null),{ok:!0};return this.#q($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}this.#q($,"fallback",this.#Q===!1?"insula-not-configured":"no-insula-reading")}let X,J=this.#$.fetchImpl?.()??globalThis.fetch,G=await this.send($,async(z,B)=>{try{let Q=Z?void 0:await this.#Z.cachedInsulaQuota(B);if(Q!==void 0){let H=S0(Q,Q.primary.checkedAt,!0);if(!H)throw Error("unusable insula reading");return await this.#Z.recordQuota($,H,B),new Response(null,{status:200})}let Y=await Z$({accessToken:z,fetchImpl:J,now:this.#$.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:$,logger:y0});return await this.recordSnapshot($,Y,!0,B),X=void 0,new Response(null,{status:200})}catch(Q){X=c0(Q);let Y=Q?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw Q}},{site:"quota"}).catch((z)=>{X=c0(z);return});if(!G)return{ok:!1,error:X??"vault refused"};return G.ok?{ok:!0}:{ok:!1,error:X??`status ${G.status}`}}requestReading($){let Z=this.#z.get($);if(Z)return Z;let X=this.pollQuota($,!1).catch((J)=>{y0.warn("vault quota poll failed",{routeId:$,error:c0(J)})}).finally(()=>{this.#z.delete($)});return this.#z.set($,X),X}async pollStale($){let Z=(this.#$.now??Date.now)(),X=[];for(let J of this.routes()){let G=fz(J.quota);if(G!==void 0&&Z-G<$)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}async decline($){await this.#Z.decline($),y0.info("vault account declined",{routeId:$})}async accept($){await this.#Z.accept($),y0.info("vault account accepted",{routeId:$})}async status(){await this.authority();let $;try{$=await E$(this.paths,this.name)}catch(Z){this.#j("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.#O().catch((Z)=>{throw new B0("vault-unreachable",`Could not reach the Claustrum vault (${this.#F()}): ${c0(Z)}. Is the vault running?`)});try{let Z=new p6({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(y0.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??((z)=>new Promise((B)=>setTimeout(B,z))),X=$.pollIntervalMs??2000,J=Date.now()+($.timeoutMs??600000),G=await this.connectStep();while(G.state==="pending"||G.state==="busy"){if($.onPending?.(G),Date.now()>=J)return G;await Z(X),G=await this.connectStep()}return G})().finally(()=>{this.#B=void 0}),this.#B}async disconnect(){await i2(this.paths.tokenPath,{force:!0}),await i2(this.paths.statePath,{force:!0}),await this.authority(),this.#X=void 0,y0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())b3({mode:"custody",auth:$,provider:"openai"})}close(){if(this.#G=!0,this.#U.resolve(),this.#H)clearTimeout(this.#H);this.#H=void 0,this.#Z.close()}}function fz($){if(!$)return;let Z=s($).limits.map((X)=>X.checkedAt);return Z.length>0?Math.max(...Z):void 0}function XZ($,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 ${n2.category} --operation read`]}function t2($,Z,X){let J=`${bz[$]} (${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 G8($,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?`. ${e6}`:"."}`}}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:[...XZ($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
99
- `)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var e2=`${String.fromCharCode(27)}\\[[0-9;]*m`,Zj=new RegExp(e2,"g"),Xj=new RegExp(`^${e2}`);function z$($){return $.authority!=="local"}async function s0($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function X7($){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."),ZZ)})])}finally{clearTimeout(Z)}}function W1($){return $.email||$.label||$.routeId}var B8="Accounts are managed in the vault with ck. Disconnect to use local accounts.",v$="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";var R0="main";function JZ($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function G7($,Z,X){let J=new Map;if($8(Z))for(let G of $)J.set(G.id,m2(G$(G.quota),Z,G.id===R0?void 0:G.id,X));return J}var z7=5,Q8=5000;function B7($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function Q7($,Z=Q8){let X=$.rows.filter((B)=>B.kind==="oauth"&&$.killswitch.get(B.id)!==!1&&s(B.quota).limits.length===0);if(X.length===0)return;if(h0({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((B)=>$.killswitch.get(B.id)!==!1))return;let G=[];if(h0({rows:X,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(B)=>{let Q=$.requestPull(B);if(Q)G.push(Q.catch(()=>{}))}}),G.length===0)return;let z;return Promise.race([Promise.all(G),new Promise((B)=>{z=setTimeout(B,Z)})]).then(()=>{}).finally(()=>clearTimeout(z))}function Y8($){return $.reason==="exhausted"||$.reason==="budget-spent"}function Y7($,Z,X){if($===void 0)return{reason:"no-credential"};if(X.get($)===!1)return{reason:"killswitch"};let J=Z.excluded.find((z)=>z.id===$);if(J?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:J.until};if(J)return{reason:"no-credential"};let G=Z.refused.find((z)=>z.id===$);if(G&&"resetAtMs"in G)return{reason:"quota-exhausted",resetAtMs:G.resetAtMs};if(G)return{reason:"quota-unknown"};return{reason:"no-credential"}}function J7($,Z,X){if(Z.refused.find((G)=>!Y8(G)&&X.get(G.id)!==!1))return{reason:"quota-unknown"};return Y7($[0],Z,X)}function H7($){let Z=$.replayable!==!1,X=$.mainId===void 0?R0:$.mainId??"",J=Z?$.placement:"main-first",G=LZ({rows:$.rows,placement:J,formerMainId:X,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),z=f1($.rows.map((Y)=>Y.id),J,X),B=new Set(G.admission.refused.filter((Y)=>Y8(Y)&&$.killswitch.get(Y.id)!==!1).map((Y)=>Y.id)),Q=z.filter((Y)=>B.has(Y));if(!Z){let Y=z.includes(X),H=Y?X:G.order[0]??Q[0];if(H!==void 0&&G.order.includes(H))return{kind:"send",order:[H],lastPath:!1};if(H!==void 0&&B.has(H))return{kind:"send",order:[H],lastPath:!0};return{kind:"block",block:Y?Y7(X,G.admission,$.killswitch):J7(z,G.admission,$.killswitch)}}if(G.order.length>0)return{kind:"send",order:G.order,lastPath:!1};if(Q.length>0)return{kind:"send",order:Q,lastPath:!0};return{kind:"block",block:J7(z,G.admission,$.killswitch)}}function H8($){let Z=h0({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),X=new Map;for(let J of $.rows)X.set(J.id,s(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 W7($,Z,X){let J=X.exclude,G=J?$.rows.filter((B)=>!J.has(B.id)):$.rows,z=new Map;for(let B of G){let Q=Z.resetCredits(B.id);if(Q!==void 0)z.set(B.id,Q)}return SZ({rows:G,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...X.pendingBytes?{pendingBytes:X.pendingBytes}:{},rowReservePercent:(B)=>Z.reservePercent(B.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:z,...X.pin===void 0?{}:{pin:{accountId:X.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function V7($,Z,X,J){let G=W7($,Z,{exclude:X,pendingBytes:J});if(G.outcome!=="dispatch"||G.source==="pin")return;return{accountId:G.accountId,source:G.source,...G.quotaCheckedAt===void 0?{}:{quotaCheckedAt:G.quotaCheckedAt}}}function U7($,Z,X){let J=$.killswitch.get(X)===!1,G=W7($,Z,{pin:X});if(G.outcome==="dispatch"){if(G.pin.action==="assign")return{kind:"move",reason:J?"killswitch":"exhausted"};return G.accountId===X?{kind:"serve"}:{kind:"detour"}}let z=G.admission.refused.find((B)=>B.id===X);if(!J&&z&&Y8(z))return{kind:"last-path"};return{kind:"none"}}function j7($,Z,X,J){let G=$.killswitch.get(X);return AZ({quota:Z.projections.get(X),now:$.now,...J===void 0?{}:{status:J},...G===void 0?{}:{killswitchPasses:G}})}function D7($){return Z0($)?{...$}:{}}function GZ($,Z,X,J){let G=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,...G,run:async({values:z,invocation:B})=>{let Q=await $.apply({command:$.command,sectionId:Z,...J?{itemId:J}:{},actionId:X.id,values:z,confirmed:!0},B);return{ok:Q.ok,text:Q.text,...Q.code?{code:Q.code}:{}}}}}function W8($,Z){return new Proxy($,{get(X,J){if(J==="read")return async()=>{let z=await X.read();if(z.status!=="ready")return z;let B={...z,rows:z.rows.map((H)=>({...H,label:H.label??H.id}))};if(!Z)return B;let Q=await s0(Z);if(!z$(Q))return B;let Y=[...Q.status.accounts.map((H)=>({id:H.routeId,label:W1(H),type:"oauth",enabled:H.enabled,identity:H.accountIdentity,quota:H.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...z,rows:Y}};if(J==="readSettings")return async()=>{let z=await X.readSettings();if(z.status==="error"||!Z)return z;let B=await s0(Z),Q=D7(z.settings.killswitch);if(!z$(B)||!z.settings.killswitch)return z;let Y=D7(Q.accounts);for(let H of B.status.accounts)Y[H.routeId]=H1({version:1,accounts:[],...z.settings},H.routeId);return{...z,settings:{...z.settings,killswitch:{...Q,accounts:Y}}}};let G=Reflect.get(X,J);return typeof G==="function"?G.bind(X):G}})}function V8($,Z,X={}){let J=_1($),G=(H)=>_1({command:$.command,title:$.title,store:W8($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:{...$.routing,formerMainId:H??""},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),z=async(H,W)=>{let V=await s0(Z),j=z$(V),D=JZ(V.status.accounts.map((A)=>({id:A.routeId,credentialId:A.credentialId}))),U=j?G(D):J,K=(await U.open(W)).menu.sections.find((A)=>A.id===H);if(!K)throw new B0("unavailable","The account menu is unavailable.");if(!j)return{lines:K.lines,items:K.items.map((A)=>({...A,actions:A.actions.map((x)=>GZ(U,H,x,A.id))})),actions:K.actions.map((A)=>GZ(U,H,A))};let M=new Map(V.status.accounts.map((A)=>[A.routeId,A])),P=($.now??Date.now)(),E=(A)=>({id:"check",label:A?"Check this account":"Check now",group:"Actions",run:async()=>{let w=[...(await s0(Z)).routes].filter((y)=>!A||y===A);if(A&&w.length===0)throw new B0("unavailable","This vault account cannot be checked right now.");for(let y of w){let f=await Z.pollQuota(y);if(!f.ok)throw new B0("quota-check-failed",`${y}: ${f.error??"vault unavailable"}`)}return`Checked quota for ${w.length} account${w.length===1?"":"s"}.`}});if(H==="quota"){let A=(x,w)=>C0(s(x.quota,$.quota?.scope),{now:P,form:w});return{lines:V.status.accounts.filter((x)=>!V.routes.has(x.routeId)).map((x)=>`${W1(x)} (${x.enabled?x.state:"disabled"}): ${A(x,"compact")}`),items:V.status.accounts.filter((x)=>V.routes.has(x.routeId)).map((x)=>({id:x.routeId,label:W1(x),group:"Accounts",status:A(x,"compact"),detail:A(x,"full"),actions:[E(x.routeId)]})),actions:V.routes.size>0?[E()]:[]}}let F=K.items.map((A)=>{let x=M.get(A.id),w=x&&H==="accounts"?`Vault · ${x.credentialType==="oauth"?"login":"API key"} · ${x.state} · ${x.enabled?"enabled":"declined"}`:A.detail;return{id:A.id,label:A.label,detail:w,group:A.group,status:x&&H==="accounts"?x.enabled?x.state:"disabled":A.status,...A.facts?{facts:A.facts}:{},actions:x&&H!=="limits"?[]:A.actions.map((y)=>GZ(U,H,y,A.id))}}),q=K.actions.filter((A)=>H==="limits"||H==="routing"&&A.id==="mode").map((A)=>GZ(U,H,A)),L=K.actions.find((A)=>A.id==="mode")?.knobs.find((A)=>A.id==="mode"),S=H==="routing"&&D===null&&L?.kind==="choice"&&(L.value==="main-first"||L.value==="fallback-first");return{lines:H==="accounts"?[`${V.status.accounts.length} vault account${V.status.accounts.length===1?"":"s"}`,`${V.routes.size} can route`,B8]:[...K.lines,...S?["No default vault account, so this mode orders like Ordered"]:[]],items:F,actions:q}},B=_1({...$,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(H)=>z("accounts",H)},quota:{title:"Quota",build:(H)=>z("quota",H)},routing:{title:"Routing",build:(H)=>z("routing",H)},limits:{title:"Limits",build:(H)=>z("limits",H)}},extras:$.extras?.map((H)=>H.id!=="reset"?H:{...H,build:async(W)=>{let V=await s0(Z);if(z$(V))return{lines:[B8]};return H.build(W)}})}),Q=async()=>{if(!z$(await s0(Z)))return{menu:J,error:void 0};let H=X.refresh===!1?void 0:await X7(Z);return{menu:B,error:H}},Y=async(H,W)=>{let V=await H.menu.open(W);if(H.error)V.menu.sections.find((D)=>D.id==="vault")?.lines.push(`Last error: ${H.error}`);return V};return{command:$.command,open:async(H)=>Y(await Q(),H),apply:async(H,W)=>{let V=await Q(),{menu:j}=V;if(j===B&&(H.sectionId==="accounts"||H.sectionId==="routing"&&H.actionId==="order"||H.sectionId==="reset"||H.sectionId==="quota"&&(await s0(Z)).routes.size===0||H.sectionId==="limits"&&H.itemId!==void 0&&!(await s0(Z)).status.accounts.some((D)=>D.routeId===H.itemId)))return{...await Y(V,W),ok:!1,code:"vault-local-action",text:v$};if(X.refuseApply)return{...await Y(V,W),ok:!1,...X.refuseApply};return j.apply(H,W)}}}var V1="openai",K8="OpenAI accounts",I1="main",q7="that account is already your main account, so it was not added again",m$=a("commands"),N7=new Set(["__proto__","constructor","prototype"]);function M7($,Z){let X={version:1,accounts:[],killswitch:$},J=Z0($.accounts)?Object.keys($.accounts):[],G={};for(let Q of new Set([I1,...Z,...J])){if(N7.has(Q))continue;let Y=H1(X,Q===I1?void 0:Q);G[Q]={primary:Y.primary,secondary:Y.secondary}}let z=H1(X,void 0),B={...$};return delete B.main,B.accounts=G,B.defaults={primary:z.primary,secondary:z.secondary},B.schema=J$,B}function F7($,Z){let X=Z0($.accounts)?{...$.accounts}:{};for(let G of new Set([I1,...Z])){if(N7.has(G)||Object.hasOwn(X,G))continue;X[G]={primary:Y1.primary,secondary:Y1.secondary}}let J=Z0($.defaults)?$.defaults:{primary:Y1.primary,secondary:Y1.secondary};return{...$,accounts:X,defaults:J,schema:J$}}function U8($,Z){let X=!1;if(Z0($.cachekeep))$.cacheKeep={...$.cachekeep,...Z0($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,X=!0;let J=$.killswitch;if(Z0(J)&&J.schema!==J$)$.killswitch=M7(J,Z),X=!0;return X}async function K7($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((X)=>X.id):[]}function L7($){let Z=async()=>{let J=await $.readSettings();if(J.status==="error")return J;let G=structuredClone(J.settings);return U8(G,await K7($)),{...J,settings:G}},X=async(J,G)=>{let z=await K7($);return $.updateSettings(async(B)=>{U8(B,z);let Q=await J(B)??B;if(Z0(Q.killswitch)&&Q.killswitch.schema!==J$)Q.killswitch=F7(Q.killswitch,z);return Q},G)};return new Proxy($,{get(J,G){if(G==="readSettings")return Z;if(G==="updateSettings")return X;let z=Reflect.get(J,G,J);return typeof z==="function"?z.bind(J):z}})}function _7($,Z){let X=(Y,H)=>Z.rowLocks?Z.rowLocks(Y):H,J=(Y,H)=>{let W=X(Y,H?.extraLocks);return{...H??{},...W?{extraLocks:W}:{}}},G=(Y,H,W,V)=>$.replace(Y,H,W,J(Y,V)),Q={add:async(Y,H)=>{let W=await $.read(),j=(W.status==="ready"?W.rows:[]).filter((K)=>K.type==="oauth"&&!K.invalid),D=Y.identity?j.find((K)=>K.identity===Y.identity):void 0;if(D?.id===I1)throw new B0("main-account",q7);let U=D??j.find((K)=>K.id===Y.id&&K.id!==I1);if(!U||Y.credential.type!=="oauth")return $.add(Y,H);let N=await G(U.id,Y.credential,Y.identity!==void 0?{identity:Y.identity}:{},H?.extraLocks?{extraLocks:H.extraLocks}:void 0);return m$.info("account signed in again",{id:U.id}),{id:N.id,outcome:"rotated",credential:N.credential,credentialEpoch:N.credentialEpoch}},replace:G,enable:(Y,H)=>$.enable(Y,J(Y,H)),disable:(Y,H,W)=>$.disable(Y,H,J(Y,W)),remove:(Y,H)=>$.remove(Y,J(Y,H))};return new Proxy($,{get(Y,H){if(Object.hasOwn(Q,H))return Q[H];let W=Reflect.get(Y,H,Y);return typeof W==="function"?W.bind(Y):W}})}var O7="migration";function j8($){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:V1,title:K8,sections:[{id:O7,slot:"extra",title:"Accounts are moving",lines:Z,items:$.map((J,G)=>({id:`blocker-${G}`,label:J.pid==="unknown"?"processes that could not be read":`pid ${J.pid}`,detail:`version ${J.version}`,actions:[]})),actions:[]}]};return D8(X)}var cz=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function sz($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(cz.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function zZ($,Z,X){if(Array.isArray($))return $.map((G,z)=>zZ(G,`${Z}[${z}]`,X));if(!Z0($))return $;let J={};for(let[G,z]of Object.entries($)){if(sz(G)){X.push(`${Z}.${G}`);continue}J[G]=zZ(z,`${Z}.${G}`,X)}return J}function D8($){let Z=[],X=zZ($,"menu",Z);if(Z.length>0)m$.warn("credential-shaped field stripped before RPC",{fields:Z});return X}function C7($){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 P7($,Z){return{label:"Add account",knobs:[{kind:"text",id:"label",label:"Label (optional)"},{kind:"toggle",id:"headless",label:"Sign in with a device code (no browser on this machine)",value:!1}],run:async(X)=>{let J=typeof X.label==="string"&&X.label.trim().length>0?X.label.trim():void 0,G=X.headless===!0,z=await $.begin({...J!==void 0?{label:J}:{},headless:G}),B=G?`Open this verification URL:
96
+ </html>`,x6=[],T$,d0=new Map;function g2($,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(A$,Z)})}function w2($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function O1(){return d0.size}function T1($){if(d0.delete($),O1()===0)C1()}async function pJ(){let $=`http://localhost:${A$}/auth/callback`;if(x6.length>0)return{port:A$,redirectUri:$};if(T$)return T$;T$=(async()=>{let Z=(G,Q)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${A$}`);if(B.pathname==="/auth/callback"){let Y=B.searchParams.get("code"),H=B.searchParams.get("state"),V=B.searchParams.get("error"),W=B.searchParams.get("error_description");if(V){let D=W||V;if(H){let U=d0.get(H);if(U)U.reject(Error(D)),T1(H);else if(O1()===0)C1()}else if(O1()===0)C1();Q.writeHead(200,{"Content-Type":"text/html"}),Q.end(b6(D));return}if(!H){if(O1()===0)C1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(b6("Missing state parameter"));return}if(!Y){if(O1()===0)C1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(b6("Missing authorization code"));return}let j=d0.get(H);if(!j){if(O1()===0)C1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(b6("Unknown state — authorization may have expired"));return}T1(H),vJ(Y,$,j.pkce).then((D)=>j.resolve(D)).catch((D)=>j.reject(D)),Q.writeHead(200,{"Content-Type":"text/html"}),Q.end(wJ);return}if(B.pathname==="/cancel"){let Y=B.searchParams.get("state"),H=Y?[Y]:[...d0.keys()];Q.writeHead(200),Q.end("Login cancelled");for(let V of H){let W=d0.get(V);if(!W)continue;W.reject(Error("Login cancelled")),T1(V)}if(O1()===0)C1();return}Q.writeHead(404),Q.end("Not found")},X=f2(Z);await g2(X,"127.0.0.1");let J=[X],z=f2(Z);try{await g2(z,"::1"),J.push(z)}catch(G){let Q=G.code;if(Q!=="EADDRNOTAVAIL"&&Q!=="EAFNOSUPPORT")throw w2(X),G}return x6=J,{port:A$,redirectUri:$}})();try{return await T$}finally{T$=void 0}}function C1(){let $=x6;x6=[];for(let Z of $)w2(Z)}function uJ($,Z,X=300000,J){return new Promise((z,G)=>{if(J?.aborted){T1(Z),G(Error("Login cancelled"));return}let Q=setTimeout(()=>{if(d0.get(Z))T1(Z),G(Error("OAuth callback timeout — authorization took too long"))},X),B=()=>{if(clearTimeout(Q),d0.get(Z))T1(Z),G(Error("Login cancelled"))};if(J)J.addEventListener("abort",B);d0.set(Z,{pkce:$,state:Z,resolve:(Y)=>{if(clearTimeout(Q),J)J.removeEventListener("abort",B);z(Y)},reject:(Y)=>{if(clearTimeout(Q),J)J.removeEventListener("abort",B);G(Y)}})})}async function lJ($){let Z=await fetch(`${P1}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":h2($)},body:JSON.stringify({client_id:k6})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${P1}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function dJ($,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 B=await fetch(`${P1}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":h2(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let V=await B.json(),W=await fetch(`${P1}/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:`${P1}/deviceauth/callback`,client_id:k6,code_verifier:V.code_verifier}).toString()});if(!W.ok)throw Error(`Token exchange failed: ${W.status}`);return await W.json()}if(B.status!==403&&B.status!==404)throw Error(`Device authorization failed: ${B.status}`);let Y=G-(Date.now()-Q);if(Y<=0)throw Error("Device authorization expired");let H=Math.min(J+xJ,Y);try{await bJ(H,void 0,{signal:X})}catch(V){if(V instanceof Error&&V.name==="AbortError")throw Error("Device authorization cancelled");throw V}}}async function p2($){let{label:Z,headless:X=!1,signal:J,version:z}=$;if(K3(Z),X){let{deviceData:V,url:W,instructions:j}=await lJ(z),D=(async()=>{let U=await dJ(V,z,J),N=Date.now(),K=S$(U);return{id:K3(Z||K||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:U.access_token,refresh:U.refresh_token,expires:N+(U.expires_in??3600)*1000,enabled:!0,addedAt:N,lastUsed:N,lastRefreshedAt:N,accountId:K}})();return{url:W,instructions:j,completion:D}}let{redirectUri:G}=await pJ(),Q=await fJ(),B=m2(crypto.getRandomValues(new Uint8Array(32)).buffer),Y=hJ(G,Q,B),H=(async()=>{try{if(J?.aborted)throw Error("Login cancelled");let V=await uJ(Q,B,void 0,J),W=Date.now(),j=S$(V);return{id:K3(Z||j||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:W+(V.expires_in??3600)*1000,enabled:!0,addedAt:W,lastUsed:W,lastRefreshedAt:W,accountId:j}}finally{T1(B)}})();return{url:Y,instructions:"Complete authorization in your browser. This window will close automatically.",completion:H}}import{basename as cJ,dirname as sJ,join as iJ}from"node:path";var y6="openai-auth.json",u2="openai-auth-state.json";function q3($){return cJ($)===y6?iJ(sJ($),u2):`${$}.state.json`}function f6($){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 N3($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function l2($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function d2($,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=N3($.get(`${z}-window-minutes`)),Q=f6($.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 i2=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function a2($,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 n2($){if(i2.some((z)=>a2($,z)==="invalid"))return{};let Z={},X=d2($,"x-codex-primary-used-percent");if(X)Z.primary=X;let J=d2($,"x-codex-secondary-used-percent");if(J)Z.secondary=J;return Z}function r2($){let Z=i2.map((X)=>a2($,X));return Z.includes("valid")&&!Z.includes("invalid")}function c2($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=N3($.window_minutes),X=f6($.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 o2($){let Z={},X=c2($.rate_limits?.primary);if(X)Z.primary=X;let J=c2($.rate_limits?.secondary);if(J)Z.secondary=J;return Z}function t1($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function s2($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=N3($.limit_window_seconds),X=f6($.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 t2($){let Z={},X=s2($.rate_limit?.primary_window);if(X)Z.primary=X;let J=s2($.rate_limit?.secondary_window);if(J)Z.secondary=J;let z=l2($.rate_limit_reset_credits?.available_count);if(z!==void 0)Z.resetCreditsAvailable=z;let G=l2($.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 Y=t1(Q.limit),H=t1(Q.used),V=t1(Q.remaining),W=t1(Q.used_percent),j=t1(Q.remaining_percent);if(Y!==void 0&&H!==void 0&&V!==void 0&&W!==void 0&&j!==void 0)Z.spendControl={limit:Y,used:H,remaining:V,usedPercent:W,remainingPercent:j,resetsAt:f6(Q.reset_at),unit:Q.unit,source:Q.source,reached:$.spend_control.reached}}let B=$.credits;if(B&&typeof B.has_credits==="boolean"&&typeof B.unlimited==="boolean"&&typeof B.overage_limit_reached==="boolean"){let Y=t1(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...Y!==void 0?{balance:Y}:{}}}return Z}import{ClaustrumClient as Az}from"@cortexkit/claustrum-client";import{resolve as e2}from"node:path";import{storeIdentity as aJ}from"@cortexkit/claustrum-client";import{SubcClient as nJ}from"@cortexkit/subc-client";function $4($){let Z=$.identity??aJ($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let X,J=!1,z,G=new Promise((B,Y)=>{z=setTimeout(()=>Y(Error("insula usage timeout")),3000),z.unref?.()}),Q=(async()=>{if(X=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await nJ.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),J)throw X.close(),Error("insula usage timeout");let B=await X.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await X.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([Q,G])}finally{J=!0,clearTimeout(z),X?.close()}}}}var L3=60000,rJ=4*L3,M3=new Map,g6=new Map;function F3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class Z4{transport;key;#$=[];#Z;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Z)return this.#Z;for(let[X,J]of g6)if($-J>=L3)g6.delete(X);let Z=g6.get(this.key);if(Z!==void 0&&$-Z<L3)return Promise.resolve();return g6.set(this.key,$),this.#Z=(async()=>{try{let X=await this.transport.getUsage();if(!F3(X)||!Array.isArray(X.result)||X.error!==void 0)throw Error("unavailable insula usage");this.#$=X.result.filter((J)=>F3(J)&&typeof J.provider==="string")}catch{this.#$=[]}})().finally(()=>{this.#Z=void 0}),this.#Z}current($,Z,X){for(let J of this.#$){if(J.provider!==$||typeof J.account!=="string"||J.account.trim()!==Z)continue;if(J.stale!==void 0||J.errorClass!==void 0||!F3(J.usage))continue;let z=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!Number.isFinite(z)||X-z>=rJ)continue;return{entry:J,context:{fetchedAt:z,...typeof J.source==="string"&&{source:J.source}}}}return}}function X4($,Z){let X=JSON.stringify([e2($.connectionFile),e2(Z)]),J=M3.get(X);if(!J)J={source:new Z4($,X),refs:0},M3.set(X,J);J.refs++;let z=!1;return{source:J.source,release(){if(z)return;if(z=!0,--J.refs===0)M3.delete(X)}}}import{ClaustrumCredentialError as JU}from"@cortexkit/claustrum-client";function _3($){let Z=new AbortController,X=[],J=!1,z=()=>{if(J)return;J=!0;for(let{source:B,listener:Y}of X)B.removeEventListener("abort",Y);X.length=0},G=(B)=>{if(J||Z.signal.aborted)return;Z.abort(B),z()},Q=$.find((B)=>B.aborted);if(Q)return Z.abort(Q.reason),{signal:Z.signal,dispose:z};for(let B of $){if(Z.signal.aborted)break;let Y=()=>G(B.reason);if(X.push({source:B,listener:Y}),B.addEventListener("abort",Y,{once:!0}),B.aborted)G(B.reason)}return{signal:Z.signal,dispose:z}}import{ClaustrumCredentialError as Vz}from"@cortexkit/claustrum-client";import{createHash as oJ,randomBytes as tJ,randomUUID as eJ}from"node:crypto";import{constants as J4}from"node:fs";import{chmod as $z,mkdir as Zz,open as Y4,readFile as O3,realpath as Xz,rename as Jz,stat as H4,unlink as W4}from"node:fs/promises";import{basename as V4,dirname as J1,extname as z4,isAbsolute as G4,join as P3,resolve as zz}from"node:path";import{ClaustrumCredentialError as Gz,ClaustrumClient as Qz,writeEnrollmentTokenFile as Bz}from"@cortexkit/claustrum-client";class R extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var Yz=1,v6=16384,U4=30000,T3=/^[0-9a-f]{64}$/,j4=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),D4=new Set(["pending_queue_full"]);function C3($){if(!($ instanceof Gz))return;if(j4.has($.code))return{code:$.code,disposition:"terminal"};if(D4.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function A3($,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 S3($){return Qz.connect($)}function K4($){let Z=z4($)||".json",X=V4($,z4($));return{statePath:P3(J1($),`${X}-state${Z}`),tokenPath:$}}function R3($){let Z=$.override?.trim();if(Z&&!G4(Z)&&!$.cwd)throw new R("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?G4(Z)?Z:zz($.cwd,Z):P3($.stateDir,`${$.host}-enrollment.json`);return K4(X)}function q4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function h6($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function N4($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function R$(){return new R("invalid-state","invalid Claustrum enrollment state")}function w6($){if(!q4($)||$.version!==Yz||typeof $.proposedName!=="string"||$.proposedName.length===0)throw R$();if($.phase==="pending"){if(!T3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!h6($.createdAt)||!h6($.updatedAt))throw R$();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)||!N4($.tokenGeneration)||!h6($.updatedAt))throw R$();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"||!h6($.updatedAt))throw R$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw R$()}function E3($){if(!q4($)||!T3.test(String($.token??""))||!N4($.token_generation))throw new R("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function Hz($){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 Q4($){try{return JSON.parse($)}catch{throw new R("invalid-state","Claustrum enrollment file is not valid JSON")}}async function z1($){if(I)try{await K0(J1($));let X=await M0($,!0);if(Buffer.byteLength(X)>v6)throw new R("unsafe-file","Claustrum enrollment file is too large");return Q4(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await Y4($,J4.O_RDONLY|J4.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new R("unsafe-file","Claustrum enrollment file could not be opened safely")}try{Hz(await Z.stat());let X=Buffer.alloc(v6+1),{bytesRead:J}=await Z.read(X,0,X.byteLength,0);if(J>v6)throw new R("unsafe-file","Claustrum enrollment file is too large");return Q4(X.subarray(0,J).toString("utf8"))}finally{await Z.close()}}function B4($,Z){let X=[];for(let J of $.split(`
97
+ `)){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 Wz($,Z,X){try{let[J,z]=await Promise.all([O3(X.passwdPath??"/etc/passwd","utf8"),O3(X.groupPath??"/etc/group","utf8")]),G=B4(J,7),Q=B4(z,4);if(!G||!Q)return!1;let B=G.filter((W)=>Number(W[2])===$),Y=Q.filter((W)=>Number(W[2])===Z);if(B.length!==1||Y.length!==1)return!1;let H=B[0]?.[0],V=Y[0]?.[3]??"";return(V===""||V.split(",").every((W)=>W===H))&&!G.some((W)=>Number(W[2])!==$&&Number(W[3])===Z)}catch{return!1}}function M4($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>O3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function F4($,Z={}){if(!I){let X=process.geteuid?.();if(X===void 0)return;let J=process.getegid?.(),z;try{z=await Xz($)}catch{return}let G;for(;;){let Q=await H4(z).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=J!==void 0&&await Wz(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 B=J1(z);if(B===z)return;z=B}}try{await v0($,M4(Z))}catch(X){if(!(X instanceof d))throw X;throw new R("unsafe-file",`Claustrum enrollment parent refused: ${X.path} (${X.reason??X.code}). Use a folder that other users cannot write or replace.`)}}async function m6($,Z={}){if(I){await K0($,!1,M4(Z));return}await Zz($,{recursive:!0,mode:448});let X=await H4($),J=process.geteuid?.();if(J!==void 0&&X.uid!==J)throw new R("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((X.mode&63)!==0)await $z($,448)}async function A1($,Z,X={}){let J=J1($);await m6(J,X),await F4(J,X);let z=`${JSON.stringify(Z)}
98
+ `;if(Buffer.byteLength(z)>v6)throw new R("invalid-state","Claustrum enrollment state is too large");if(I)return v1($,z);let G=P3(J,`.${V4($)}.${process.pid}.${eJ()}.tmp`),Q,B=!1;try{Q=await Y4(G,"wx",384),B=!0,await Q.writeFile(z,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await Jz(G,$),B=!1}finally{if(await Q?.close().catch(()=>{}),B)await W4(G).catch(()=>{})}}async function E$($,Z){let X=await z1($.tokenPath),J=X===void 0?void 0:E3(X),z=await z1($.statePath),G=z===void 0?void 0:w6(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 X1(G)}async function I3($,Z){let X;try{X=await E$($,Z)}catch(J){if(!(J instanceof R)||J.kind!=="invalid-state"&&J.kind!=="invalid-token")return"unreadable";try{let z=await z1($.statePath);if(z===void 0)return"unreadable";let G=w6(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 S1($){let Z=await z1($);if(Z===void 0)throw new R("not-enrolled","Claustrum enrollment is not configured");return E3(Z)}function X1($){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 L4(){return new R("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class p6{#$;#Z;#Q;#J;#V;#H;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#Q=$.proposedName,this.#J=$.now??Date.now,this.#V=$.mintSecret??(()=>tJ(32).toString("hex")),this.#H=$.writeTokenFile??Bz}async status(){return E$(this.#Z,this.#Q)}async resetTerminal(){return _4(this.#Z,this.#Q)}async#W($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#J()};return await A1(this.#Z.statePath,X,this.#X),X1(X)}async reconcile(){await m6(J1(this.#Z.statePath),this.#X);let $=await $0({name:"ceremony",path:this.#Z.statePath,ttlMs:U4,renew:!0});if(!$)return{state:"busy"};try{let Z=await z1(this.#Z.tokenPath),X=Z===void 0?void 0:E3(Z),J=await z1(this.#Z.statePath),z=J===void 0?void 0:w6(J);if(z&&z.proposedName!==this.#Q)throw L4();if(X){if(!z||z.phase==="pending"){let Q={version:1,phase:"approved",proposedName:z?.proposedName??this.#Q,tokenGeneration:X.token_generation,updatedAt:this.#J()};await A1(this.#Z.statePath,Q,this.#X),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.#J()};return await A1(this.#Z.statePath,Q,this.#X),X1(Q)}if(z&&z.phase!=="pending")return X1(z);if(!z){let Q=this.#J();if(z={version:1,phase:"pending",proposedName:this.#Q,requestSecret:this.#V(),createdAt:Q,updatedAt:Q},!T3.test(z.requestSecret))throw new R("invalid-state","invalid minted Claustrum enrollment secret");await A1(this.#Z.statePath,z,this.#X)}if(!z.requestId)try{let Q=oJ("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),B=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:Q});z={...z,requestId:B.requestId,updatedAt:this.#J()},await A1(this.#Z.statePath,z,this.#X)}catch(Q){let B=C3(Q);if(!B)throw Q;if(B.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:B.code};return this.#W(z,B.code)}let G=z.requestId;if(!G)return X1(z);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:z.requestSecret});if(Q.status==="pending")return X1(z);if(Q.status==="denied"){let Y={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#J()};return await A1(this.#Z.statePath,Y,this.#X),X1(Y)}await m6(J1(this.#Z.tokenPath),this.#X),await F4(J1(this.#Z.tokenPath),this.#X),await this.#H(this.#Z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let B={version:1,phase:"approved",proposedName:z.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#J()};return await A1(this.#Z.statePath,B,this.#X),X1(B)}catch(Q){let B=C3(Q);if(!B)throw Q;if(B.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:G,retryCode:B.code};return this.#W(z,B.code)}}finally{await $.release()}}}async function _4($,Z){await m6(J1($.statePath));let X=await $0({name:"ceremony",path:$.statePath,ttlMs:U4,renew:!0});if(!X)return"busy";try{if(await z1($.tokenPath)!==void 0)return"refused-approved";let J=await z1($.statePath);if(J===void 0)return"idle";let z=w6(J);if(z.proposedName!==Z)throw L4();if(z.phase==="pending")return"refused-pending";return await X.assertOwned(),await W4($.statePath),"reset"}finally{await X.release()}}var I$="claustrum-tombstone:v1:";function u6($){return`${I$}${$}`}function b3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function l6($){return typeof $==="string"&&$.startsWith(I$)}function O4($,Z){if(!b3($)||$.type!=="oauth")return!1;return $.refresh===u6(Z)}function C4($,Z){if(O4($,Z))return"placeholder";if(b3($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!l6($.refresh))return"login";if(b3($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function x3($){let Z=C4($.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 P4($,Z){return Z!==void 0&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function Uz($,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 T4=n("claustrum");function f3($,Z,X,J=T4){let z=P4(Z,X);return J.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:z,reason:Uz(Z,X)}),z}var y3=300000;function k3(){return new R("invalid-material","Claustrum returned invalid credential material")}function jz($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw k3()}if(!X||typeof X!=="object")throw k3();let J=X,z=J.access_token??J.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(I$))throw k3();return Z}function Dz($,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}function Kz($){let{grants:Z,grantTuples:X}=$;if(Z===void 0||X===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(X.map(({selectorKind:J,selector:z,operation:G})=>Object.freeze({selectorKind:J,selector:z,operation:G})))})}class d6{#$;#Z;#Q;#J;#V;#H;#X;#W=new WeakMap;#B=new WeakMap;#U=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>S1(Z);else throw new R("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#J=$.family,this.#V=$.parseIdentity,this.#H=$.requireAssertion??!1,this.#Q=$.now??Date.now,this.#X=$.logger??T4}#z($){if(this.#U)throw new R("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#G($){this.#z($);let Z=await this.#Z();if(this.#z($),!/^[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#Y($,Z){this.#z(Z);let X,J;try{let z=$();X=Z?await Promise.race([z,new Promise((G,Q)=>{let B=()=>Q(Z.reason);if(Z.addEventListener("abort",B,{once:!0}),J=()=>Z.removeEventListener("abort",B),Z.aborted)B()})]):await z}catch(z){if(this.#z(Z),z instanceof Vz)throw z;throw new R("unavailable","Claustrum scoped operation unavailable")}finally{J?.()}return this.#z(Z),X}async discover($){let Z=await this.#G($),X=await this.#Y(()=>this.#$.listScoped(Z),$),J=[],z=[],G=new Map;for(let Y of X.rows){let H=Dz(Y,this.#J);if(!H)continue;z.push({row:Y,type:H}),G.set(Y.id,(G.get(Y.id)??0)+1)}let Q=[];for(let{row:Y,type:H}of z){let V;if(!Y.id.trim())V="empty credential id";else if((G.get(Y.id)??0)>1)V="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())V="blank account identity";else if(!Y.state.trim())V="empty state";if(V){J.push({...Y.id.trim()&&{credentialId:Y.id},reason:V});continue}Q.push(Object.freeze({credentialId:Y.id,credentialType:H,...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.#X.warn("skipped malformed vault record",Y);let B=Kz(X);return{view:X.view,credentials:Object.freeze(Q),skipped:Object.freeze(J),...B&&{grantReach:B}}}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.#H&&z===void 0)throw new R("identity-unasserted","Claustrum dispatch requires a known account identity");let G=await this.#G(Z),Q=await this.#Y(()=>this.#$.getScoped({credentialId:X,enrollmentToken:G,...J==="oauth"&&{minTtlMs:y3}}),Z);if(Q.credentialId!==void 0&&Q.credentialId!==X)throw new R("identity-changed","Claustrum served credential identity changed");let B=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||B===null&&J==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#Q()<y3))throw new R("insufficient-validity","Claustrum served credential has insufficient validity");let Y=jz(Q.material),H=Q.accountId?.trim()?Q.accountId:void 0;if(this.#H&&(Q.credentialId===void 0||H===void 0))throw new R("identity-unasserted","Claustrum served credential did not assert its identity");let V=H===void 0?this.#V?.(Y):void 0,W=H??V;if(z!==void 0&&W!==void 0&&W!==z)throw new R("identity-changed","Claustrum served credential identity changed");let j=W??z,U=Object.freeze(Object.defineProperty({credentialId:X,credentialType:J,...j!==void 0&&{accountIdentity:j},accountIdentitySource:H!==void 0?"asserted":V!==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:B},"accessToken",{value:Y,enumerable:!1}));return this.#W.set(U,G),U}async reportFailure($,Z,X){if(Z!==401)return;this.#z();let J=this.#W.get($);if(!J)throw new R("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#B.get($);if(z)return z;let G=this.#Y(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:J,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#B.set($,G);try{await G,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(Q){throw this.#B.delete($),Q}}close(){if(this.#U)return;this.#U=!0,this.#$.close()}}import{createHash as qz}from"node:crypto";function A4($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function g3($,Z,X){return $.some((J)=>A4(J,Z,X))}function h3($,Z,X){let J={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==X),J]}function v3($,Z,X){return $.filter((J)=>!Z.some((z)=>A4(J,z,X)))}var R4="vault:";function Nz($){return qz("sha256").update($).digest("hex")}function Mz($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function Fz($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function G1($){return[$.credentialId,...$.aliases??[]]}function E4($,Z,X={}){let J=X.now??Date.now(),z=X.routePrefix??R4,G=X.reservedRouteIds??new Set,Q=$?.rows??[],B=[...$?.declined??[]],Y=Z.skipped.length===0,H=new Set(Z.credentials.map((F)=>F.credentialId)),V=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),W=Z.skipped.some((F)=>F.credentialId===void 0),j=(F)=>!H.has(F)&&(V.has(F)||W),D=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let q of G1(F))if(!D.has(q))D.set(q,F.accountIdentity)}let U=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:D.get(F.credentialId),claimed:!1},L=Fz(q),S=U.get(L)??[];S.push(q),U.set(L,S)}let N=new Set,K=new Set(G),M=[],P=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),E=[...U.values()].map((F)=>F.toSorted(P)).sort((F,q)=>F[0]&&q[0]?P(F[0],q[0]):0);for(let F of E){let q=F[0]?.identity,L=F.filter((v)=>v.credential.state==="active"),S=L.length?L:F,A=S.filter((v)=>v.claimed),x=A.length?A:S,w=new Set(F.map((v)=>v.credential.credentialId)),y=Q.find((v)=>!N.has(v)&&G1(v).some((g0)=>w.has(g0))&&(v.accountIdentity===void 0||v.accountIdentity===q)),f=x.find((v)=>v.credential.credentialId===y?.credentialId)??x[0];if(!f)continue;let h=f.credential,o=y??(q===void 0?void 0:Q.find((v)=>!N.has(v)&&v.accountIdentity===q));if(o)N.add(o);let c=o?.routeId;if(!c||G.has(c)){let v=`${z}${h.credentialId}${q===void 0?"":`~${Nz(q).slice(0,10)}`}`;c=v;for(let g0=2;K.has(c);g0++)c=`${v}~${g0}`}K.add(c);let r$=o?G1(o).filter(j):[],x1=[...new Set([...F.map((v)=>v.credential.credentialId),...r$])].filter((v)=>v!==h.credentialId).sort((v,g0)=>v.localeCompare(g0)),o$=X.mapAccount?.(h)??{};M.push({previousIndex:o?Q.indexOf(o):1/0,row:{routeId:c,credentialId:h.credentialId,credentialType:h.credentialType,...q!==void 0&&{accountIdentity:q},...x1.length&&{aliases:x1},state:h.state,label:o$.label?.trim()||Mz(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...x1].some((v)=>g3(B,v,q)),addedAt:o?.addedAt??J,...o?.quota!==void 0&&{quota:o.quota},...!f.claimed&&q!==void 0&&{unclaimed:!0}}})}return Q.forEach((F,q)=>{if(N.has(F)||!G1(F).some(j))return;if(K.has(F.routeId))return;let[L,...S]=G1(F).filter((w)=>!H.has(w));if(L===void 0)return;K.add(F.routeId);let{aliases:A,...x}=F;M.push({previousIndex:q,row:{...x,credentialId:L,...S.length&&{aliases:S},stale:!0}})}),M.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,complete:Y,...!Y&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:M.map((F)=>F.row),declined:B}}function m3($){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 b$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function e1($){return $===void 0||typeof $==="string"}function Lz($){let Z=b$($)?q1($.quota):void 0;if(!b$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!e1($.accountIdentity)||!e1($.email)||!e1($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((X)=>typeof X==="string"))||$.quota!==void 0&&Z===void 0||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return{...$,...Z===void 0?{}:{quota:Z}}}var _z=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function S4($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!b$(X)||!e1(X.credentialId)||typeof X.reason!=="string"||!_z.has(X.reason))return;Z.push(X)}return Z}function Oz($){if(!b$($)||$.version!==1||!e1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!S4($.rejected))throw new R("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let G=Lz(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(!b$(z)||typeof z.credentialId!=="string"||!e1(z.accountIdentity))throw new R("invalid-state","Claustrum roster file is not valid");X.push(z)}let J=S4($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...J&&{rejected:J},rows:Z,declined:X}}async function L0($){let Z;try{Z=await M0($,I)}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 Oz(X)}var Cz={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},Pz={name:"claustrum-roster",ttlMs:30000};async function $$($,Z,X={}){return pZ($,Cz,async(J)=>{let z=await L0($),{next:G,result:Q}=await Z(z,{assertOwned:()=>J.assertOwned()});if(G)await J.assertOwned(),await F0($,G,{beforeRename:async()=>{await X.beforePublish?.(),await J.assertOwned()}});return Q})}function w3($,Z){return $$($,(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=h3(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 p3($,Z){return $$($,(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:v3(X.declined,G1(J),J.accountIdentity),rows:X.rows.map((z)=>z===J?{...z,enabled:!0}:z)},result:void 0}})}function Tz($,Z){if(!G1($).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")&&G1($).length===1)return"bind";return"refuse"}function u3($,Z){return $$($,(X)=>{let J=X?.rows.find((B)=>B.routeId===Z.routeId),z=!X||!J?"refuse":Tz(J,Z);if(!X||!J||z==="refuse")return{result:!1};let G=E0(J.quota,Z.observation),Q=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...X,rows:X.rows.map((B)=>B===J?{...B,...Q,quota:G}:B)},result:!0}})}function l3($,Z){return $$($,(X)=>{let J=X?.rows.find((G)=>G.routeId===Z.routeId);if(!X||!J||J.accountIdentity===void 0||J.accountIdentity!==Z.accountIdentity)return{result:!1};let z=E0(J.quota,Z.observation);return{next:{...X,rows:X.rows.map((G)=>G===J?{...G,quota:z}:G)},result:!0}})}async function d3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let X=await $0({...Pz,path:$.path,renew:!0});if(!X){let J=await L0($.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 $$($.path,async(z)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await X.assertOwned();let G=typeof $.projection==="function"?$.projection():$.projection,Q=E4(z,J,G);return{...JSON.stringify(z)!==JSON.stringify(Q)&&{next:Q},result:Q}})}finally{await X.release()}}class c6{#$;#Z=new AbortController;#Q;#J;#V;#H;#X;#W;#B;#U=!1;#z;constructor($){this.#$=$,this.#Q=$.logger??n("claustrum")}#G($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}async#Y(){return await this.#$.isCustodyActive?.()??!0}#D($,Z){let X=_3([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((B)=>{if(G(),X.signal.aborted)z(X.signal.reason);else J(B)},(B)=>{G(),z(B)}),X.signal.aborted)Q()})}async#K(){if(this.#G(),this.#J)return this.#J;if(!this.#V)this.#V=this.#$.connect().then(($)=>{if(this.#Z.signal.aborted)$.close(),this.#G();if(this.#J=new d6({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Q}),this.#$.insula&&$.insula)this.#z=X4($.insula,this.#$.tokenPath);return this.#J}).finally(()=>{this.#V=void 0});return this.#D(this.#V)}snapshot(){return this.#X}grantReach(){let $=this.#W;return $&&this.#X?.view===$.view?$.reach:void 0}routingRows(){return m3(this.#X)}refresh(){if(this.#G(),this.#H)return this.#H;return this.#H=(async()=>{if(!await this.#Y()){this.#X=void 0,this.#W=void 0,this.#J?.close(),this.#J=void 0,this.#z?.release(),this.#z=void 0;return}let $=await this.#K(),Z,X=await d3({path:this.#$.rosterPath,custody:{discover:async(z)=>{return Z=await $.discover(z),Z}},isActive:()=>this.#Y(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#G();let J=X?.view!==this.#X?.view;if(this.#X=X,Z&&X?.view!==void 0)this.#W=Z.grantReach?{view:X.view,reach:Z.grantReach}:void 0;if(X&&J)this.#$.onRoster?.(X);return X})().finally(()=>{this.#H=void 0}),this.#H}start(){if(this.#U)return;this.#G(),this.#U=!0;let $=async()=>{try{await this.refresh(),await this.refreshInsulaQuota()}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.#B=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#B=void 0,$()},Z),this.#B.unref?.()};$()}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#Y())return;try{await S1(this.#$.tokenPath),await this.#K(),await this.#z?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#Y())return;try{return await S1(this.#$.tokenPath),this.#q($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#Y())return;try{await S1(this.#$.tokenPath);let X=(await L0(this.#$.rosterPath))?.rows.find((J)=>J.routeId===$);return this.#q(X?.accountIdentity)}catch{return}}#q($){if(!this.#$.insula||!$)return;let Z=this.#z?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#G(Z);let X=this.#X??await this.#D(this.refresh(),Z);if(!X||!await this.#Y())throw new R("not-active","Claustrum scoped custody is not active");let J=await L0(this.#$.rosterPath);this.#G(Z);let z=X.rows.find((Y)=>Y.routeId===$),G=J?.rows.find((Y)=>Y.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.#D(this.#K(),Z),B=_3([this.#Z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},B.signal)}finally{B.dispose()}}async reportFailure($,Z,X){if(this.#G(),!this.#J)throw new R("no-receipt","Claustrum dispatch receipt has no active owner");await this.#J.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(f3(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 w3(this.#$.rosterPath,$),this.#X=await L0(this.#$.rosterPath)}async accept($){this.#G(),await p3(this.#$.rosterPath,$),this.#X=await L0(this.#$.rosterPath)}async recordQuota($,Z,X){this.#G();let J=await u3(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.#X=await L0(this.#$.rosterPath);return J}async recordAccountQuota($,Z,X){this.#G();let J=await l3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:X});if(J)this.#X=await L0(this.#$.rosterPath);return J}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new R("closed","Claustrum consumer is closed")),this.#B)(this.#$.clearTimeoutImpl??clearTimeout)(this.#B);this.#B=void 0,this.#J?.close(),this.#z?.release(),this.#z=void 0,this.#X=void 0,this.#W=void 0}}async function I4($){let Z=await Az.connect($);return Object.assign(Z,{insula:$4($)})}var Sz=u6("openai");function b4($){return l6($)}function k0($){if(!$||$.corrupt===!0)return!1;return b4($.refresh)}class x$ 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 s6($){if(b4($))throw new x$}function c0($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var Rz=n("quota");var Ez="app_EMoamEEZ73f0CkXaXp7hrann",Iz="https://auth.openai.com";async function x4($){s6($.refreshToken);let Z=await $.fetchImpl(`${Iz}/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:Ez}).toString()});if(!Z.ok){let z=D3(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 bz="https://chatgpt.com/backend-api/wham/usage";async function Z$($){let Z=$.logger??Rz,X=$.accountKey??"unknown",J=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let z=await $.fetchImpl(bz,{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=D3(z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${z.status}`),{status:z.status,retryAfter:Q})}let G=t2(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:c0(z)}),z}}import{createHash as yz}from"node:crypto";var fz=globalThis.setTimeout,gz=5;function k$($){let Z=$?.quota?.checkIntervalMinutes??gz;return Math.max(1,Z)*60000}function hz($){return $?.quota?.enabled!==!1}function s3($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function vz($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function k4($,Z,X){if(!hz(Z))return X+k$(Z);let J=vz(Z),z=[];for(let G of["primary","secondary"]){let Q=$?.[G];if(!Q)continue;if(Q.remainingPercent>=J[G])continue;let B=Q.resetsAt?Date.parse(Q.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=X)return X+k$(Z);z.push(B)}if(!z.length)return X+k$(Z);return Math.min(...z)+60000}function mz($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function wz($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function _0($){return yz("sha256").update($).digest("hex").slice(0,16)}class Q1{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!==_0($))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($)!==_0(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return X}getAllFallbacks(){return this.fallbacks}setMain($,Z,X,J=!1){if(!J&&!y4(Z.quota))return;if(this.mainTokenFp=_0($),X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)this.clearRateLimited("main");if(X)this.mainQuotaAccountId=X;if(this.main=Z,c3(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&&!y4(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($,_0(X));else this.fallbackTokenFps.delete($);if(c3(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=_0($);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=Q1.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(k0(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=_0($);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=wz(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=mz($);if(!X)return;let J=Z?_0(Z):null;if(J&&X.tokenFingerprint&&X.tokenFingerprint!==J)return;let z={quota:X.quota,refreshAfter:k4(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&&n1(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=k$(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 n1(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==_0(Z))return!1}return n1(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,_0(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<Q1.API_CALL_GAP_MS)await new Promise((z)=>{let G=fz(z,Q1.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=_0($);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 $0({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=_0($),this.main={quota:z,refreshAfter:k4(z,this.storage,G),checkedAt:G},c3(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 $0({name:Q1.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+k$(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(Q1.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(Q1.isAuthError($))return;this.mainLastApiError=P$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(Q1.isAuthError(X))return;let J=_0(Z),z=this.fallbackErrorTokenFps.get($)===J?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,P$({error:X,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set($,J)}}function y4($){return Boolean($.primary||$.secondary)}function c3($){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 XG}from"node:fs/promises";var R1=n("refresh"),n3=n("accounts"),dz=1e4,cz=15000,i3=50;function B1($){return $.type==="oauth"&&$.corrupt!==!0}function sz($){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 a6 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var iz=[401,403,429],f4={primary:0,secondary:0},az=!1,Y1={primary:5,secondary:10};function k($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var nz=new Set(["__proto__","constructor","prototype"]);function e3($){return $.length>0&&!nz.has($)}function rz($){return $ instanceof a6||k($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function i6($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():uz(),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 g4($){if(!k($))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 oz($){if(!k($))return;let Z={};for(let z of["primary","secondary"]){let G=$[z];if(!k(G))continue;let Q=Number(G.usedPercent),B=Number(G.remainingPercent),Y=Number(G.checkedAt);if(!Number.isFinite(Q)||!Number.isFinite(B)||!Number.isFinite(Y))continue;let H=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[z]={usedPercent:Q,remainingPercent:B,checkedAt:Y,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(k(X)){let z=Number(X.limit),G=Number(X.used),Q=Number(X.remaining),B=Number(X.usedPercent),Y=Number(X.remainingPercent);if(Number.isFinite(z)&&Number.isFinite(G)&&Number.isFinite(Q)&&Number.isFinite(B)&&Number.isFinite(Y)&&typeof X.reached==="boolean")Z.spendControl={limit:z,used:G,remaining:Q,usedPercent:B,remainingPercent:Y,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(k(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 tz($){if(!k($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!sz(Z))return null;let J=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...i6($),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{...i6($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...i6($),type:"oauth",corrupt:!0}}return{...i6($),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:g4($.lastRefreshError),lastQuotaRefreshError:g4($.lastQuotaRefreshError),quota:oz($.quota)}}function ez($){if(!k($))return;let Z=Object.create(null);for(let[X,J]of Object.entries($)){if(!e3(X)||!k(J))continue;let z={};if(k(J.inFlight))z.inFlight={...J.inFlight};if(k(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,...k(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 h4=new Set;function $G($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(h4.has(Z))return;h4.add(Z),n3.warn("account load-dropped, preserved on disk",{droppedIds:$})}function ZG($){if(!k($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(tz).filter((J)=>J!=null);if(X.length<Z.length){let J=new Set;for(let Q of Z)if(k(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);$G(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:k($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:k($.refresh)?$.refresh:void 0,quota:k($.quota)?$.quota:void 0,reset:ez($.reset),dump:k($.dump)?$.dump:void 0,costZeroing:k($.costZeroing)?$.costZeroing:void 0,killswitch:k($.killswitch)?$.killswitch:void 0,logging:k($.logging)?$.logging:void 0,cachekeep:k($.cachekeep)?$.cachekeep:void 0,cacheKeep:k($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:X}}async function n6($){try{return{exists:!0,value:JSON.parse(await XG($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function r6($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function JG($){let Z;try{Z=(await n6($)).value}catch{return null}return jG(Z)}function zG($,Z){if(!k($))return $;let X=k(Z)?Z:{},J=k(X.main)?X.main:void 0,z=k(X.accounts)?X.accounts:{},G=k($.quota)?$.quota:{},Q=k($.refresh)?$.refresh:{},B=J??G,Y=J??Q,V=Q.mainRefreshLeaseId!==void 0?{id:Q.mainRefreshLeaseId,until:Q.mainRefreshLeaseUntil,tokenHash:Q.mainRefreshLeaseTokenHash}:{id:Y.refreshLeaseId,until:Y.refreshLeaseUntil,tokenHash:Y.refreshLeaseTokenHash},j=Array.isArray($.accounts)?$.accounts.map((D)=>{if(!k(D))return D;let U=typeof D.id==="string"&&k(z[D.id])?z[D.id]:{};return{...D,...U}}):void 0;return GG({...$,refresh:r6({...Q,mainLastRefreshError:Q.mainLastRefreshError??Y.lastRefreshError,mainRefreshLeaseId:V.id,mainRefreshLeaseUntil:V.until,mainRefreshLeaseTokenHash:V.tokenHash}),quota:r6({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:j})}async function $8($){let Z=await n6($.configPath);if(!Z.exists)return null;let X=await n6($.statePath);return ZG(zG(Z.value,X.value))}function GG($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function QG($){if($.type==="api")return r6({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return r6({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function o6($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function y$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function BG($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function YG($,Z){if(!BG($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var HG=300000;function v4($,Z){if($===void 0)return 0;return $>Z+HG?0:$}function WG($,Z,X){let J=Date.now(),z=v4(Z.lastRefreshedAt,J),G=v4(X.lastRefreshedAt,J),Q=Z.expires??0,B=X.expires??0,Y=G>z?X:z>G?Z:B>Q?X:Q>B?Z:YG(Z,X);y$($,Y,"access"),y$($,Y,"refresh"),y$($,Y,"expires"),y$($,Y,"lastRefreshedAt"),y$($,Y,"lastRefreshError")}function VG($,Z){if(!k($))return Z;let X=$,J=o6(X.quota),z=o6(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 WG(Q,X,Z),Q}async function UG($,Z=!1){let X=Date.now(),J=X+cz,z=0;while(Date.now()<=J){z++;let B=await $0({name:"save",ttlMs:dz,path:$,renew:Z});if(B)return B;let Y=J-Date.now();if(Y<=0)break;await lz(Math.min(i3+c4(i3),Y))}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 ${i3}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 jG($){if(!k($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let X of $.accounts){if(!k(X))continue;if(typeof X.id!=="string")continue;let J=X.id.trim();if(!J)continue;Z.add(J)}return Z}function DG($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:o6($.main.quota),J=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:o6(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 KG($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function r3($){if(Array.isArray($))return $.map(r3);if(!k($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,r3(X)]))}async function qG($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},J){let z=Z.statePath,G=await UG(z);try{let Q=(await n6(z)).value,B=k(Q)?{...Q,version:1}:{version:1};if(X.mainQuota)DG(B,$);if(X.mainRefresh)KG(B,$);if(X.accounts){let Y=X.accounts===!0?null:new Set(X.accounts),H=await JG(Z.configPath);B.accounts={...k(B.accounts)?B.accounts:{}};for(let V of $.accounts){if(Y&&!Y.has(V.id))continue;if(H&&!H.has(V.id))continue;B.accounts[V.id]=VG(B.accounts[V.id],QG(V))}if(Y){for(let V of Y)if(!$.accounts.some((W)=>W.id===V))delete B.accounts[V]}if(H){for(let V of Object.keys(B.accounts))if(!H.has(V))delete B.accounts[V]}}if(J&&!J())return;await F0(z,r3(B))}finally{await G.release()}}function l4($){return $?.fallbackOn?.length?$.fallbackOn:iz}function NG($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??f4.primary,secondary:Z.secondary??Z["1w"]??f4.secondary}}function o3($){return $?.quota?.enabled!==!1}function g$($){return $?.quota?.failClosedOnUnknownQuota??az}function t6($,Z,X=Date.now()){if(!o3(Z))return!0;if(!$)return!g$(Z);let J=NG(Z),z=g$(Z);for(let G of["primary","secondary"]){let Q=$[G];if(!Q)continue;if(s3(Q,X)){if(z)return!1;continue}if(Q.remainingPercent<J[G])return!1}return!0}function Z8($){return $?.killswitch?.enabled===!0}function m4($){return{primary:$?.primary??$?.["5h"]??Y1.primary,secondary:$?.secondary??$?.["1w"]??Y1.secondary}}function w4($){return typeof $==="number"&&Number.isFinite($)?$:0}function H1($,Z){if(!$?.killswitch)return Y1;if($.killswitch.schema===J$){let{accounts:X,defaults:J}=$.killswitch,z=Z??"main",G=k(X)&&Object.hasOwn(X,z)&&k(X[z])?X[z]:k(J)?J:void 0;return{primary:w4(G?.primary),secondary:w4(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return m4($.killswitch.accounts[Z]);return m4($.killswitch.main)}function d4($,Z,X,J=Date.now()){if(!Z8(Z))return!0;if(!$)return!g$(Z);let z=H1(Z,X),G=g$(Z);for(let Q of["primary","secondary"]){let B=$[Q];if(!B)continue;if(s3(B,J)){if(G)return!1;continue}if(B.remainingPercent<z[Q])return!1}return!0}function MG($){return $?.refresh?.enabled!==!1}function X8($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function c4($){return Math.floor(Math.random()*($+1))}function E1($,Z,X){return!$.access||!$.expires||$.expires-X<=X8(Z)}function FG($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function X$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class s4 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 U0($,Z){let X=$.accounts.findIndex((J)=>J.id===Z.id);if(X!==-1)$.accounts[X]=Z}function f$($){return $ instanceof Error?$.message:String($)}function t3($,Z,X){if(Z instanceof x$)return;$.lastRefreshError=I6({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function a3($,Z,X){if(Z instanceof x$)return;if($.lastQuotaRefreshError=P$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)t3($,Z,X)}function p4($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function LG($,Z){if(!$)return!1;return p4($.primary,Z)||p4($.secondary,Z)}function _G($,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 u4($,Z,X){return!_G($.quota,Z,X)}function OG($,Z,X,J){return j3(X)&&t6($.quota,Z,J)&&LG($.quota,J)}function CG($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var PG=60000,TG=60000,AG=600000;function SG($){return`fallback-oauth-refresh-${pz("sha256").update($).digest("base64url").slice(0,16)}`}var RG=1e4,EG=100;class IG{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($)s6($.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+CG(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return $8(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await qG($,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(()=>{})},PG+c4(TG)),"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||!B1(z))continue;if(X$(Z,z))continue;if(k0(z))continue;let G=!1,Q=z;try{if(E1(Q,Z,this.now())){let B=Q.lastRefreshError;if(B&&Z1(B,Q.refresh,this.now()))throw G=!0,Error(C$(B,this.now()));try{Q=await this.refreshAccount(Q,Z),J=!0}catch(Y){if(rz(Y))continue;G=!0;let H=Z.accounts.find((V)=>V.id===z.id&&B1(V));if(H&&!Z1(H.lastRefreshError,H.refresh,this.now()))t3(H,Y,this.now()),U0(Z,H),J=!0;throw Y}}if(this.seedFallbackQuota(Q,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(Q),Z))X.push(Q)}catch(B){let Y=FG(Q,this.now());if(G){if(!Y)continue}else if(!Y)continue;if(OG(Q,Z,B,this.now()))R1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:Q.id,error:f$(B)}),X.push(Q);else if(!g$(Z))X.push(Q)}}if(J){let z=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(z)).catch((G)=>{n3.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:f$(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){n3.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:f$(Z)})}}accountPassesQuotaPolicy($,Z){return t6($.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(!$||!MG($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!B1(X))continue;if(X$($,X))continue;if(k0(X))continue;if(!E1(X,$,this.now()))continue;if(Z1(X.lastRefreshError,X.refresh,this.now()))continue;try{R1.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){R1.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:f$(J)}),t3(X,J,this.now()),U0($,X),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!o3($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!B1(X))continue;if(X$($,X))continue;if(k0(X))continue;let J=X;try{if(E1(J,$,this.now())){if(Z1(J.lastRefreshError,J.refresh,this.now()))continue;J=await this.refreshAccount(J,$),Z=!0}if(n1(J.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(J,$),!(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access):u4(J,$,this.now())))continue;await this.refreshAccountQuota(J,$),Z=!0}catch(z){a3(X,z,this.now()),U0($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!o3(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||!B1(G))continue;if(X$(Z,G))continue;if(k0(G))continue;let Q=G;try{if(E1(Q,Z,this.now())){let B=Q.lastRefreshError;if(B&&Z1(B,Q.refresh,this.now()))throw Error(C$(B,this.now()));Q=await this.refreshAccount(Q,Z),z=!0}if(!J&&!u4(Q,Z,this.now())){if(Q.lastQuotaRefreshError)Q.lastQuotaRefreshError=void 0,U0(Z,Q),z=!0;continue}await this.refreshAccountQuota(Q,Z),z=!0}catch(B){a3(G,B,this.now()),U0(Z,G),z=!0,X.push({accountId:G.id,message:f$(B)})}}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 U0(Z,Q),Q}let z=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,z);let G=await z;return U0(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,X,J){let z=Date.now()+RG;while(Date.now()<z){await new Promise((H)=>setTimeout(H,EG));let G=await this.load(),Q=G?.accounts.find((H)=>H.id===$.id&&B1(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||!E1(Q,G,this.now())))return U0(Z,Q),R1.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:Q.id,expiresInMs:Q.expires?Q.expires-this.now():void 0}),Q;let Y=Q.lastRefreshError;if(Y&&Z1(Y,Q.refresh,this.now()))throw U0(Z,Q),Error(C$(Y,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(X$($,Z))throw new s4(Z.id)}async refreshAccountNow($,Z,X){let J=await this.load(),z=J?.accounts.find((B)=>B.id===$.id&&B1(B));if(this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!E1(z,J,this.now()))return U0(Z,z),z;let G=z??$,Q=await $0({name:SG(G.id),ttlMs:AG,path:this.paths.configPath,renew:!0});if(!Q){R1.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let B=await this.waitForConcurrentFallbackRefresh($,Z,G,X);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(J=await this.load(),z=J?.accounts.find((V)=>V.id===$.id&&B1(V)),this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!E1(z,J,this.now()))return U0(Z,z),z;if(!z)throw new a6($.id);G=z;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});R1.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 Y=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=Y.access,G.refresh=Y.refresh,G.expires=Y.expires,G.lastRefreshedAt=Y.expires-Y.expiresIn*1000,G.lastRefreshError=void 0,U0(Z,G),await this.save(Z),!(await this.load())?.accounts.some((V)=>V.id===$.id))throw new a6($.id);return R1.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,U0(Z,X),await this.save(Z)}catch(G){throw a3($,G,this.now()),U0(Z,$),G}}}var i4="/backend-api/wham/rate-limit-reset-credits",mU=`https://chatgpt.com${i4}`,bG=`${i4}/consume`,wU=`https://chatgpt.com${bG}`;function X0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as fG}from"node:fs";import{rm as t4}from"node:fs/promises";import{dirname as gG,join as e4}from"node:path";import{resolveClaustrumConnectionPath as hG}from"@cortexkit/claustrum-client";function a4($,Z){if(!$)return;let X=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(X)||X<0||X>100)return;return{usedPercent:X,remainingPercent:100-X,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function n4($){if(!X0($)||typeof $.minor!=="number"||!Number.isSafeInteger($.minor)||typeof $.exponent!=="number"||!Number.isInteger($.exponent))return;let Z=$.minor/10**$.exponent;return Number.isFinite(Z)?Z:void 0}function xG($){let Z=n4($.total),X=n4($.remaining);if(Z===void 0||X===void 0||Z<0||X<0)return;let J=Z-X,z=$.spendable===!1,G=Z>0?J/Z*100:z?100:0;return{limit:Z,used:J,remaining:X,usedPercent:G,remainingPercent:100-G,reached:z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...X0($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function r4($,Z){let X=a4($.usage?.primary,Z.fetchedAt);if(!X||!Number.isFinite(Z.fetchedAt))return;let J=a4($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((B)=>X0(B)&&B.id==="individual_limit"):void 0,G=X0(z)?xG(z):void 0,Q=X0($.savedResets)?$.savedResets.availableCount:void 0;return{primary:X,...J&&{secondary:J},...typeof Q==="number"&&Number.isFinite(Q)&&Q>=0&&{resetCreditsAvailable:Q},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}var o4=["primary","secondary"];function J8($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function h$($){return typeof $==="number"&&Number.isFinite($)}function kG($,Z){if(!J8(Z))return;let X=Z.usedPercent;if(!h$(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...h$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function yG($){let Z=$.spendControl;if(J8(Z)&&typeof Z.reached==="boolean"){let X=(J)=>h$(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 S0($,Z,X){if(!J8($)||!h$(Z))return;let J=[],z=[];for(let Y of o4){let H=kG(Y,$[Y]);if(H)J.push(H);else if(X)z.push({label:Y})}let G=yG($),Q=$.resetCreditsAvailable,B=typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>=0?{resetCredits:{value:Q,checkedAt:Z}}:void 0;if(J.length===0&&z.length===0&&!G&&!B)return;return{checkedAt:Z,...J.length>0?{readings:J}:{},...z.length>0?{coverage:z}:{},...G?{budget:G}:{},...B?{counters:B}:{}}}function z$($){if(!B0($))return;let Z=s($),X={};for(let J of o4){let z=Z.limits.find((Q)=>Q.label===J&&Q.kind==="reading");if(!z||!h$(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}function z8($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var G8="ck auth reclassify --from-registry";function e6($,Z){if(Z===void 0)return"No ChatGPT login in the vault has the `openai-native` category, or the grant is missing. Check `ck auth status` for categories and `ck auth grant` for the grant.";if(Z.grants===0)return`The vault has no grant letting ${$} read OpenAI accounts. Grant it with \`${z8($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${G8}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var y0=n("vault"),vG="openai-auth",$7={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},mG={opencode:"OpenCode",pi:"Pi"};function wG($){return A3(vG,$)}function $Z($){return e4(gG($),"openai-auth-vault")}function pG($,Z){return{...R3({stateDir:$,host:Z}),rosterPath:e4($,`${Z}-roster.json`)}}var ZZ=2000;var uG={"vault-unreachable":"Request refused locally: this host is connected to the credential vault, which could not be reached, and local accounts are not used while it is connected. Start the vault and connect accounts in it, or disconnect this host from the vault.","vault-empty":"Request refused locally: this host is connected to the credential vault, which serves it no usable OpenAI account, and local accounts are not used while it is connected. Connect accounts in the vault, or disconnect this host from the vault.","vault-grant-unreached":`Request refused locally: this host is connected to the credential vault, whose grant for it reaches no ChatGPT login, and local accounts are not used while it is connected. Logins without the openai-native category are not reached: run ${G8} to fill empty category sets, then check the CATEGORIES column with ck auth status. Or disconnect this host from the vault.`,"vault-refused":"Request refused locally: the credential vault did not authorize an account, and local accounts are not used while this host is connected to it. Check the accounts in the vault, or disconnect this host from the vault."};function Z7($,Z){if($!=="vault-no-grant")return uG[$];return`Request refused locally: this host is connected to the credential vault, which has no grant letting it read OpenAI accounts, and local accounts are not used while it is connected. Disconnect this host from the vault, or grant it access with: ${z8(Z)}`}function X7($){let Z=$.snapshot();if(Z===void 0)return"vault-unreachable";if(Z.rows.length===0){let X=$.grantReach();if(X!==void 0)return X.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function lG($){let Z=r1($);return Z?o1(Z):void 0}class Q8{host;name;paths;#$;#Z;#Q=new Map;#J=new Map;#V=new Map;#H;#X;#W;#B;#U=!1;#z=!1;#G=Promise.withResolvers();#Y;#D="unknown";#K;constructor($){this.#$=$,this.host=$.host,this.name=wG($.host),this.paths=pG($.stateDir,$.host),this.#Z=new c6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:$7,connect:()=>this.#_(),isCustodyActive:()=>this.enrolled(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:lG,insula:{provider:"codex",normalize:r4},...$.now?{now:$.now}:{},onRoster:()=>{this.#X=void 0},onError:(Z)=>this.#j("vault roster refresh failed",Z),logger:y0})}#q(){return(this.#$.connectionFile??hG)()}#L(){return{connectionFile:this.#q(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>y0.debug("vault transport error",{errorClass:$})}}#_(){return(this.#$.connectScoped?.()??I4(this.#L())).then(($)=>{return this.#H=$.insula!==void 0,$})}#N($,Z,X){if(this.#V.get($)===Z)return;this.#V.set($,Z),y0.info("vault background quota source changed",{routeId:$,source:Z,reason:X})}#O(){return this.#$.connectEnrollment?.()??S3(this.#L())}#j($,Z){this.#X=c0(Z),y0.warn($,{host:this.host,error:this.#X})}#M(){return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=fG($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#M(),Z=await I3(this.paths,this.name);if($===this.#M())return this.#D=Z,this.#K=$,Z;return"unreadable"}enrolled(){return this.#K!==this.#M()||this.#D!=="local"}start(){if(this.#U||this.#z)return;this.#U=!0;let $=async()=>{try{await this.authority(),await this.#F(),await this.#Z.refreshInsulaQuota()}catch(X){if(!this.#z)this.#j("vault roster refresh failed",X)}if(this.#z)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#Y=setTimeout(()=>{this.#Y=void 0,$()},Z),this.#Y.unref?.()};$()}#F(){return this.#B??=this.#Z.refresh().finally(()=>{this.#B=void 0,this.#G.resolve()}),this.#B}firstRoster(){return this.#G.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let $=this.#B;if($)await $.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#B??this.#F()).catch((X)=>{this.#j("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let $=this.#B;if($)await $.catch(()=>{return});let Z=await this.#F();return this.#X=void 0,Z}catch($){return this.#j("vault roster refresh failed",$),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}grantReach(){return this.#Z.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap(($)=>$.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,credentialId:$.get(Z.id)?.credentialId,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.#j("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#Z.authorize($,Z.signal)}catch(X){this.#j("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.#j("vault failure report failed",X)}await this.refresh()}recordSnapshot($,Z,X,J){let z=S0(Z,(this.#$.now??Date.now)(),X);if(!z)return Promise.resolve();return this.#Z.recordQuota($,z,J).then(()=>{},(G)=>this.#j("vault quota write failed",G))}pollQuota($,Z=!0){let X=this.#J.get($);if(X)return X;let J=this.#C($,Z).finally(()=>{this.#J.delete($)});return this.#J.set($,J),J}async#C($,Z){if(Z){await this.authority(),await this.#Z.refreshInsulaQuota();let G=(await L0(this.paths.rosterPath))?.rows.find((B)=>B.routeId===$),Q=await this.#Z.cachedInsulaQuotaForRoute($);if(Q!==void 0&&G?.accountIdentity){let B=S0(Q,Q.primary.checkedAt,!0);if(!B)return this.#N($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota($,G.accountIdentity,B))return this.#N($,"insula",null),{ok:!0};return this.#N($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}this.#N($,"fallback",this.#H===!1?"insula-not-configured":"no-insula-reading")}let X,J=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,Q)=>{try{let B=Z?void 0:await this.#Z.cachedInsulaQuota(Q);if(B!==void 0){let H=S0(B,B.primary.checkedAt,!0);if(!H)throw Error("unusable insula reading");return await this.#Z.recordQuota($,H,Q),new Response(null,{status:200})}let Y=await Z$({accessToken:G,fetchImpl:J,now:this.#$.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:$,logger:y0});return await this.recordSnapshot($,Y,!0,Q),X=void 0,new Response(null,{status:200})}catch(B){X=c0(B);let Y=B?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw B}},{site:"quota"}).catch((G)=>{X=c0(G);return});if(!z)return{ok:!1,error:X??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:X??`status ${z.status}`}}requestReading($){let Z=this.#Q.get($);if(Z)return Z;let X=this.pollQuota($,!1).catch((J)=>{y0.warn("vault quota poll failed",{routeId:$,error:c0(J)})}).finally(()=>{this.#Q.delete($)});return this.#Q.set($,X),X}async pollStale($){let Z=(this.#$.now??Date.now)(),X=[];for(let J of this.routes()){let z=dG(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($),y0.info("vault account declined",{routeId:$})}async accept($){await this.#Z.accept($),y0.info("vault account accepted",{routeId:$})}async status(){await this.authority();let $;try{$=await E$(this.paths,this.name)}catch(Z){this.#j("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.#O().catch((Z)=>{throw new Q0("vault-unreachable",`Could not reach the Claustrum vault (${this.#q()}): ${c0(Z)}. Is the vault running?`)});try{let Z=new p6({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(y0.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.#W??=(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.#W=void 0}),this.#W}async disconnect(){await t4(this.paths.tokenPath,{force:!0}),await t4(this.paths.statePath,{force:!0}),await this.authority(),this.#X=void 0,y0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())x3({mode:"custody",auth:$,provider:"openai"})}close(){if(this.#z=!0,this.#G.resolve(),this.#Y)clearTimeout(this.#Y);this.#Y=void 0,this.#Z.close()}}function dG($){if(!$)return;let Z=s($).limits.map((X)=>X.checkedAt);return Z.length>0?Math.max(...Z):void 0}function XZ($,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 ${$7.category} --operation read`]}function J7($,Z,X){let J=`${mG[$]} (${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 B8($,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?`. ${e6($.name,$.grantReach())}`:"."}`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${Z.code}). Run Connect again to send a new request.`};case"pending":case"busy":return{ok:!1,text:[...XZ($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
99
+ `)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var z7=`${String.fromCharCode(27)}\\[[0-9;]*m`,Vj=new RegExp(z7,"g"),Uj=new RegExp(`^${z7}`);function G$($){return $.authority!=="local"}async function s0($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function B7($){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."),ZZ)})])}finally{clearTimeout(Z)}}function W1($){return $.email||$.label||$.routeId}var H8="Accounts are managed in the vault with ck. Disconnect to use local accounts.",v$="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";var R0="main";function JZ($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function H7($,Z,X){let J=new Map;if(Z8(Z))for(let z of $)J.set(z.id,d4(z$(z.quota),Z,z.id===R0?void 0:z.id,X));return J}var W7=5,W8=5000;function V7($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function U7($,Z=W8){let X=$.rows.filter((Q)=>Q.kind==="oauth"&&$.killswitch.get(Q.id)!==!1&&s(Q.quota).limits.length===0);if(X.length===0)return;if(h0({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((Q)=>$.killswitch.get(Q.id)!==!1))return;let z=[];if(h0({rows:X,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(Q)=>{let B=$.requestPull(Q);if(B)z.push(B.catch(()=>{}))}}),z.length===0)return;let G;return Promise.race([Promise.all(z),new Promise((Q)=>{G=setTimeout(Q,Z)})]).then(()=>{}).finally(()=>clearTimeout(G))}function V8($){return $.reason==="exhausted"||$.reason==="budget-spent"}function j7($,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 Y7($,Z,X){if(Z.refused.find((z)=>!V8(z)&&X.get(z.id)!==!1))return{reason:"quota-unknown"};return j7($[0],Z,X)}function D7($){let Z=$.replayable!==!1,X=$.mainId===void 0?R0:$.mainId??"",J=Z?$.placement:"main-first",z=_Z({rows:$.rows,placement:J,formerMainId:X,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),G=f1($.rows.map((Y)=>Y.id),J,X),Q=new Set(z.admission.refused.filter((Y)=>V8(Y)&&$.killswitch.get(Y.id)!==!1).map((Y)=>Y.id)),B=G.filter((Y)=>Q.has(Y));if(!Z){let Y=G.includes(X),H=Y?X:z.order[0]??B[0];if(H!==void 0&&z.order.includes(H))return{kind:"send",order:[H],lastPath:!1};if(H!==void 0&&Q.has(H))return{kind:"send",order:[H],lastPath:!0};return{kind:"block",block:Y?j7(X,z.admission,$.killswitch):Y7(G,z.admission,$.killswitch)}}if(z.order.length>0)return{kind:"send",order:z.order,lastPath:!1};if(B.length>0)return{kind:"send",order:B,lastPath:!0};return{kind:"block",block:Y7(G,z.admission,$.killswitch)}}function U8($){let Z=h0({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),X=new Map;for(let J of $.rows)X.set(J.id,s(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 K7($,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 B=Z.resetCredits(Q.id);if(B!==void 0)G.set(Q.id,B)}return RZ({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 q7($,Z,X,J){let z=K7($,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 N7($,Z,X){let J=$.killswitch.get(X)===!1,z=K7($,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&&V8(G))return{kind:"last-path"};return{kind:"none"}}function M7($,Z,X,J){let z=$.killswitch.get(X);return SZ({quota:Z.projections.get(X),now:$.now,...J===void 0?{}:{status:J},...z===void 0?{}:{killswitchPasses:z}})}function F7($){return X0($)?{...$}:{}}function zZ($,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 B=await $.apply({command:$.command,sectionId:Z,...J?{itemId:J}:{},actionId:X.id,values:G,confirmed:!0},Q);return{ok:B.ok,text:B.text,...B.code?{code:B.code}:{}}}}}function j8($,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 B=await s0(Z);if(!G$(B))return Q;let Y=[...B.status.accounts.map((H)=>({id:H.routeId,label:W1(H),type:"oauth",enabled:H.enabled,identity:H.accountIdentity,quota:H.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:Y}};if(J==="readSettings")return async()=>{let G=await X.readSettings();if(G.status==="error"||!Z)return G;let Q=await s0(Z),B=F7(G.settings.killswitch);if(!G$(Q)||!G.settings.killswitch)return G;let Y=F7(B.accounts);for(let H of Q.status.accounts)Y[H.routeId]=H1({version:1,accounts:[],...G.settings},H.routeId);return{...G,settings:{...G.settings,killswitch:{...B,accounts:Y}}}};let z=Reflect.get(X,J);return typeof z==="function"?z.bind(X):z}})}function D8($,Z,X={}){let J=_1($),z=(H)=>_1({command:$.command,title:$.title,store:j8($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:{...$.routing,formerMainId:H??""},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),G=async(H,V)=>{let W=await s0(Z),j=G$(W),D=JZ(W.status.accounts.map((A)=>({id:A.routeId,credentialId:A.credentialId}))),U=j?z(D):J,K=(await U.open(V)).menu.sections.find((A)=>A.id===H);if(!K)throw new Q0("unavailable","The account menu is unavailable.");if(!j)return{lines:K.lines,items:K.items.map((A)=>({...A,actions:A.actions.map((x)=>zZ(U,H,x,A.id))})),actions:K.actions.map((A)=>zZ(U,H,A))};let M=new Map(W.status.accounts.map((A)=>[A.routeId,A])),P=($.now??Date.now)(),E=(A)=>({id:"check",label:A?"Check this account":"Check now",group:"Actions",run:async()=>{let w=[...(await s0(Z)).routes].filter((y)=>!A||y===A);if(A&&w.length===0)throw new Q0("unavailable","This vault account cannot be checked right now.");for(let y of w){let f=await Z.pollQuota(y);if(!f.ok)throw new Q0("quota-check-failed",`${y}: ${f.error??"vault unavailable"}`)}return`Checked quota for ${w.length} account${w.length===1?"":"s"}.`}});if(H==="quota"){let A=(x,w)=>C0(s(x.quota,$.quota?.scope),{now:P,form:w});return{lines:W.status.accounts.filter((x)=>!W.routes.has(x.routeId)).map((x)=>`${W1(x)} (${x.enabled?x.state:"disabled"}): ${A(x,"compact")}`),items:W.status.accounts.filter((x)=>W.routes.has(x.routeId)).map((x)=>({id:x.routeId,label:W1(x),group:"Accounts",status:A(x,"compact"),detail:A(x,"full"),actions:[E(x.routeId)]})),actions:W.routes.size>0?[E()]:[]}}let F=K.items.map((A)=>{let x=M.get(A.id),w=x&&H==="accounts"?`Vault · ${x.credentialType==="oauth"?"login":"API key"} · ${x.state} · ${x.enabled?"enabled":"declined"}`:A.detail;return{id:A.id,label:A.label,detail:w,group:A.group,status:x&&H==="accounts"?x.enabled?x.state:"disabled":A.status,...A.facts?{facts:A.facts}:{},actions:x&&H!=="limits"?[]:A.actions.map((y)=>zZ(U,H,y,A.id))}}),q=K.actions.filter((A)=>H==="limits"||H==="routing"&&A.id==="mode").map((A)=>zZ(U,H,A)),L=K.actions.find((A)=>A.id==="mode")?.knobs.find((A)=>A.id==="mode"),S=H==="routing"&&D===null&&L?.kind==="choice"&&(L.value==="main-first"||L.value==="fallback-first");return{lines:H==="accounts"?[`${W.status.accounts.length} vault account${W.status.accounts.length===1?"":"s"}`,`${W.routes.size} can route`,H8]:[...K.lines,...S?["No default vault account, so this mode orders like Ordered"]:[]],items:F,actions:q}},Q=_1({...$,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(H)=>G("accounts",H)},quota:{title:"Quota",build:(H)=>G("quota",H)},routing:{title:"Routing",build:(H)=>G("routing",H)},limits:{title:"Limits",build:(H)=>G("limits",H)}},extras:$.extras?.map((H)=>H.id!=="reset"?H:{...H,build:async(V)=>{let W=await s0(Z);if(G$(W))return{lines:[H8]};return H.build(V)}})}),B=async()=>{if(!G$(await s0(Z)))return{menu:J,error:void 0};let H=X.refresh===!1?void 0:await B7(Z);return{menu:Q,error:H}},Y=async(H,V)=>{let W=await H.menu.open(V);if(H.error)W.menu.sections.find((D)=>D.id==="vault")?.lines.push(`Last error: ${H.error}`);return W};return{command:$.command,open:async(H)=>Y(await B(),H),apply:async(H,V)=>{let W=await B(),{menu:j}=W;if(j===Q&&(H.sectionId==="accounts"||H.sectionId==="routing"&&H.actionId==="order"||H.sectionId==="reset"||H.sectionId==="quota"&&(await s0(Z)).routes.size===0||H.sectionId==="limits"&&H.itemId!==void 0&&!(await s0(Z)).status.accounts.some((D)=>D.routeId===H.itemId)))return{...await Y(W,V),ok:!1,code:"vault-local-action",text:v$};if(X.refuseApply)return{...await Y(W,V),ok:!1,...X.refuseApply};return j.apply(H,V)}}}var V1="openai",M8="OpenAI accounts",I1="main",_7="that account is already your main account, so it was not added again",m$=n("commands"),O7=new Set(["__proto__","constructor","prototype"]);function C7($,Z){let X={version:1,accounts:[],killswitch:$},J=X0($.accounts)?Object.keys($.accounts):[],z={};for(let B of new Set([I1,...Z,...J])){if(O7.has(B))continue;let Y=H1(X,B===I1?void 0:B);z[B]={primary:Y.primary,secondary:Y.secondary}}let G=H1(X,void 0),Q={...$};return delete Q.main,Q.accounts=z,Q.defaults={primary:G.primary,secondary:G.secondary},Q.schema=J$,Q}function P7($,Z){let X=X0($.accounts)?{...$.accounts}:{};for(let z of new Set([I1,...Z])){if(O7.has(z)||Object.hasOwn(X,z))continue;X[z]={primary:Y1.primary,secondary:Y1.secondary}}let J=X0($.defaults)?$.defaults:{primary:Y1.primary,secondary:Y1.secondary};return{...$,accounts:X,defaults:J,schema:J$}}function K8($,Z){let X=!1;if(X0($.cachekeep))$.cacheKeep={...$.cachekeep,...X0($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,X=!0;let J=$.killswitch;if(X0(J)&&J.schema!==J$)$.killswitch=C7(J,Z),X=!0;return X}async function L7($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((X)=>X.id):[]}function T7($){let Z=async()=>{let J=await $.readSettings();if(J.status==="error")return J;let z=structuredClone(J.settings);return K8(z,await L7($)),{...J,settings:z}},X=async(J,z)=>{let G=await L7($);return $.updateSettings(async(Q)=>{K8(Q,G);let B=await J(Q)??Q;if(X0(B.killswitch)&&B.killswitch.schema!==J$)B.killswitch=P7(B.killswitch,G);return B},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 A7($,Z){let X=(Y,H)=>Z.rowLocks?Z.rowLocks(Y):H,J=(Y,H)=>{let V=X(Y,H?.extraLocks);return{...H??{},...V?{extraLocks:V}:{}}},z=(Y,H,V,W)=>$.replace(Y,H,V,J(Y,W)),B={add:async(Y,H)=>{let V=await $.read(),j=(V.status==="ready"?V.rows:[]).filter((K)=>K.type==="oauth"&&!K.invalid),D=Y.identity?j.find((K)=>K.identity===Y.identity):void 0;if(D?.id===I1)throw new Q0("main-account",_7);let U=D??j.find((K)=>K.id===Y.id&&K.id!==I1);if(!U||Y.credential.type!=="oauth")return $.add(Y,H);let N=await z(U.id,Y.credential,Y.identity!==void 0?{identity:Y.identity}:{},H?.extraLocks?{extraLocks:H.extraLocks}:void 0);return m$.info("account signed in again",{id:U.id}),{id:N.id,outcome:"rotated",credential:N.credential,credentialEpoch:N.credentialEpoch}},replace:z,enable:(Y,H)=>$.enable(Y,J(Y,H)),disable:(Y,H,V)=>$.disable(Y,H,J(Y,V)),remove:(Y,H)=>$.remove(Y,J(Y,H))};return new Proxy($,{get(Y,H){if(Object.hasOwn(B,H))return B[H];let V=Reflect.get(Y,H,Y);return typeof V==="function"?V.bind(Y):V}})}var S7="migration";function q8($){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:V1,title:M8,sections:[{id:S7,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 N8(X)}var $Q=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function ZQ($){let Z=$.toLowerCase().replace(/[-_]/g,"");if($Q.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function GZ($,Z,X){if(Array.isArray($))return $.map((z,G)=>GZ(z,`${Z}[${G}]`,X));if(!X0($))return $;let J={};for(let[z,G]of Object.entries($)){if(ZQ(z)){X.push(`${Z}.${z}`);continue}J[z]=GZ(G,`${Z}.${z}`,X)}return J}function N8($){let Z=[],X=GZ($,"menu",Z);if(Z.length>0)m$.warn("credential-shaped field stripped before RPC",{fields:Z});return X}function R7($){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 E7($,Z){return{label:"Add account",knobs:[{kind:"text",id:"label",label:"Label (optional)"},{kind:"toggle",id:"headless",label:"Sign in with a device code (no browser on this machine)",value:!1}],run:async(X)=>{let J=typeof X.label==="string"&&X.label.trim().length>0?X.label.trim():void 0,z=X.headless===!0,G=await $.begin({...J!==void 0?{label:J}:{},headless:z}),Q=z?`Open this verification URL:
100
100
 
101
- ${z.url}
101
+ ${G.url}
102
102
 
103
- Then enter the code: ${z.instructions.match(/Enter code: (.+)/)?.[1]??z.instructions}
103
+ Then enter the code: ${G.instructions.match(/Enter code: (.+)/)?.[1]??G.instructions}
104
104
 
105
105
  The account is added when you finish.`:`Open this URL and complete sign-in:
106
106
 
107
- ${z.url}
107
+ ${G.url}
108
108
 
109
- ${z.instructions}
109
+ ${G.instructions}
110
110
 
111
- The account is added when you finish.`,Q=z.completion.then(async(Y)=>{if(Z&&await Z.authority()!=="local")throw new B0("vault-local-action",v$);let H=await $.mainIdentity?.();if(Y.id===I1||Y.accountId&&H&&Y.accountId===H)throw m$.warn("account add rejected (main identity)",{id:Y.id}),new B0("main-account",q7);return m$.info("account added",{id:Y.id}),C7(Y)});return{status:"pending",message:B,completion:Q}}}}function q8($){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:G})=>{if(!G.sessionId)return"No current session.";return await $.clearPin?.(G.sessionId),m$.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 N8($){let{vault:Z}=$;return{id:"vault",title:"Vault",build:async()=>{let X=await Z.status(),J=await Z.authority()!=="local",G=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}`,t2(X.host,X.name,X.enrollment),...XZ(X.name,X.enrollment),...J?[X.accounts.length===0?e6:`The vault serves ${X.accounts.length} OpenAI account${X.accounts.length===1?"":"s"}; ${G} 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((z)=>({id:z.routeId,label:W1(z),group:"Accounts",status:z.enabled?z.state:"disabled",detail:[z.credentialType==="api_key"?"API key":"login",z.state==="active"?"active":`vault state ${z.state}`,z.enabled?"enabled":"disabled here"].join(", "),actions:[z.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(z.routeId),await $.changed?.(),`${W1(z)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await Z.accept(z.routeId),await $.changed?.(),`${W1(z)} 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:z})=>{let B=await Z.connectStep();if(B.state!=="pending"&&B.state!=="busy")return await $.changed?.(),G8(Z,B);return Z.waitForApproval($.wait).then(async(Q)=>{await $.changed?.();let Y=G8(Z,Q);z.notify(Y.text,Y.ok?"info":"warning")}).catch((Q)=>{z.notify(`Connecting to the vault failed: ${Q instanceof Error?Q.message:String(Q)}`,"error")}),{ok:!0,text:[...XZ(Z.name,B),"Waiting for the approval; you are told here when it lands."].join(`
112
- `)}}}]}}}}var T7=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],A7=["primary","secondary"];function M8($){let Z=new Set($.unavailableSections),X=(Y)=>({title:Y,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),J=[...$.extras??[]];if(Z.has("reset")){let Y={id:"reset",...X("Reset credits")},H=J.findIndex((W)=>W.id==="reset");if(H<0)J.unshift(Y);else J[H]=Y}let G={command:V1,title:K8,store:W8(L7(_7($.store,{...$.rowLocks?{rowLocks:$.rowLocks}:{}}))),...$.extraLocks?{extraLocks:$.extraLocks}:{},accounts:{...$.login?{login:P7($.login,$.vault)}:{},...$.protect?{protect:$.protect}:{},...$.describeIdentity?{describeIdentity:$.describeIdentity}:{}},quota:$.quotaCheck?{check:$.quotaCheck}:{},routing:{orderedVariants:T7,formerMainId:I1},limits:{labels:A7},...Z.has("cache")?{cache:X("Cache")}:$.cache?{cache:$.cache}:{},...Z.has("diagnostics")?{diagnostics:X("Diagnostics")}:$.diagnostics?{diagnostics:$.diagnostics}:{},extras:J,...$.logger?{logger:$.logger}:{},...$.now?{now:$.now}:{}},z=$.vault?V8(G,$.vault,{refresh:!$.readOnly,...$.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):_1(G),B=$.vault?V8(G,$.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,Q=(Y)=>{let{sessionId:H}=Y,W=Y.notify.bind(Y);return{...H!==void 0?{sessionId:H}:{},notify:W}};return{command:V1,async open(Y){let H=Q(Y),W=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(W&&!W.migrated)return{command:V1,menu:j8(W.blockers)};let V=await z.open(H);return{...V,menu:D8(V.menu)}},async apply(Y,H){let W=Q(H),V=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(V&&!V.migrated)return{command:V1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:j8(V.blockers)};if($.readOnly&&$.vault)return z.apply(Y,W);if($.readOnly||$.allowAction&&!$.allowAction(Y)||Z.has(Y.sectionId)){if(B)return B.apply(Y,W);return{...await z.open(W),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let j=await z.apply(Y,W);if(j.ok)await $.afterApply?.();return{...j,menu:D8(j.menu)}}}}function S7($,Z,X){let J=$.get(Z.sessionId),G=new Set(Z.validPinnedAccountIds);if(J&&!Z.excludeAccountIds.includes(J.accountId)&&W$(J,G,Z.wireAccountIdByAccount[J.accountId])){if(Z.persist){let Y=Z.quotaCheckedAtByAccount[J.accountId];X(Z.sessionId,{accountId:J.accountId,inputBytes:Z.requestBytes,...J.wireIdentity!==void 0?{wireIdentity:J.wireIdentity}:{},...Y!==void 0?{quotaCheckedAt:Y}:{}})}return{accountId:J.accountId}}let z=new Map(Object.entries(Z.quotaCheckedAtByAccount)),B=OZ($,z,Z.sessionId),Q=Z.select(B);if(!Q)return;if(Z.persist){let Y=Z.wireAccountIdByAccount[Q.accountId];X(Z.sessionId,{accountId:Q.accountId,inputBytes:Z.requestBytes,...Y!==void 0?{wireIdentity:Y}:{},...Q.quotaCheckedAt!==void 0?{quotaCheckedAt:Q.quotaCheckedAt}:{}})}return{accountId:Q.accountId}}import{statSync as iz}from"node:fs";var R7=30000,az=8,nz=1800000;function E7($){return $.identity?`identity:${$.identity}`:`row:${$.id}`}function F8($){try{let Z=iz($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function b1($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}function L8($,Z){try{return E0($,Z)}catch{return $}}function I7($,Z,X){let J=E7(Z);$.set(J,[...$.get(J)??[],{credentialEpoch:Z.credentialEpoch,identity:Z.identity,observation:X}].slice(-az))}function b7($,Z,X){let J=$;for(let G of Z.get(E7($))??[]){if(!(X-G.observation.checkedAt<=nz)||G.credentialEpoch!==$.credentialEpoch||G.identity!==$.identity)continue;J={...J,quota:L8(J.quota,G.observation)}}return J}function x7($,Z,X,J){let G=a1($);if(typeof Z?.status==="number"||V3(Z)){let B=I6({error:Z,now:X,refreshToken:$,...J?{previous:{message:"",checkedAt:X,nextRetryAt:J.nextRetryAt,retryCount:J.retryCount,tokenHash:J.tokenHash}}:{}});return{nextRetryAt:B.nextRetryAt,tokenHash:G,retryCount:B.retryCount}}return{nextRetryAt:X+R7,tokenHash:G,retryCount:J?.tokenHash===G?J.retryCount:0}}function k7($,Z,X,J){let G=new Map;for(let z of $){if(J(z,X))continue;let B=Z.get(z.id);G.set(z.id,B&&B.nextRetryAt>X?B.nextRetryAt:X+R7)}return G}var XK=a("quota");import{types as rz}from"node:util";var oz=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,tz=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function h7($){return $.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,(Z,X,J)=>{if(X)return String.fromCharCode(Number.parseInt(X,16));return{b:"\b",f:"\f",n:`
113
- `,r:"\r",t:"\t"}[J]??J??Z})}function ez($,Z){if(!Z)return $;let X=$.split(Z).join("[credential]"),J=Z.replace(/\s/g,"");if(!J)return X;let G=X.replace(/\s/g,"");if(!G.includes(J))return X;let z=[];for(let Y=0;Y<X.length;Y++){let H=X[Y]??"";if(!/\s/.test(H))z.push(Y)}let B=[],Q=0;for(let Y=G.indexOf(J);Y>=0;Y=G.indexOf(J,Y+J.length)){let H=z[Y]??Q,W=(z[Y+J.length-1]??H)+1;B.push(X.slice(Q,H),"[credential]"),Q=W}return B.length?B.join("")+X.slice(Q):X}function y7($,Z){let X=ez($,Z);return E4(X).replaceAll("***REDACTED***","[credential]")}function U1($,Z){let X=y7($,Z),J=h7(X),G=y7(J,Z);return G===J?X:G}function f7($){let Z=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec($);if(!Z)return;let X=Z[3]??"",J=(Z[2]??"")+X,G=0;while(J[G]==="0")G++;if(G===J.length)return"0";let z=J.length;while(J[z-1]==="0")z--;let B=Z[4]??"0",Q=B.startsWith("-")||B.startsWith("+")?1:0;while(B[Q]==="0")Q++;let Y=B.slice(Q)||"0";if(Y.length>16)return;let H=BigInt((B.startsWith("-")?"-":"")+Y)-BigInt(X.length)+BigInt(J.length-z);return`${Z[1]}${J.slice(G,z)}e${H}`}function v7($,Z){let X=Z?f7(Z):void 0;return $.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(J)=>{if(!J.startsWith('"'))return Z&&(J===Z||X!==void 0&&f7(J)===X||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===Z)?'"[credential]"':J;let G=h7(J.slice(1,-1)),z=U1(G,Z);return z===G?J:JSON.stringify(z)})}function _8($,Z){let X=v7($,Z);try{return JSON.parse($),X}catch{return U1(X,Z)}}var $B=16384,ZB=65536,XB=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function JB($){try{let Z=t(JSON.parse($),"request_id");if(typeof Z==="string")return Z;if(typeof Z!=="number")return;let X=0,J,G=!0,z=!1,B;for(let Q of $.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Y=Q[0];if(Y==="{"||Y==="["){X++;continue}if(Y==="}"||Y==="]"){X--;continue}if(X!==1)continue;if(Y===","){G=!0,z=!1,J=void 0;continue}if(Y===":"){z=!0;continue}if(G&&Y.startsWith('"')){J=JSON.parse(Y),G=!1;continue}if(z&&J==="request_id"&&!Y.startsWith('"'))B=Y;z=!1}return B}catch{return}}function GB($,Z){let X=_8($,Z);if(Buffer.byteLength(X,"utf8")<=ZB)return X;let J=XB.flatMap((z)=>z.exec(X)?.[0]??[]);for(let z of["FreeUsageLimitError","GoUsageLimitError"])if(X.includes(z))J.push(z);let G={retry:J};try{let z=JSON.parse(X);if(t(z,"type")==="error")G.type="error";let B=t(z,"error"),Q={};for(let H of["code","type"]){let W=t(B,H);if(typeof W==="string")Q[H]=W.slice(0,256)}if(Object.keys(Q).length)G.error=Q;let Y={};for(let H of["workspace","limitName"]){let W=t(t(z,"metadata"),H);if(typeof W==="string")Y[H]=W.slice(0,256)}if(Object.keys(Y).length)G.metadata=Y}catch{}return JSON.stringify(G)}function BZ($){if(!$||typeof $!=="object")return!1;let Z=$;for(let X=0;Z&&X<16;X++){if(rz.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function t($,Z){if(!BZ($))return;let X=Object.getOwnPropertyDescriptor($,Z);return X&&"value"in X?X.value:void 0}function w$($,Z){return U1($,Z).slice(0,$B)}function B$($,Z){let X=Object.getOwnPropertyDescriptor($,Z)?.get;if(!X)throw Error(`Missing native ${Z} accessor`);return X}var zB=B$(DOMException.prototype,"message"),BB=B$(DOMException.prototype,"name");function j1($,Z){let X=t($,"message"),J=t($,"name");if(BZ($)&&$ instanceof DOMException)try{X=zB.call($),J=BB.call($)}catch{}let G=Error(w$(typeof X==="string"?X:typeof $==="string"?$:"Provider request failed",Z));for(let V of Object.getOwnPropertyNames(G))if(V!=="message")Reflect.deleteProperty(G,V);Object.defineProperty(G,"name",{value:typeof J==="string"?w$(J,Z):"Error",configurable:!0,writable:!0});let z=(V,j,D)=>{let U=t(V,D);if(typeof U==="string"||typeof U==="number"&&Number.isFinite(U)||typeof U==="boolean")Object.defineProperty(j,D,{value:typeof U==="string"?w$(U,Z):U,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=t($,V);if(typeof j==="number"&&Number.isFinite(j))z($,G,V)}for(let V of["code","type","isRetryable"])z($,G,V);for(let V of["error","data"]){let j=t($,V),D=Object.create(null);for(let N of["type","code","message","resets_at","resets_in_seconds"])z(j,D,N);let U=t(j,"error");if(BZ(U)){let N=Object.create(null);for(let K of["type","code","message","resets_at","resets_in_seconds"])z(U,N,K);D.error=N}if(Object.keys(D).length)Object.defineProperty(G,V,{value:D,enumerable:!0})}let B=t($,"responseHeaders");if(B&&typeof B==="object"){let V={};for(let j of["retry-after-ms","retry-after"]){let D=t(B,j);if(typeof D==="string")V[j]=w$(D,Z)}Object.defineProperty(G,"responseHeaders",{value:V,enumerable:!0})}let Q=t($,"responseBody");if(typeof Q==="string")Object.defineProperty(G,"responseBody",{value:GB(Q,Z),enumerable:!0});let Y=t($,"request_id"),H=t(B,"x-request-id"),W=typeof Y==="string"?Y:typeof H==="string"?H:typeof Q==="string"?JB(_8(Q,Z)):void 0;if(typeof W==="string")Object.defineProperty(G,"request_id",{value:w$(W,Z),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(V);if(t($,j)===!0)Object.defineProperty(G,j,{value:!0})}return G}function QB($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!oz.test($)&&!tz.test($)))return $;let X;try{X=JSON.parse($)}catch{return $}if(X?.type==="error"||X?.error||X?.response?.error)return v7($,Z);return $}var YB=B$(Response.prototype,"status"),HB=B$(Response.prototype,"statusText"),WB=B$(Response.prototype,"headers"),VB=B$(Response.prototype,"body"),UB=Response.prototype.text,g7=Headers.prototype.entries;async function m7($,Z,X="http"){try{let D=function(U){let N=j&&U.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,N+U.slice(N.length).replace(/^data: ?([^\r\n]*)/gm,(K,M)=>K.slice(0,K.length-M.length)+QB(M,Z))};if(!BZ($))throw Error("Invalid provider response");let J=YB.call($),G=WB.call($),z=VB.call($),B=new Headers;for(let[U,N]of g7.call(G))B.append(U,N);let Q={status:J,statusText:U1(HB.call($),Z),headers:B};if(J<200||J>299){for(let[N,K]of g7.call(G)){if(U1(N,Z?.toLowerCase())!==N){Q.headers.delete(N);continue}try{Q.headers.set(N,U1(K,Z))}catch{Q.headers.delete(N)}}Q.headers.delete("content-length");let U=await UB.call($);return new Response(_8(U,Z),Q)}if(!z||X==="http")return $;Q.headers.delete("content-length");let Y=ReadableStream.prototype.getReader.call(z),H=new TextDecoder("utf-8",{ignoreBOM:!0}),W=new TextEncoder,V="",j=!0;return new Response(new ReadableStream({async pull(U){try{for(;;){let N=await Y.read();V+=H.decode(N.value,{stream:!N.done});let K=!1;for(;;){let M=/\r?\n\r?\n/.exec(V);if(!M)break;let P=M.index+M[0].length;U.enqueue(W.encode(D(V.slice(0,P)))),V=V.slice(P),K=!0}if(N.done){if(V)U.enqueue(W.encode(D(V)));U.close();return}if(K)return}}catch(N){U.error(j1(N,Z))}},async cancel(U){try{await Y.cancel(U)}catch(N){throw j1(N,Z)}finally{Y.releaseLock()}}}),Q)}catch(J){throw j1(J,Z)}}var w7={name:"@cortexkit/pi-openai-auth",version:"1.1.0",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/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --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/common-auth":"^0.18.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.9.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.16.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};var QZ=new Map;function p7($){return QZ.get($)?.accountId}function u7($){return QZ.delete($)}function l7($){return S7(QZ,$,(Z,X)=>QZ.set(Z,X))}import{join as $5}from"node:path";import{createHash as _B}from"node:crypto";import{constants as i7}from"node:fs";import{lstat as t7,mkdir as a7,open as e7,unlink as OB}from"node:fs/promises";import{dirname as Q$,resolve as n7}from"node:path";import{setTimeout as CB}from"node:timers/promises";import{rmdirSync as DB,statSync as c7,utimesSync as KB}from"node:fs";import{mkdir as qB,rmdir as NB,stat as O8,utimes as MB}from"node:fs/promises";var FB=30000,YZ=1e4,LB=3000,C8,p$=new Map;process.once("exit",()=>{for(let[$,Z]of p$)try{if(Z.renewedAt+YZ<Date.now())continue;let X=c7($);if(P8(X,Z)&&X.mtime.getTime()===Z.mtime)DB($)}catch{}});function P8($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function u$($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function d7(){return Object.assign(Error("Pi auth lock held"),{code:"ELOCKED"})}async function T8($){try{await NB($)}catch(Z){if(u$(Z)!=="ENOENT")throw Z}}async function A8($,Z){try{await qB($)}catch(X){if(u$(X)!=="EEXIST")throw X;if(Z<=0)throw d7();let J;try{J=(await O8($)).mtime.getTime()}catch(G){if(u$(G)==="ENOENT")return A8($,0);throw G}if(!(J<Date.now()-Z))throw d7();return await T8($),A8($,0)}try{if(!C8){let G=new Date(Math.ceil(Date.now()/1000)*1000+5);await MB($,G,G)}let X=await O8($),J=X.mtime.getTime();return C8??=J%1000===0?"s":"ms",{dev:X.dev,ino:X.ino,mtime:J}}catch(X){throw await T8($).catch(()=>{}),X}}async function s7($,Z,X){let J=`${$}.lock`,G=await A8(J,FB),z=G.mtime,B=Date.now(),Q=!1,Y;p$.set(J,{...G,renewedAt:B});function H(){if(Q=!0,Y)clearTimeout(Y);p$.delete(J),Z()}function W(){if(!Q&&B+YZ<Date.now())H()}function V(U=LB){if(Q)return;Y=setTimeout(()=>{D()},U),Y.unref()}function j(U){if(Q)return;if(u$(U)==="ENOENT"||B+YZ<Date.now())H();else V(1000)}async function D(){if(W(),Q)return;let U;try{U=c7(J)}catch(K){j(K);return}if(W(),Q)return;if(!P8(U,G)||U.mtime.getTime()!==z){H();return}let N=new Date(C8==="s"?Math.ceil(Date.now()/1000)*1000:Date.now());try{KB(J,N,N)}catch(K){j(K);return}if(W(),Q)return;z=N.getTime(),B=Date.now(),p$.set(J,{...G,mtime:z,renewedAt:B}),V()}return X?.(async()=>{if(Y)clearTimeout(Y);await D()}),V(),{assertFresh:W,async release(){if(Q)return;if(Q=!0,Y)clearTimeout(Y);p$.delete(J);let U=()=>B+YZ<Date.now();if(U()){H();return}let N;try{N=await O8(J)}catch(K){if(u$(K)!=="ENOENT")throw K;H();return}if(U()||!P8(N,G)||z!==N.mtime.getTime()){H();return}await T8(J)}}}class i extends Error{code;constructor($){super(`Pi slot: ${$}`);this.code=$,this.name="PiSlotError"}}function PB($){let Z=$.indexOf("{")+1,X={offset:Z-1,children:[]},J=()=>{while(/\s/.test($[Z]??"")&&Z<$.length)Z++},G=()=>{Z++;while(Z<$.length){if($[Z++]==='"')return;if($[Z-1]==="\\")Z++}};J();while($[Z]!=="}"){let z=Z;G();let B=JSON.parse($.slice(z,Z));J(),Z++,J();let Q=Z,Y=0;while(Z<$.length){let W=$[Z];if(W==='"'){G();continue}if(W==="{"||W==="[")Y++;if(W==="}"||W==="]"){if(Y===0)break;Y--}if(W===","&&Y===0)break;Z++}let H=Z;while(/\s/.test($[H-1]??""))H--;if(X.children.push({key:B,offset:z,length:H-z,value:{offset:Q,length:H-Q}}),J(),$[Z]==="}")break;Z++,J()}return X}function d$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R8($){if(Array.isArray($))return`[${$.map(R8).join(",")}]`;if(d$($))return`{${Object.keys($).sort().map((Z)=>`${JSON.stringify(Z)}:${R8($[Z])}`).join(",")}}`;return JSON.stringify($)}function f0($){return _B("sha256").update(R8($)).digest("hex")}function l$($){return d$($)?$.code:void 0}async function r7($,Z=!1,X){if(I)try{await X?.($);let G=await EZ($,!0),z=G.toString("utf8");if(!G.equals(Buffer.from(z)))throw new i(Z?"invalid-stash":"invalid-auth");return z}catch(G){if(l$(G)==="ENOENT")return;throw G}let J;try{J=await e7($,i7.O_RDONLY|i7.O_NOFOLLOW);let G=await J.stat();if(!G.isFile()||Z&&(G.mode&511)!==384)throw new i("unsafe-path");await X?.($);let z=await t7($);if(!z.isFile()||z.dev!==G.dev||z.ino!==G.ino)throw new i("unsafe-path");let B=await J.readFile(),Q=B.toString("utf8");if(!B.equals(Buffer.from(Q)))throw new i(Z?"invalid-stash":"invalid-auth");return Q}catch(G){if(l$(G)==="ENOENT"&&!J)return;if(l$(G)==="ELOOP"||l$(G)==="ENOENT")throw new i("unsafe-path");throw G}finally{await J?.close()}}function TB($,Z){try{let X=JSON.parse($);if(!d$(X))throw Error();let J=PB($),G=J.children,z=G.map((Y)=>Y.key);if(new Set(z).size!==z.length)throw Error();let B=G.find((Y)=>Y.key===Z),Q=B?X[Z]:null;if(Q!==null&&!d$(Q))throw Error();if(B&&Q===null)throw Error();return{text:$,root:J,property:B,entry:Q}}catch{throw new i("invalid-auth")}}function AB($){let Z=$.property?.value;return Z?$.text.slice(Z.offset,Z.offset+Z.length):null}function o7($,Z,X){let{text:J,root:G,property:z}=$,B=G.children??[];if(z){let H=z.value;if(!H)throw new i("invalid-auth");if(X!==null)return J.slice(0,H.offset)+X+J.slice(H.offset+H.length);let W=B.indexOf(z),V=B[W-1],j=B[W+1],D=V?V.offset+V.length:z.offset,U=!V&&j?j.offset:z.offset+z.length;return J.slice(0,D)+J.slice(U)}if(X===null)return J;let Q=B.at(-1),Y=Q?Q.offset+Q.length:G.offset+1;return`${J.slice(0,Y)}${Q?",":""}${JSON.stringify(Z)}:${X}${J.slice(Y)}`}async function SB($){if(I)return;let Z=await e7($,"r");try{await Z.sync()}finally{await Z.close()}}async function S8($,Z,X,J){await F0($,null,{serialize:()=>Z,durable:!0,durability:I?"file-only-on-windows":void 0,beforeRename:async()=>{await J?.($),X()}})}function E8($){return RB($)}function RB($,Z,X){let{provider:J,placeholderKey:G}=$,z=$.lockTimeoutMs??30000;if(!J||!$.authPath||!$.stashPath||!G||G.startsWith("!")||G.includes("$")||!Number.isFinite(z)||z<0)throw new i("invalid-options");let B=n7($.authPath),Q=n7($.stashPath);if(B===Q||Q===`${B}.lock`)throw new i("invalid-options");let Y=f0(B),H=f0(G),W={type:"api_key",key:G},V=(K)=>f0(K)===f0(W);async function j(){let K=await r7(Q,!0,X?.afterReadCheck);if(K===void 0)return;try{let M=JSON.parse(K);if(M.version!==1||M.provider!==J||M.authIdentity!==Y||M.placeholderIdentity!==H||M.entry!==null&&!d$(M.entry)||M.sha256!==f0(M.entry)||(M.entry===null?M.entryJson!==null:typeof M.entryJson!=="string"||f0(JSON.parse(M.entryJson))!==M.sha256))throw Error();return M}catch{throw new i("invalid-stash")}}async function D(K){let M,P,E=!1,F=()=>{if(P?.(),E)throw new i("lock-compromised")};try{if(I)await K0(Q$(B));else await a7(Q$(B),{recursive:!0,mode:448});let q=Date.now()+z,L=0;while(!M)try{let A=await s7(B,()=>{E=!0},X?.onRenew);M=A.release,P=A.assertFresh}catch(A){if(l$(A)!=="ELOCKED")throw A;let x=q-Date.now();if(x<=0)throw new i("lock-timeout");await CB(Math.min(Math.round(Math.min(10*2**L++,1000)*(1+Math.random())),x))}F();let S=await K(F);return F(),S}catch(q){if(q instanceof i||q instanceof d)throw q;throw new i("io")}finally{await M?.().catch(()=>{}),F()}}async function U(){let K=TB(await r7(B,!1,X?.afterReadCheck)??"{}",J),M=await j();return{auth:K,stash:M}}async function N(K){K(),await OB(Q),await SB(Q$(Q)),Z?.("stash-deleted")}return{inspect:()=>D(async()=>{let{auth:K,stash:M}=await U();return{slot:V(K.entry)?"placeholder":K.entry===null?"empty":!M||f0(K.entry)===M.sha256?"original":"foreign",stash:M?"valid":"missing"}}),enterVault:()=>D(async(K)=>{let{auth:M,stash:P}=await U();if(V(M.entry)){if(!P)throw new i("missing-stash");return}if(P&&f0(M.entry)!==P.sha256)throw new i("conflict");if(!P){if(I)await K0(Q$(Q));else{await a7(Q$(Q),{recursive:!0,mode:448});let F=await t7(Q$(Q));if(!F.isDirectory()||(F.mode&511)!==448)throw new i("unsafe-path")}let E={version:1,provider:J,authIdentity:Y,placeholderIdentity:H,entry:M.entry,entryJson:AB(M),sha256:f0(M.entry)};await S8(Q,JSON.stringify(E),K,X?.beforeRename),Z?.("stash-written")}await S8(B,o7(M,J,JSON.stringify(W)),K,X?.beforeRename),Z?.("auth-written")}),exitVault:()=>D(async(K)=>{let{auth:M,stash:P}=await U();if(!P){if(V(M.entry))throw new i("missing-stash");return"nothing-to-do"}if(V(M.entry))await S8(B,o7(M,J,P.entryJson),K,X?.beforeRename),Z?.("auth-written");else if(f0(M.entry)!==P.sha256)return"conflict";return await N(K),"restored"})}}import{getAgentDir as EB}from"@earendil-works/pi-coding-agent";var c$="openai-auth-vault-mode-not-a-credential",Z5="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.",X5="A Pi login was added while connected to the vault. Both that login and the stashed original are kept; neither was overwritten.";function J5($){return E8({authPath:$5(EB(),"auth.json"),provider:"openai-codex",stashPath:$5($Z($),"pi-openai-codex-login.json"),placeholderKey:c$})}function IB($){return{id:"pi-login",title:"Pi login",build:()=>{let Z=$(),X=Date.now(),J=s({limits:["primary","secondary"].flatMap((z)=>{let B=Z?.[z];return B?[{...B,kind:"reading",scope:"all",label:z,checkedAt:B.checkedAt??X}]:[]}),...Z?.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:X}}:{}}),G=y1(J,{now:X});return{lines:["Managed by Pi /login",...G.length>0?G:[C0(J,{now:X})]]}}}}function bB($,Z={}){let X=Z.beginAccountLogin??g4,J=Z.packageVersion??w7.version,G=N8({vault:$.vault,changed:Z.afterApply,...Z.vaultWait?{wait:Z.vaultWait}:{}}),z=M8({store:$.store(),vault:$.vault,login:{begin:(B)=>X({...B,version:J}),mainIdentity:async()=>$.mainIdentity()},quotaCheck:async(B)=>{if(B.length===1){let Y=$.store();for(let H of B)await Y.requestReading(H);await Y.pullsSettled();return}let Q=(await $.refreshAllQuota()).filter((Y)=>!Y.ok);if(Q.length>0)throw new B0("quota-check-failed",Q.map((Y)=>`${Y.account}: ${Y.error??"quota check failed"}`).join(`
114
- `))},extras:[IB(()=>$.mainQuota()),q8({getPin:async(B)=>p7(B),clearPin:async(B)=>u7(B)}),{...G,build:async(B)=>{let Q=await G.build(B),Y={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 B0("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"?[X5]:[]].join(`
116
- `)}},H=Q.actions??[];return{...Q,actions:[...H.map((W)=>W.id==="disconnect"&&$.disconnectVault?{...W,run:Y.run}:W),...$.vaultMode()&&$.disconnectVault&&!H.some((W)=>W.id==="disconnect")?[Y]:[]]}}}],afterApply:async()=>{return await Z.afterApply?.(),$.reload()}});return{command:z.command,open:async(B)=>{return await $.readAuthority(),z.open(B)},apply:async(B,Q)=>{return await $.readAuthority(),z.apply(B,Q)}}}async function xB($,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 H3(bB(X,Z),$.ui,{sessionId:$.sessionManager.getSessionId()})}function G5($,Z={}){$.registerCommand(V1,{description:"OpenAI accounts: add and manage accounts, quota, routing and limits",handler:(X,J)=>xB(J,Z)})}import{connect as kB}from"node:net";import{connect as yB}from"node:tls";var fB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",z5=["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 I8{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,G=X.port?Number(X.port):X.protocol==="https:"?443:80,z=`${X.pathname}${X.search}`,B=crypto.getRandomValues(new Uint8Array(16)),Q=Buffer.from(B).toString("base64"),Y=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Q+fB));this.expectedAccept=Buffer.from(new Uint8Array(Y)).toString("base64");let H={};for(let[j,D]of Object.entries(Z))H[j.toLowerCase()]=D;let W=[`GET ${z} HTTP/1.1`,`Host: ${J}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Q}`];for(let j of z5)if(H[j]!==void 0)W.push(`${gB(j)}: ${H[j]}`);for(let[j,D]of Object.entries(Z))if(!z5.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")W.push(`${j}: ${D}`);let V=`${W.join(`\r
111
+ The account is added when you finish.`,B=G.completion.then(async(Y)=>{if(Z&&await Z.authority()!=="local")throw new Q0("vault-local-action",v$);let H=await $.mainIdentity?.();if(Y.id===I1||Y.accountId&&H&&Y.accountId===H)throw m$.warn("account add rejected (main identity)",{id:Y.id}),new Q0("main-account",_7);return m$.info("account added",{id:Y.id}),R7(Y)});return{status:"pending",message:Q,completion:B}}}}function F8($){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),m$.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 L8($){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}`,J7(X.host,X.name,X.enrollment),...XZ(X.name,X.enrollment),...J?[X.accounts.length===0?e6(X.name,Z.grantReach()):`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:W1(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?.(),`${W1(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await Z.accept(G.routeId),await $.changed?.(),`${W1(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?.(),B8(Z,Q);return Z.waitForApproval($.wait).then(async(B)=>{await $.changed?.();let Y=B8(Z,B);G.notify(Y.text,Y.ok?"info":"warning")}).catch((B)=>{G.notify(`Connecting to the vault failed: ${B instanceof Error?B.message:String(B)}`,"error")}),{ok:!0,text:[...XZ(Z.name,Q),"Waiting for the approval; you are told here when it lands."].join(`
112
+ `)}}}]}}}}var I7=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],b7=["primary","secondary"];function _8($){let Z=new Set($.unavailableSections),X=(Y)=>({title:Y,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),J=[...$.extras??[]];if(Z.has("reset")){let Y={id:"reset",...X("Reset credits")},H=J.findIndex((V)=>V.id==="reset");if(H<0)J.unshift(Y);else J[H]=Y}let z={command:V1,title:M8,store:j8(T7(A7($.store,{...$.rowLocks?{rowLocks:$.rowLocks}:{}}))),...$.extraLocks?{extraLocks:$.extraLocks}:{},accounts:{...$.login?{login:E7($.login,$.vault)}:{},...$.protect?{protect:$.protect}:{},...$.describeIdentity?{describeIdentity:$.describeIdentity}:{}},quota:$.quotaCheck?{check:$.quotaCheck}:{},routing:{orderedVariants:I7,formerMainId:I1},limits:{labels:b7},...Z.has("cache")?{cache:X("Cache")}:$.cache?{cache:$.cache}:{},...Z.has("diagnostics")?{diagnostics:X("Diagnostics")}:$.diagnostics?{diagnostics:$.diagnostics}:{},extras:J,...$.logger?{logger:$.logger}:{},...$.now?{now:$.now}:{}},G=$.vault?D8(z,$.vault,{refresh:!$.readOnly,...$.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):_1(z),Q=$.vault?D8(z,$.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,B=(Y)=>{let{sessionId:H}=Y,V=Y.notify.bind(Y);return{...H!==void 0?{sessionId:H}:{},notify:V}};return{command:V1,async open(Y){let H=B(Y),V=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(V&&!V.migrated)return{command:V1,menu:q8(V.blockers)};let W=await G.open(H);return{...W,menu:N8(W.menu)}},async apply(Y,H){let V=B(H),W=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(W&&!W.migrated)return{command:V1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:q8(W.blockers)};if($.readOnly&&$.vault)return G.apply(Y,V);if($.readOnly||$.allowAction&&!$.allowAction(Y)||Z.has(Y.sectionId)){if(Q)return Q.apply(Y,V);return{...await G.open(V),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let j=await G.apply(Y,V);if(j.ok)await $.afterApply?.();return{...j,menu:N8(j.menu)}}}}function x7($,Z,X){let J=$.get(Z.sessionId),z=new Set(Z.validPinnedAccountIds);if(J&&!Z.excludeAccountIds.includes(J.accountId)&&W$(J,z,Z.wireAccountIdByAccount[J.accountId])){if(Z.persist){let Y=Z.quotaCheckedAtByAccount[J.accountId];X(Z.sessionId,{accountId:J.accountId,inputBytes:Z.requestBytes,...J.wireIdentity!==void 0?{wireIdentity:J.wireIdentity}:{},...Y!==void 0?{quotaCheckedAt:Y}:{}})}return{accountId:J.accountId}}let G=new Map(Object.entries(Z.quotaCheckedAtByAccount)),Q=CZ($,G,Z.sessionId),B=Z.select(Q);if(!B)return;if(Z.persist){let Y=Z.wireAccountIdByAccount[B.accountId];X(Z.sessionId,{accountId:B.accountId,inputBytes:Z.requestBytes,...Y!==void 0?{wireIdentity:Y}:{},...B.quotaCheckedAt!==void 0?{quotaCheckedAt:B.quotaCheckedAt}:{}})}return{accountId:B.accountId}}import{statSync as XQ}from"node:fs";var k7=30000,JQ=8,zQ=1800000;function y7($){return $.identity?`identity:${$.identity}`:`row:${$.id}`}function O8($){try{let Z=XQ($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function b1($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}function C8($,Z){try{return E0($,Z)}catch{return $}}function f7($,Z,X){let J=y7(Z);$.set(J,[...$.get(J)??[],{credentialEpoch:Z.credentialEpoch,identity:Z.identity,observation:X}].slice(-JQ))}function g7($,Z,X){let J=$;for(let z of Z.get(y7($))??[]){if(!(X-z.observation.checkedAt<=zQ)||z.credentialEpoch!==$.credentialEpoch||z.identity!==$.identity)continue;J={...J,quota:C8(J.quota,z.observation)}}return J}function h7($,Z,X,J){let z=a1($);if(typeof Z?.status==="number"||U3(Z)){let Q=I6({error:Z,now:X,refreshToken:$,...J?{previous:{message:"",checkedAt:X,nextRetryAt:J.nextRetryAt,retryCount:J.retryCount,tokenHash:J.tokenHash}}:{}});return{nextRetryAt:Q.nextRetryAt,tokenHash:z,retryCount:Q.retryCount}}return{nextRetryAt:X+k7,tokenHash:z,retryCount:J?.tokenHash===z?J.retryCount:0}}function v7($,Z,X,J){let z=new Map;for(let G of $){if(J(G,X))continue;let Q=Z.get(G.id);z.set(G.id,Q&&Q.nextRetryAt>X?Q.nextRetryAt:X+k7)}return z}var UK=n("quota");import{types as GQ}from"node:util";var QQ=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,BQ=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function u7($){return $.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,(Z,X,J)=>{if(X)return String.fromCharCode(Number.parseInt(X,16));return{b:"\b",f:"\f",n:`
113
+ `,r:"\r",t:"\t"}[J]??J??Z})}function YQ($,Z){if(!Z)return $;let X=$.split(Z).join("[credential]"),J=Z.replace(/\s/g,"");if(!J)return X;let z=X.replace(/\s/g,"");if(!z.includes(J))return X;let G=[];for(let Y=0;Y<X.length;Y++){let H=X[Y]??"";if(!/\s/.test(H))G.push(Y)}let Q=[],B=0;for(let Y=z.indexOf(J);Y>=0;Y=z.indexOf(J,Y+J.length)){let H=G[Y]??B,V=(G[Y+J.length-1]??H)+1;Q.push(X.slice(B,H),"[credential]"),B=V}return Q.length?Q.join("")+X.slice(B):X}function m7($,Z){let X=YQ($,Z);return y2(X).replaceAll("***REDACTED***","[credential]")}function U1($,Z){let X=m7($,Z),J=u7(X),z=m7(J,Z);return z===J?X:z}function w7($){let Z=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec($);if(!Z)return;let X=Z[3]??"",J=(Z[2]??"")+X,z=0;while(J[z]==="0")z++;if(z===J.length)return"0";let G=J.length;while(J[G-1]==="0")G--;let Q=Z[4]??"0",B=Q.startsWith("-")||Q.startsWith("+")?1:0;while(Q[B]==="0")B++;let Y=Q.slice(B)||"0";if(Y.length>16)return;let H=BigInt((Q.startsWith("-")?"-":"")+Y)-BigInt(X.length)+BigInt(J.length-G);return`${Z[1]}${J.slice(z,G)}e${H}`}function l7($,Z){let X=Z?w7(Z):void 0;return $.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(J)=>{if(!J.startsWith('"'))return Z&&(J===Z||X!==void 0&&w7(J)===X||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===Z)?'"[credential]"':J;let z=u7(J.slice(1,-1)),G=U1(z,Z);return G===z?J:JSON.stringify(G)})}function P8($,Z){let X=l7($,Z);try{return JSON.parse($),X}catch{return U1(X,Z)}}var HQ=16384,WQ=65536,VQ=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function UQ($){try{let Z=e(JSON.parse($),"request_id");if(typeof Z==="string")return Z;if(typeof Z!=="number")return;let X=0,J,z=!0,G=!1,Q;for(let B of $.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Y=B[0];if(Y==="{"||Y==="["){X++;continue}if(Y==="}"||Y==="]"){X--;continue}if(X!==1)continue;if(Y===","){z=!0,G=!1,J=void 0;continue}if(Y===":"){G=!0;continue}if(z&&Y.startsWith('"')){J=JSON.parse(Y),z=!1;continue}if(G&&J==="request_id"&&!Y.startsWith('"'))Q=Y;G=!1}return Q}catch{return}}function jQ($,Z){let X=P8($,Z);if(Buffer.byteLength(X,"utf8")<=WQ)return X;let J=VQ.flatMap((G)=>G.exec(X)?.[0]??[]);for(let G of["FreeUsageLimitError","GoUsageLimitError"])if(X.includes(G))J.push(G);let z={retry:J};try{let G=JSON.parse(X);if(e(G,"type")==="error")z.type="error";let Q=e(G,"error"),B={};for(let H of["code","type"]){let V=e(Q,H);if(typeof V==="string")B[H]=V.slice(0,256)}if(Object.keys(B).length)z.error=B;let Y={};for(let H of["workspace","limitName"]){let V=e(e(G,"metadata"),H);if(typeof V==="string")Y[H]=V.slice(0,256)}if(Object.keys(Y).length)z.metadata=Y}catch{}return JSON.stringify(z)}function QZ($){if(!$||typeof $!=="object")return!1;let Z=$;for(let X=0;Z&&X<16;X++){if(GQ.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function e($,Z){if(!QZ($))return;let X=Object.getOwnPropertyDescriptor($,Z);return X&&"value"in X?X.value:void 0}function w$($,Z){return U1($,Z).slice(0,HQ)}function Q$($,Z){let X=Object.getOwnPropertyDescriptor($,Z)?.get;if(!X)throw Error(`Missing native ${Z} accessor`);return X}var DQ=Q$(DOMException.prototype,"message"),KQ=Q$(DOMException.prototype,"name");function j1($,Z){let X=e($,"message"),J=e($,"name");if(QZ($)&&$ instanceof DOMException)try{X=DQ.call($),J=KQ.call($)}catch{}let z=Error(w$(typeof X==="string"?X:typeof $==="string"?$:"Provider request failed",Z));for(let W of Object.getOwnPropertyNames(z))if(W!=="message")Reflect.deleteProperty(z,W);Object.defineProperty(z,"name",{value:typeof J==="string"?w$(J,Z):"Error",configurable:!0,writable:!0});let G=(W,j,D)=>{let U=e(W,D);if(typeof U==="string"||typeof U==="number"&&Number.isFinite(U)||typeof U==="boolean")Object.defineProperty(j,D,{value:typeof U==="string"?w$(U,Z):U,enumerable:!0,configurable:!0,writable:!0})};for(let W of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=e($,W);if(typeof j==="number"&&Number.isFinite(j))G($,z,W)}for(let W of["code","type","isRetryable"])G($,z,W);for(let W of["error","data"]){let j=e($,W),D=Object.create(null);for(let N of["type","code","message","resets_at","resets_in_seconds"])G(j,D,N);let U=e(j,"error");if(QZ(U)){let N=Object.create(null);for(let K of["type","code","message","resets_at","resets_in_seconds"])G(U,N,K);D.error=N}if(Object.keys(D).length)Object.defineProperty(z,W,{value:D,enumerable:!0})}let Q=e($,"responseHeaders");if(Q&&typeof Q==="object"){let W={};for(let j of["retry-after-ms","retry-after"]){let D=e(Q,j);if(typeof D==="string")W[j]=w$(D,Z)}Object.defineProperty(z,"responseHeaders",{value:W,enumerable:!0})}let B=e($,"responseBody");if(typeof B==="string")Object.defineProperty(z,"responseBody",{value:jQ(B,Z),enumerable:!0});let Y=e($,"request_id"),H=e(Q,"x-request-id"),V=typeof Y==="string"?Y:typeof H==="string"?H:typeof B==="string"?UQ(P8(B,Z)):void 0;if(typeof V==="string")Object.defineProperty(z,"request_id",{value:w$(V,Z),enumerable:!0});for(let W of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(W);if(e($,j)===!0)Object.defineProperty(z,j,{value:!0})}return z}function qQ($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!QQ.test($)&&!BQ.test($)))return $;let X;try{X=JSON.parse($)}catch{return $}if(X?.type==="error"||X?.error||X?.response?.error)return l7($,Z);return $}var NQ=Q$(Response.prototype,"status"),MQ=Q$(Response.prototype,"statusText"),FQ=Q$(Response.prototype,"headers"),LQ=Q$(Response.prototype,"body"),_Q=Response.prototype.text,p7=Headers.prototype.entries;async function d7($,Z,X="http"){try{let D=function(U){let N=j&&U.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,N+U.slice(N.length).replace(/^data: ?([^\r\n]*)/gm,(K,M)=>K.slice(0,K.length-M.length)+qQ(M,Z))};if(!QZ($))throw Error("Invalid provider response");let J=NQ.call($),z=FQ.call($),G=LQ.call($),Q=new Headers;for(let[U,N]of p7.call(z))Q.append(U,N);let B={status:J,statusText:U1(MQ.call($),Z),headers:Q};if(J<200||J>299){for(let[N,K]of p7.call(z)){if(U1(N,Z?.toLowerCase())!==N){B.headers.delete(N);continue}try{B.headers.set(N,U1(K,Z))}catch{B.headers.delete(N)}}B.headers.delete("content-length");let U=await _Q.call($);return new Response(P8(U,Z),B)}if(!G||X==="http")return $;B.headers.delete("content-length");let Y=ReadableStream.prototype.getReader.call(G),H=new TextDecoder("utf-8",{ignoreBOM:!0}),V=new TextEncoder,W="",j=!0;return new Response(new ReadableStream({async pull(U){try{for(;;){let N=await Y.read();W+=H.decode(N.value,{stream:!N.done});let K=!1;for(;;){let M=/\r?\n\r?\n/.exec(W);if(!M)break;let P=M.index+M[0].length;U.enqueue(V.encode(D(W.slice(0,P)))),W=W.slice(P),K=!0}if(N.done){if(W)U.enqueue(V.encode(D(W)));U.close();return}if(K)return}}catch(N){U.error(j1(N,Z))}},async cancel(U){try{await Y.cancel(U)}catch(N){throw j1(N,Z)}finally{Y.releaseLock()}}}),B)}catch(J){throw j1(J,Z)}}var c7={name:"@cortexkit/pi-openai-auth",version:"1.2.0",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/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --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/common-auth":"^0.19.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.10.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.16.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};var BZ=new Map;function s7($){return BZ.get($)?.accountId}function i7($){return BZ.delete($)}function a7($){return x7(BZ,$,(Z,X)=>BZ.set(Z,X))}import{join as G5}from"node:path";import{createHash as IQ}from"node:crypto";import{constants as t7}from"node:fs";import{lstat as J5,mkdir as e7,open as z5,unlink as bQ}from"node:fs/promises";import{dirname as B$,resolve as $5}from"node:path";import{setTimeout as xQ}from"node:timers/promises";import{rmdirSync as CQ,statSync as r7,utimesSync as PQ}from"node:fs";import{mkdir as TQ,rmdir as AQ,stat as T8,utimes as SQ}from"node:fs/promises";var RQ=30000,YZ=1e4,EQ=3000,A8,p$=new Map;process.once("exit",()=>{for(let[$,Z]of p$)try{if(Z.renewedAt+YZ<Date.now())continue;let X=r7($);if(S8(X,Z)&&X.mtime.getTime()===Z.mtime)CQ($)}catch{}});function S8($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function u$($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function n7(){return Object.assign(Error("Pi auth lock held"),{code:"ELOCKED"})}async function R8($){try{await AQ($)}catch(Z){if(u$(Z)!=="ENOENT")throw Z}}async function E8($,Z){try{await TQ($)}catch(X){if(u$(X)!=="EEXIST")throw X;if(Z<=0)throw n7();let J;try{J=(await T8($)).mtime.getTime()}catch(z){if(u$(z)==="ENOENT")return E8($,0);throw z}if(!(J<Date.now()-Z))throw n7();return await R8($),E8($,0)}try{if(!A8){let z=new Date(Math.ceil(Date.now()/1000)*1000+5);await SQ($,z,z)}let X=await T8($),J=X.mtime.getTime();return A8??=J%1000===0?"s":"ms",{dev:X.dev,ino:X.ino,mtime:J}}catch(X){throw await R8($).catch(()=>{}),X}}async function o7($,Z,X){let J=`${$}.lock`,z=await E8(J,RQ),G=z.mtime,Q=Date.now(),B=!1,Y;p$.set(J,{...z,renewedAt:Q});function H(){if(B=!0,Y)clearTimeout(Y);p$.delete(J),Z()}function V(){if(!B&&Q+YZ<Date.now())H()}function W(U=EQ){if(B)return;Y=setTimeout(()=>{D()},U),Y.unref()}function j(U){if(B)return;if(u$(U)==="ENOENT"||Q+YZ<Date.now())H();else W(1000)}async function D(){if(V(),B)return;let U;try{U=r7(J)}catch(K){j(K);return}if(V(),B)return;if(!S8(U,z)||U.mtime.getTime()!==G){H();return}let N=new Date(A8==="s"?Math.ceil(Date.now()/1000)*1000:Date.now());try{PQ(J,N,N)}catch(K){j(K);return}if(V(),B)return;G=N.getTime(),Q=Date.now(),p$.set(J,{...z,mtime:G,renewedAt:Q}),W()}return X?.(async()=>{if(Y)clearTimeout(Y);await D()}),W(),{assertFresh:V,async release(){if(B)return;if(B=!0,Y)clearTimeout(Y);p$.delete(J);let U=()=>Q+YZ<Date.now();if(U()){H();return}let N;try{N=await T8(J)}catch(K){if(u$(K)!=="ENOENT")throw K;H();return}if(U()||!S8(N,z)||G!==N.mtime.getTime()){H();return}await R8(J)}}}class i extends Error{code;constructor($){super(`Pi slot: ${$}`);this.code=$,this.name="PiSlotError"}}function kQ($){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 B=Z,Y=0;while(Z<$.length){let V=$[Z];if(V==='"'){z();continue}if(V==="{"||V==="[")Y++;if(V==="}"||V==="]"){if(Y===0)break;Y--}if(V===","&&Y===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:B,length:H-B}}),J(),$[Z]==="}")break;Z++,J()}return X}function d$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function b8($){if(Array.isArray($))return`[${$.map(b8).join(",")}]`;if(d$($))return`{${Object.keys($).sort().map((Z)=>`${JSON.stringify(Z)}:${b8($[Z])}`).join(",")}}`;return JSON.stringify($)}function f0($){return IQ("sha256").update(b8($)).digest("hex")}function l$($){return d$($)?$.code:void 0}async function Z5($,Z=!1,X){if(I)try{await X?.($);let z=await IZ($,!0),G=z.toString("utf8");if(!z.equals(Buffer.from(G)))throw new i(Z?"invalid-stash":"invalid-auth");return G}catch(z){if(l$(z)==="ENOENT")return;throw z}let J;try{J=await z5($,t7.O_RDONLY|t7.O_NOFOLLOW);let z=await J.stat();if(!z.isFile()||Z&&(z.mode&511)!==384)throw new i("unsafe-path");await X?.($);let G=await J5($);if(!G.isFile()||G.dev!==z.dev||G.ino!==z.ino)throw new i("unsafe-path");let Q=await J.readFile(),B=Q.toString("utf8");if(!Q.equals(Buffer.from(B)))throw new i(Z?"invalid-stash":"invalid-auth");return B}catch(z){if(l$(z)==="ENOENT"&&!J)return;if(l$(z)==="ELOOP"||l$(z)==="ENOENT")throw new i("unsafe-path");throw z}finally{await J?.close()}}function yQ($,Z){try{let X=JSON.parse($);if(!d$(X))throw Error();let J=kQ($),z=J.children,G=z.map((Y)=>Y.key);if(new Set(G).size!==G.length)throw Error();let Q=z.find((Y)=>Y.key===Z),B=Q?X[Z]:null;if(B!==null&&!d$(B))throw Error();if(Q&&B===null)throw Error();return{text:$,root:J,property:Q,entry:B}}catch{throw new i("invalid-auth")}}function fQ($){let Z=$.property?.value;return Z?$.text.slice(Z.offset,Z.offset+Z.length):null}function X5($,Z,X){let{text:J,root:z,property:G}=$,Q=z.children??[];if(G){let H=G.value;if(!H)throw new i("invalid-auth");if(X!==null)return J.slice(0,H.offset)+X+J.slice(H.offset+H.length);let V=Q.indexOf(G),W=Q[V-1],j=Q[V+1],D=W?W.offset+W.length:G.offset,U=!W&&j?j.offset:G.offset+G.length;return J.slice(0,D)+J.slice(U)}if(X===null)return J;let B=Q.at(-1),Y=B?B.offset+B.length:z.offset+1;return`${J.slice(0,Y)}${B?",":""}${JSON.stringify(Z)}:${X}${J.slice(Y)}`}async function gQ($){if(I)return;let Z=await z5($,"r");try{await Z.sync()}finally{await Z.close()}}async function I8($,Z,X,J){await F0($,null,{serialize:()=>Z,durable:!0,durability:I?"file-only-on-windows":void 0,beforeRename:async()=>{await J?.($),X()}})}function x8($){return hQ($)}function hQ($,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 i("invalid-options");let Q=$5($.authPath),B=$5($.stashPath);if(Q===B||B===`${Q}.lock`)throw new i("invalid-options");let Y=f0(Q),H=f0(z),V={type:"api_key",key:z},W=(K)=>f0(K)===f0(V);async function j(){let K=await Z5(B,!0,X?.afterReadCheck);if(K===void 0)return;try{let M=JSON.parse(K);if(M.version!==1||M.provider!==J||M.authIdentity!==Y||M.placeholderIdentity!==H||M.entry!==null&&!d$(M.entry)||M.sha256!==f0(M.entry)||(M.entry===null?M.entryJson!==null:typeof M.entryJson!=="string"||f0(JSON.parse(M.entryJson))!==M.sha256))throw Error();return M}catch{throw new i("invalid-stash")}}async function D(K){let M,P,E=!1,F=()=>{if(P?.(),E)throw new i("lock-compromised")};try{if(I)await K0(B$(Q));else await e7(B$(Q),{recursive:!0,mode:448});let q=Date.now()+G,L=0;while(!M)try{let A=await o7(Q,()=>{E=!0},X?.onRenew);M=A.release,P=A.assertFresh}catch(A){if(l$(A)!=="ELOCKED")throw A;let x=q-Date.now();if(x<=0)throw new i("lock-timeout");await xQ(Math.min(Math.round(Math.min(10*2**L++,1000)*(1+Math.random())),x))}F();let S=await K(F);return F(),S}catch(q){if(q instanceof i||q instanceof d)throw q;throw new i("io")}finally{await M?.().catch(()=>{}),F()}}async function U(){let K=yQ(await Z5(Q,!1,X?.afterReadCheck)??"{}",J),M=await j();return{auth:K,stash:M}}async function N(K){K(),await bQ(B),await gQ(B$(B)),Z?.("stash-deleted")}return{inspect:()=>D(async()=>{let{auth:K,stash:M}=await U();return{slot:W(K.entry)?"placeholder":K.entry===null?"empty":!M||f0(K.entry)===M.sha256?"original":"foreign",stash:M?"valid":"missing"}}),enterVault:()=>D(async(K)=>{let{auth:M,stash:P}=await U();if(W(M.entry)){if(!P)throw new i("missing-stash");return}if(P&&f0(M.entry)!==P.sha256)throw new i("conflict");if(!P){if(I)await K0(B$(B));else{await e7(B$(B),{recursive:!0,mode:448});let F=await J5(B$(B));if(!F.isDirectory()||(F.mode&511)!==448)throw new i("unsafe-path")}let E={version:1,provider:J,authIdentity:Y,placeholderIdentity:H,entry:M.entry,entryJson:fQ(M),sha256:f0(M.entry)};await I8(B,JSON.stringify(E),K,X?.beforeRename),Z?.("stash-written")}await I8(Q,X5(M,J,JSON.stringify(V)),K,X?.beforeRename),Z?.("auth-written")}),exitVault:()=>D(async(K)=>{let{auth:M,stash:P}=await U();if(!P){if(W(M.entry))throw new i("missing-stash");return"nothing-to-do"}if(W(M.entry))await I8(Q,X5(M,J,P.entryJson),K,X?.beforeRename),Z?.("auth-written");else if(f0(M.entry)!==P.sha256)return"conflict";return await N(K),"restored"})}}import{getAgentDir as vQ}from"@earendil-works/pi-coding-agent";var c$="openai-auth-vault-mode-not-a-credential",Q5="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.",B5="A Pi login was added while connected to the vault. Both that login and the stashed original are kept; neither was overwritten.";function Y5($){return x8({authPath:G5(vQ(),"auth.json"),provider:"openai-codex",stashPath:G5($Z($),"pi-openai-codex-login.json"),placeholderKey:c$})}function mQ($){return{id:"pi-login",title:"Pi login",build:()=>{let Z=$(),X=Date.now(),J=s({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=y1(J,{now:X});return{lines:["Managed by Pi /login",...z.length>0?z:[C0(J,{now:X})]]}}}}function wQ($,Z={}){let X=Z.beginAccountLogin??p2,J=Z.packageVersion??c7.version,z=L8({vault:$.vault,changed:Z.afterApply,...Z.vaultWait?{wait:Z.vaultWait}:{}}),G=_8({store:$.store(),vault:$.vault,login:{begin:(Q)=>X({...Q,version:J}),mainIdentity:async()=>$.mainIdentity()},quotaCheck:async(Q)=>{if(Q.length===1){let Y=$.store();for(let H of Q)await Y.requestReading(H);await Y.pullsSettled();return}let B=(await $.refreshAllQuota()).filter((Y)=>!Y.ok);if(B.length>0)throw new Q0("quota-check-failed",B.map((Y)=>`${Y.account}: ${Y.error??"quota check failed"}`).join(`
114
+ `))},extras:[mQ(()=>$.mainQuota()),F8({getPin:async(Q)=>s7(Q),clearPin:async(Q)=>i7(Q)}),{...z,build:async(Q)=>{let B=await z.build(Q),Y={id:"disconnect",label:"Disconnect",confirm:"Disconnect this Pi host from the vault and restore its original login?",run:async()=>{let V;try{V=await $.disconnectVault?.()}catch{let W=!1;try{await Z.afterApply?.()}catch{W=!0}let j=await $.readAuthority();throw new Q0("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.",...W?["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.`,...V==="conflict"?[B5]:[]].join(`
116
+ `)}},H=B.actions??[];return{...B,actions:[...H.map((V)=>V.id==="disconnect"&&$.disconnectVault?{...V,run:Y.run}:V),...$.vaultMode()&&$.disconnectVault&&!H.some((V)=>V.id==="disconnect")?[Y]:[]]}}}],afterApply:async()=>{return await Z.afterApply?.(),$.reload()}});return{command:G.command,open:async(Q)=>{return await $.readAuthority(),G.open(Q)},apply:async(Q,B)=>{return await $.readAuthority(),G.apply(Q,B)}}}async function pQ($,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 W3(wQ(X,Z),$.ui,{sessionId:$.sessionManager.getSessionId()})}function H5($,Z={}){$.registerCommand(V1,{description:"OpenAI accounts: add and manage accounts, quota, routing and limits",handler:(X,J)=>pQ(J,Z)})}import{connect as uQ}from"node:net";import{connect as lQ}from"node:tls";var dQ="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",W5=["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 k8{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)),B=Buffer.from(Q).toString("base64"),Y=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(B+dQ));this.expectedAccept=Buffer.from(new Uint8Array(Y)).toString("base64");let H={};for(let[j,D]of Object.entries(Z))H[j.toLowerCase()]=D;let V=[`GET ${G} HTTP/1.1`,`Host: ${J}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${B}`];for(let j of W5)if(H[j]!==void 0)V.push(`${cQ(j)}: ${H[j]}`);for(let[j,D]of Object.entries(Z))if(!W5.includes(j.toLowerCase())&&j.toLowerCase()!=="content-length")V.push(`${j}: ${D}`);let W=`${V.join(`\r
117
117
  `)}\r
118
118
  \r
119
- `;try{this.log("connect_start",{host:J,port:G,tls:X.protocol==="https:"});let j=()=>{this.socket?.write(V)},D=X.protocol==="https:"?yB({host:J,port:G,servername:J},j):kB({host:J,port:G},j);this.socket=D,D.on("data",(U)=>{this.onData(typeof U==="string"?Buffer.from(U,"binary"):U)}),D.on("error",(U)=>{this.readyState=3;let N=U instanceof Error?U.message:String(U);this.log("socket_error",{message:N}),this.emit("error",{message:N})}),D.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=hB(this.rxBuffer,$),!this.handshakeDone){let Z=Buffer.from(this.rxBuffer).toString("latin1"),X=Z.indexOf(`\r
119
+ `;try{this.log("connect_start",{host:J,port:z,tls:X.protocol==="https:"});let j=()=>{this.socket?.write(W)},D=X.protocol==="https:"?lQ({host:J,port:z,servername:J},j):uQ({host:J,port:z},j);this.socket=D,D.on("data",(U)=>{this.onData(typeof U==="string"?Buffer.from(U,"binary"):U)}),D.on("error",(U)=>{this.readyState=3;let N=U instanceof Error?U.message:String(U);this.log("socket_error",{message:N}),this.emit("error",{message:N})}),D.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=sQ(this.rxBuffer,$),!this.handshakeDone){let Z=Buffer.from(this.rxBuffer).toString("latin1"),X=Z.indexOf(`\r
120
120
  \r
121
- `);if(X===-1)return;let J=Z.slice(0,X),G=J.split(`\r
122
- `)[0]??"",z=J.match(/sec-websocket-accept:\s*(\S+)/i);if(!G.includes(" 101")){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:G}),this.emit("error",{message:`WS upgrade failed: ${G}`});return}if(!z||z[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:G}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:G}),this.emit("open",{})}this.drainFrames()}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let Z=$[0],X=$[1],J=(Z&128)!==0,G=Z&15,z=(X&128)!==0,B=X&127,Q=2;if(B===126){if($.length<4)return;B=$[2]<<8|$[3],Q=4}else if(B===127){if($.length<10)return;B=0;for(let H=0;H<8;H++)B=B*256+$[2+H];Q=10}if(z)Q+=4;if($.length<Q+B)return;let Y=$.slice(Q,Q+B);this.rxBuffer=$.slice(Q+B),this.handleFrame(J,G,Y)}}handleFrame($,Z,X){if(Z===9){this.writeFrame(10,X);return}if(Z===10)return;if(Z===8){let G=1005,z="";if(X.length>=2)G=X[0]<<8|X[1],z=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:G,reason:z});return}if(Z===1||Z===2)this.fragOpcode=Z,this.fragChunks=[X];else if(Z===0)this.fragChunks.push(X);if(!$)return;let J=vB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let G=Buffer.from(J).toString("utf-8");this.emit("message",{data:G})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,Z){let X=Z.length,J=crypto.getRandomValues(new Uint8Array(4)),G;if(X<126)G=[128|$,128|X];else if(X<65536)G=[128|$,254,X>>8&255,X&255];else{G=[128|$,255];for(let Q=7;Q>=0;Q--)G.push(X/2**(8*Q)&255)}let z=new Uint8Array(X);for(let Q=0;Q<X;Q++)z[Q]=Z[Q]^J[Q%4];let B=new Uint8Array(G.length+4+X);B.set(G,0),B.set(J,G.length),B.set(z,G.length+4);try{this.socket?.write(B)}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 gB($){return $}function hB($,Z){let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function vB($){let Z=0;for(let G of $)Z+=G.length;let X=new Uint8Array(Z),J=0;for(let G of $)X.set(G,J),J+=G.length;return X}import{statSync as aB}from"node:fs";var mB=15000;function s$($){if(!$)return;let Z=r1($);return Z?o1(Z):void 0}class b8{deps;now;token;identity;quota;snapshot;firstPolledFor;inflight;lastPull;constructor($){this.deps=$,this.now=$.now??Date.now}observeToken($){if(!$)return;let Z=s$($);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 $=G$(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??mB))return this.inflight;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 G=J instanceof Error?J.message:String(J);return this.deps.log?.warn("Pi login quota poll failed",{error:G}),{ok:!1,error:G}}})();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=S0($,this.now(),X);if(J)this.merge(J);return!0}owns($){if(!this.token)return!1;let Z=s$($);return Z&&this.identity?Z===this.identity:$===this.token}merge($){try{let Z=E0(this.quota,$);if(Q0(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 wB}from"node:os";import{join as B5}from"node:path";function pB(){return process.env.PI_AGENT_DIR?.trim()||B5(wB(),".pi","agent")}function Q5(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||B5(pB(),y6)}function uB($=Q5()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||K3($)}function Y5($=Q5()){return{configPath:$,statePath:uB($)}}function x8($){return $!==void 0&&($.vault===!0||!!$.token)}function H5($,Z,X,J,G=new Set){return $.filter((z)=>{if(!z.candidate||z.type!=="oauth")return!1;if(z.credential?.type!=="oauth")return!1;if(k0(z.credential))return!1;if(z.id===R0)return!1;if(J&&z.identity===J)return!1;if(z.identity!==void 0&&G.has(z.identity))return!1;return t6(G$(z.quota),Z,X)})}function HZ($,Z){let X=$.now(),J=G7(Z,$.storage,X);return{rows:Z.map((z)=>({id:z.id,kind:z.kind??"oauth",...Q0(z.quota)?{quota:z.quota}:{}})),now:X,rateLimitMarks:new Map,refreshBackoff:$.refreshBackoff(Z),killswitch:J,requestPull:$.requestPull}}async function W5($){let Z=$.accounts(),X=Q7(HZ($,Z),$.firstReadingWaitMs);if(X)await X,Z=$.accounts();if($.mode==="sticky-balanced"&&$.sessionId){let J=await dB($,Z,$.sessionId);if(J)return J}return lB($,Z)}async function lB($,Z){let X=B7($.mode),J=H7({...HZ($,Z),placement:X,mainId:$.mainId});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 G=new Map(Z.map((H)=>[H.id,H])),z=v2($.storage),B=[],Q=new Set,Y;for(;;){let H=_Z(J.order.filter((j)=>!Q.has(j)),B,z);if(H===void 0)break;let W=G.get(H);if(!x8(W)){Q.add(H);continue}let V=await $.send(W);if(!V){Q.add(H);continue}Y={attempt:V,accountId:W.id},B.push({id:W.id,...V.status!==void 0?{status:V.status}:{}})}if(Y)return{kind:"sent",...Y};return{kind:"blocked",block:{reason:"no-credential"}}}async function dB($,Z,X){let J=$.requestBytes,G=new Map(Z.map((K)=>[K.id,K])),z=HZ($,Z),B=H8(z),Q={requestBytes:J,reservePercent:(K)=>H1($.storage,K===R0?void 0:K),resetCredits:()=>{return},onEmptyWeightedSet:()=>{$.log?.debug("sticky routing: no fresh weighted candidates; using configured order")}},Y=(K,M,P)=>(E,F)=>{let q=new Set(E);return $.placePin({sessionId:X,requestBytes:J,validPinnedAccountIds:K.rows.map((L)=>L.id).filter((L)=>!M.excluded.has(L)),excludeAccountIds:E,quotaCheckedAtByAccount:Object.fromEntries(K.rows.map((L)=>[L.id,M.projections.get(L.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(P.map((L)=>[L.id,L.identity])),select:(L)=>V7(K,Q,q,L),persist:F})},H=Y(z,B,Z),W=H([],!0);if(!W)return;let V=W.accountId,j=(K)=>{let M=H([V],!0);if(!M)return!1;return $.log?.debug("sticky routing: migrated session pin",{fromAccountId:V,toAccountId:M.accountId,reason:K}),V=M.accountId,!0},D=U7(z,Q,V);if(D.kind==="none")return;if(D.kind==="move"){if(!j(D.reason)&&D.reason==="killswitch")return}else if(D.kind==="detour"){let K=H([V],!1);if(!K)return;$.log?.debug("sticky routing: pinned account awaits a quota reading",{pinnedAccountId:V,servedAccountId:K.accountId}),V=K.accountId}let U=G.get(V);if(!x8(U))return;let N=await $.send(U);if(!N)return;if(N.status===401||N.status===403||N.status===429){let K=$.accounts();z=HZ($,K),B=H8(z),H=Y(z,B,K);let M=j7(z,B,V,N.status);if(M.action==="migrate"){let P=V;if(j(M.reason)&&V!==P){let E=K.find((q)=>q.id===V),F=x8(E)?await $.send(E):void 0;if(E&&F)N=F,U=E;else V=P}}}return{kind:"sent",attempt:N,accountId:U.id}}var cB=500,sB=15000;function WZ($,Z,X){return new Promise((J,G)=>{let z=setTimeout(()=>J(X()),Z);z.unref?.(),$.then((B)=>{clearTimeout(z),J(B)},(B)=>{clearTimeout(z),G(B)})})}var iB={info(){},warn(){}};class k8{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;quotaPulls=new Map;polled=new Set;polledSnapshots=new Map;pollOutcomes=new Map;disposed=!1;constructor($){this.deps=$,this.now=$.now??Date.now,this.log=$.log??iB}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 WZ(this.startRead($),this.deps.readBudgetMs??cB,()=>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}|${F8($.configPath)}|${F8($.statePath)}`}storeFor($){if(this.store?.configPath===$.configPath)return this.store.store;let Z=J3({provider:"openai",configPath:$.configPath,statePath:$.statePath,quota:qZ,now:this.now,pull:(X)=>this.coalescedPull(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 G=()=>{if(this.inflightRead===J)this.inflightRead=void 0};return X.then(G,G),X}async read($,Z){let X=this.deps.paths(),J;try{J=await this.storeFor(X).read()}catch(z){return this.log.warn("account pool read failed",{error:z instanceof Error?z.message:String(z)}),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 G=J.status==="ready"?{active:!0,rows:J.rows,key:$,readAt:Z}:{active:!1,rows:[],key:$,readAt:Z};if(Z>=this.snapshot.readAt)this.snapshot={...G,rows:this.withLocalState(G.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,G=this.rotated.get(X.id);if(G?.type==="oauth"&&X.credential?.type==="oauth"){let z=X.credential.lastRefreshedAt??0,B=G.lastRefreshedAt??0;if(z>=B)this.rotated.delete(X.id);else J={...J,credential:G}}return b7(J,this.pending,Z)})}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??sB))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set($,X);let G=this.storeFor(this.deps.paths());return G.requestReading($),G.pullsSettled()}coalescedPull($){let Z=JSON.stringify([this.deps.paths().configPath,$.id,$.credentialEpoch,$.identity]),X=this.quotaPulls.get(Z);if(X)return X;let J=this.pull($).finally(()=>this.quotaPulls.delete(Z));return this.quotaPulls.set(Z,J),J}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){I7(this.pending,$,Z),this.replaceRow($.id,(X)=>({...X,quota:L8(X.quota,Z),needsFirstReading:!1}))}recordSnapshot($,Z,X,J){if(!this.snapshot.active||this.disposed||this.setAside())return;let G=this.snapshot.rows.find((j)=>j.id===$);if(G?.type!=="oauth")return;let z=s$(X);if(!(z&&G.identity?z===G.identity:b1(G)?.access===X))return;let Q=S0(Z,this.now(),J);if(!Q)return;if(this.applyObservation(G,Q),G.credentialEpoch===void 0)return;let Y={credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}},H=this.storeFor(this.deps.paths()),V=(this.writes.get(G.id)??Promise.resolve()).then(async()=>{if(this.disposed||(this.deps.vaultAuthority?await this.deps.vaultAuthority()!=="local":this.setAside()))return;return H.recordQuota(G.id,Y,Q)}).catch((j)=>{this.log.warn("pool quota not recorded",{rowId:G.id,error:j instanceof Error?j.message:String(j)})});this.writes.set(G.id,V),V.finally(()=>{if(this.writes.get(G.id)===V)this.writes.delete(G.id)})}rowForToken($){let Z=s$($);return this.snapshot.rows.find((X)=>Z&&X.identity?X.identity===Z:b1(X)?.access===$)}refreshDueTokens($,Z){if(this.setAside())return Promise.resolve();let X=this.now(),J=Z8(Z),G=[];for(let z of $){if(!z.candidate)continue;let B=b1(z);if(!B)continue;let Q=(B.expires??0)-X;if(!(!B.access||!B.expires||Q<=J)||this.refreshBackedOff(z,X))continue;G.push(this.refresh(z.id))}return Promise.all(G).then(()=>{})}refreshBackedOff($,Z=this.now()){let X=b1($);if(!X)return!1;let J=this.backoff.get($.id);return Boolean(J&&J.tokenHash===a1(X.refresh)&&J.nextRetryAt>Z)}usableToken($,Z=this.now()){if(this.setAside())return;let X=b1($);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?b1(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($,(G)=>({...G,credential:J.credential,...J.identity!==void 0&&G.identity===void 0?{identity:J.identity}:{}}));return}if(J.status==="identity-contradicted"){this.backoff.delete($),this.replaceRow($,(G)=>({...G,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;this.backoff.set($,x7(Z,X,this.now(),this.backoff.get($)))}refreshBackoffFor($){return k7($,this.backoff,this.now(),(Z,X)=>this.usableToken(Z,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 nB=Q8,rB=500,oB=64;function tB(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function i$($,Z){return{type:"error",reason:"error",error:{role:"assistant",content:[],api:$.api,provider:$.provider,model:$.id,usage:tB(),stopReason:"error",errorMessage:Z,timestamp:Date.now()}}}function eB($){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 ${z7} 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 $Q($){for(let[Z,X]of Object.entries($)){if(Z.toLowerCase()!=="authorization")continue;return/^Bearer\s+(.+)$/i.exec(X.trim())?.[1]}return}class y8{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??Y5;let Z=()=>$.fetchImpl??globalThis.fetch;this.main=new b8({now:this.now,poll:async(X,J)=>{if(await this.readAuthority()!=="local")throw Error("Pi login quota polling is disabled while enrolled");let G=await Z$({accessToken:X,fetchImpl:Z(),now:this.now,...J?{accountId:J}:{},accountKey:R0}),z=S0(G,this.now(),!0);if(!z)throw Error("the quota poll returned no reading");return{snapshot:G,observation:z}}}),this.pool=new k8({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 S2({refreshToken:X.refresh,fetchImpl:Z(),now:this.now}),G=S$({id_token:"",access_token:J.access,refresh_token:J.refresh});return{...J,...G?{identity:G}:{}}},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 G=await Z$({accessToken:J.access,fetchImpl:Z(),now:this.now,...X.identity?{accountId:X.identity}:{},accountKey:X.id}),z=S0(G,this.now(),!0);if(!z)throw Error("the quota poll returned no reading");return{snapshot:G,observation:z}}}),this.vault=$.vault??new J8({host:"pi",stateDir:$Z(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??J5(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 G=await this.readAuthority()!=="local";if(G!==Z){if(G)await this.vaultSlot().enterVault();else await this.vaultSlot().exitVault();this.slotNeedsRefresh=!0}this.slotVaultMode=G}async start(){return await this.readAuthority(),this.vault.start(),this.pool.load().then(()=>{},()=>{})}async storage(){let $=this.paths(),Z;try{let X=aB($.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=e3($).then((J)=>{return this.storageCache={key:Z,storage:J},J},()=>this.storageCache?.storage??null);this.storageRead={key:Z,promise:X}}return WZ(this.storageRead.promise,this.deps.readBudgetMs??rB,()=>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(),G=this.vault.identities();if(X&&!(J!==void 0&&G.has(J))){let Q=this.main.quotaMap();Z.push({id:R0,token:X,...J?{identity:J}:{},...Q?{quota:Q}:{}})}let z=this.pool.peek(),B=this.now();if(z.active)for(let Q of H5(z.rows,$,B,J,G))Z.push({id:Q.id,token:this.pool.usableToken(Q,B),...Q.identity?{identity:Q.identity}:{},...Q.quota!==void 0?{quota:Q.quota}:{}})}poolRowById($){return this.pool.peek().rows.find((Z)=>Z.id===$)}requestPull($){if($===R0)return this.main.requestReading();if(this.vault.owns($))return this.vault.requestReading($);return this.pool.requestReading($)}rememberVaultToken($,Z){this.vaultTokens.delete($),this.vaultTokens.set($,Z);while(this.vaultTokens.size>oB){let X=this.vaultTokens.keys().next().value;if(X===void 0)break;this.vaultTokens.delete(X)}}recordHeaders($,Z,X){let J=new Headers(X),G=d4(J),z=c4(J),B=this.vaultTokens.get(Z);if(B?.id===$)this.vault.recordSnapshot($,G,z,B.receipt);else if($===R0)this.main.record(G,Z,z);else this.pool.recordSnapshot($,G,Z,z)}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=$Q($);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,s4(J))}stream($,Z,X){let J=this.deps.createStream(),G=this.deps.installWebSocket?.()??(()=>{});return(async()=>{try{if(await this.readAuthority()!=="local"&&X?.apiKey!==c$){J.push(i$($,Z5));return}let z=await this.route($,Z,X);if(z.kind==="blocked"){J.push(i$($,z.refusal?r2[z.refusal]:eB(z.block)));return}if(z.head)J.push(z.head);if(z.rest)for(;;){let B=await z.rest.next();if(B.done)break;J.push(B.value)}}catch(z){J.push(i$($,j1(z,X?.apiKey).message))}finally{J.end(),G()}})(),J}async route($,Z,X){let J=await this.storage(),G=await this.readAuthority()!=="local";if(G)await WZ(this.vault.awaitRequestRoster().then(()=>!0),ZZ,()=>!1);else this.main.observeToken(X?.apiKey),await this.pool.current(),this.pool.refreshDueTokens(this.pool.peek().rows,J);let z=J?.routing?.mode??"main-first",B=!1,Q=0,H=await(()=>W5({accounts:()=>{let W=this.accounts(J);return Q=W.length,W},storage:J,mode:z,mainId:G?JZ(this.vault.routes()):void 0,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),firstReadingWaitMs:this.deps.firstReadingWaitMs??nB,send:(W)=>W.vault?this.vaultAttempt($,Z,X,W.id).then((V)=>{if(!V)B=!0;return V}):W.token?this.attempt($,Z,X,W.id,W.token):Promise.resolve(void 0),placePin:l7}))();if(H.kind==="blocked"){if(G&&(Q===0||B))return{...H,refusal:B?"vault-refused":o2(this.vault)};if(G&&H.block.reason==="no-credential")return{...H,refusal:"vault-empty"};return H}return{kind:"sent",...H.attempt}}async attempt($,Z,X,J,G){let z,B;try{let W=X?.fetch??globalThis.fetch;B=this.deps.streamSimple($,Z,{...X,apiKey:G,fetch:Object.assign(async(V,j)=>{try{return await m7(await W(V,j),G,"event-stream")}catch(D){throw j1(D,G)}},W),onResponse:async(V,j)=>{z=V.status,this.recordHeaders(J,G,V.headers),await X?.onResponse?.(V,j)}})}catch(W){return{head:i$($,j1(W,G).message),rest:void 0}}let Q=async function*(){try{for await(let W of B){if(W.type==="error")W.error.errorMessage=U1(W.error.errorMessage??"",G);yield W}}catch(W){yield i$($,j1(W,G).message)}}(),Y=await Q.next(),H=Y.done?void 0:Y.value;return{...z!==void 0?{status:z}:{},head:H,rest:Y.done||H?.type==="error"?void 0:Q}}async vaultAttempt($,Z,X,J){let G;return await this.vault.send(J,async(B,Q)=>{return this.rememberVaultToken(B,{id:J,receipt:{credentialId:Q.credentialId,accountIdentitySource:Q.accountIdentitySource,...Q.accountIdentity!==void 0?{accountIdentity:Q.accountIdentity}:{},...Q.expectedAccountIdentity!==void 0?{expectedAccountIdentity:Q.expectedAccountIdentity}:{}}}),G=await this.attempt($,Z,X,J,B),new Response(null,{status:G.status??200})},{site:"model",...X?.signal?{signal:X.signal}:{}})?G: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((z)=>({account:z.id,ok:z.ok,...z.error?{error:z.error}:{}}));let[Z,X,J]=await Promise.all([this.main.currentToken()?this.main.pollNow():void 0,this.pool.pollRows($),this.vault.pollStale(0)]),G=[];if(Z)G.push({account:R0,ok:Z.ok,...Z.error?{error:Z.error}:{}});for(let z of[...X,...J])G.push({account:z.id,ok:z.ok,...z.error?{error:z.error}:{}});return G}}}}var n$="https://chatgpt.com/backend-api",U5;class g8 extends I8{constructor($,Z){let X=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),X);let J=U5;if(J)this.addEventListener("message",(G)=>{let z=G?.data;if(typeof z==="string")J(X,z)})}}var a$=0,f8;function JQ(){let $=globalThis;if(a$===0)f8=$.WebSocket,$.WebSocket=g8;return a$++,()=>{if(a$=Math.max(0,a$-1),a$===0){if($.WebSocket===g8)$.WebSocket=f8;f8=void 0}}}var GQ=[{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:n$,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:n$,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:n$,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:n$,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:128000}],zQ=5000;function V5($,Z){$.registerProvider("openai-codex",{baseUrl:n$,api:"openai-codex-responses",name:"OpenAI Codex (CortexKit)",...Z.vaultMode()?{apiKey:c$}:{},models:GQ,streamSimple:(X,J,G)=>Z.stream(X,J,G)})}function BQ(){return new y8({streamSimple:($,Z,X)=>XQ($,Z,X),createStream:ZQ,installWebSocket:JQ})}async function QQ($){let Z=BQ();U5=(B,Q)=>Z.observeWebSocketMessage(B,Q);let X,J,G=(B=!0)=>Z.syncVaultSlot(X?async()=>{V5($,Z),await X?.()}:void 0,B),z=()=>{G(!1).catch(()=>{J?.("Pi could not load the vault login slot. Reopen the session or disconnect in /openai.","error")})};if(G5($,{pool:Z.commandSupport(),afterApply:G,onContext:(B)=>{X=()=>B.modelRegistry.refresh(),J=(Q,Y)=>B.ui.notify(Q,Y)}}),await G().catch(()=>{}),V5($,Z),setInterval(z,zQ).unref?.(),typeof $.on==="function")$.on("session_start",async(B,Q)=>{X=()=>Q.modelRegistry.refresh(),J=(Y,H)=>Q.ui.notify(Y,H),Z.start();try{await G()}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 Q.modelRegistry.getApiKeyForProvider("openai-codex"))}catch{}})}export{V5 as registerPiProvider,JQ as installRawCodexWebSocket,QQ as default,BQ as createPiOpenAIRuntime};
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,B=2;if(Q===126){if($.length<4)return;Q=$[2]<<8|$[3],B=4}else if(Q===127){if($.length<10)return;Q=0;for(let H=0;H<8;H++)Q=Q*256+$[2+H];B=10}if(G)B+=4;if($.length<B+Q)return;let Y=$.slice(B,B+Q);this.rxBuffer=$.slice(B+Q),this.handleFrame(J,z,Y)}}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=iQ(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 B=7;B>=0;B--)z.push(X/2**(8*B)&255)}let G=new Uint8Array(X);for(let B=0;B<X;B++)G[B]=Z[B]^J[B%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 cQ($){return $}function sQ($,Z){let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function iQ($){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 JB}from"node:fs";var aQ=15000;function s$($){if(!$)return;let Z=r1($);return Z?o1(Z):void 0}class y8{deps;now;token;identity;quota;snapshot;firstPolledFor;inflight;lastPull;constructor($){this.deps=$,this.now=$.now??Date.now}observeToken($){if(!$)return;let Z=s$($);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 $=z$(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??aQ))return this.inflight;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=S0($,this.now(),X);if(J)this.merge(J);return!0}owns($){if(!this.token)return!1;let Z=s$($);return Z&&this.identity?Z===this.identity:$===this.token}merge($){try{let Z=E0(this.quota,$);if(B0(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 nQ}from"node:os";import{join as V5}from"node:path";function rQ(){return process.env.PI_AGENT_DIR?.trim()||V5(nQ(),".pi","agent")}function U5(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||V5(rQ(),y6)}function oQ($=U5()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||q3($)}function j5($=U5()){return{configPath:$,statePath:oQ($)}}function f8($){return $!==void 0&&($.vault===!0||!!$.token)}function D5($,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(k0(G.credential))return!1;if(G.id===R0)return!1;if(J&&G.identity===J)return!1;if(G.identity!==void 0&&z.has(G.identity))return!1;return t6(z$(G.quota),Z,X)})}function HZ($,Z){let X=$.now(),J=H7(Z,$.storage,X);return{rows:Z.map((G)=>({id:G.id,kind:G.kind??"oauth",...B0(G.quota)?{quota:G.quota}:{}})),now:X,rateLimitMarks:new Map,refreshBackoff:$.refreshBackoff(Z),killswitch:J,requestPull:$.requestPull}}async function K5($){let Z=$.accounts(),X=U7(HZ($,Z),$.firstReadingWaitMs);if(X)await X,Z=$.accounts();if($.mode==="sticky-balanced"&&$.sessionId){let J=await eQ($,Z,$.sessionId);if(J)return J}return tQ($,Z)}async function tQ($,Z){let X=V7($.mode),J=D7({...HZ($,Z),placement:X,mainId:$.mainId});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=l4($.storage),Q=[],B=new Set,Y;for(;;){let H=OZ(J.order.filter((j)=>!B.has(j)),Q,G);if(H===void 0)break;let V=z.get(H);if(!f8(V)){B.add(H);continue}let W=await $.send(V);if(!W){B.add(H);continue}Y={attempt:W,accountId:V.id},Q.push({id:V.id,...W.status!==void 0?{status:W.status}:{}})}if(Y)return{kind:"sent",...Y};return{kind:"blocked",block:{reason:"no-credential"}}}async function eQ($,Z,X){let J=$.requestBytes,z=new Map(Z.map((K)=>[K.id,K])),G=HZ($,Z),Q=U8(G),B={requestBytes:J,reservePercent:(K)=>H1($.storage,K===R0?void 0:K),resetCredits:()=>{return},onEmptyWeightedSet:()=>{$.log?.debug("sticky routing: no fresh weighted candidates; using configured order")}},Y=(K,M,P)=>(E,F)=>{let q=new Set(E);return $.placePin({sessionId:X,requestBytes:J,validPinnedAccountIds:K.rows.map((L)=>L.id).filter((L)=>!M.excluded.has(L)),excludeAccountIds:E,quotaCheckedAtByAccount:Object.fromEntries(K.rows.map((L)=>[L.id,M.projections.get(L.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(P.map((L)=>[L.id,L.identity])),select:(L)=>q7(K,B,q,L),persist:F})},H=Y(G,Q,Z),V=H([],!0);if(!V)return;let W=V.accountId,j=(K)=>{let M=H([W],!0);if(!M)return!1;return $.log?.debug("sticky routing: migrated session pin",{fromAccountId:W,toAccountId:M.accountId,reason:K}),W=M.accountId,!0},D=N7(G,B,W);if(D.kind==="none")return;if(D.kind==="move"){if(!j(D.reason)&&D.reason==="killswitch")return}else if(D.kind==="detour"){let K=H([W],!1);if(!K)return;$.log?.debug("sticky routing: pinned account awaits a quota reading",{pinnedAccountId:W,servedAccountId:K.accountId}),W=K.accountId}let U=z.get(W);if(!f8(U))return;let N=await $.send(U);if(!N)return;if(N.status===401||N.status===403||N.status===429){let K=$.accounts();G=HZ($,K),Q=U8(G),H=Y(G,Q,K);let M=M7(G,Q,W,N.status);if(M.action==="migrate"){let P=W;if(j(M.reason)&&W!==P){let E=K.find((q)=>q.id===W),F=f8(E)?await $.send(E):void 0;if(E&&F)N=F,U=E;else W=P}}}return{kind:"sent",attempt:N,accountId:U.id}}var $B=500,ZB=15000;function WZ($,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)})})}var XB={info(){},warn(){}};class g8{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;quotaPulls=new Map;polled=new Set;polledSnapshots=new Map;pollOutcomes=new Map;disposed=!1;constructor($){this.deps=$,this.now=$.now??Date.now,this.log=$.log??XB}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 WZ(this.startRead($),this.deps.readBudgetMs??$B,()=>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}|${O8($.configPath)}|${O8($.statePath)}`}storeFor($){if(this.store?.configPath===$.configPath)return this.store.store;let Z=z3({provider:"openai",configPath:$.configPath,statePath:$.statePath,quota:qZ,now:this.now,pull:(X)=>this.coalescedPull(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 G=X.credential.lastRefreshedAt??0,Q=z.lastRefreshedAt??0;if(G>=Q)this.rotated.delete(X.id);else J={...J,credential:z}}return g7(J,this.pending,Z)})}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??ZB))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set($,X);let z=this.storeFor(this.deps.paths());return z.requestReading($),z.pullsSettled()}coalescedPull($){let Z=JSON.stringify([this.deps.paths().configPath,$.id,$.credentialEpoch,$.identity]),X=this.quotaPulls.get(Z);if(X)return X;let J=this.pull($).finally(()=>this.quotaPulls.delete(Z));return this.quotaPulls.set(Z,J),J}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){f7(this.pending,$,Z),this.replaceRow($.id,(X)=>({...X,quota:C8(X.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=s$(X);if(!(G&&z.identity?G===z.identity:b1(z)?.access===X))return;let B=S0(Z,this.now(),J);if(!B)return;if(this.applyObservation(z,B),z.credentialEpoch===void 0)return;let Y={credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},H=this.storeFor(this.deps.paths()),W=(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,Y,B)}).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,W),W.finally(()=>{if(this.writes.get(z.id)===W)this.writes.delete(z.id)})}rowForToken($){let Z=s$($);return this.snapshot.rows.find((X)=>Z&&X.identity?X.identity===Z:b1(X)?.access===$)}refreshDueTokens($,Z){if(this.setAside())return Promise.resolve();let X=this.now(),J=X8(Z),z=[];for(let G of $){if(!G.candidate)continue;let Q=b1(G);if(!Q)continue;let B=(Q.expires??0)-X;if(!(!Q.access||!Q.expires||B<=J)||this.refreshBackedOff(G,X))continue;z.push(this.refresh(G.id))}return Promise.all(z).then(()=>{})}refreshBackedOff($,Z=this.now()){let X=b1($);if(!X)return!1;let J=this.backoff.get($.id);return Boolean(J&&J.tokenHash===a1(X.refresh)&&J.nextRetryAt>Z)}usableToken($,Z=this.now()){if(this.setAside())return;let X=b1($);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?b1(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;this.backoff.set($,h7(Z,X,this.now(),this.backoff.get($)))}refreshBackoffFor($){return v7($,this.backoff,this.now(),(Z,X)=>this.usableToken(Z,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 zB=W8,GB=500,QB=64;function BB(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function i$($,Z){return{type:"error",reason:"error",error:{role:"assistant",content:[],api:$.api,provider:$.provider,model:$.id,usage:BB(),stopReason:"error",errorMessage:Z,timestamp:Date.now()}}}function YB($){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 ${W7} 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 HB($){for(let[Z,X]of Object.entries($)){if(Z.toLowerCase()!=="authorization")continue;return/^Bearer\s+(.+)$/i.exec(X.trim())?.[1]}return}class h8{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??j5;let Z=()=>$.fetchImpl??globalThis.fetch;this.main=new y8({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 Z$({accessToken:X,fetchImpl:Z(),now:this.now,...J?{accountId:J}:{},accountKey:R0}),G=S0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.pool=new g8({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 x4({refreshToken:X.refresh,fetchImpl:Z(),now:this.now}),z=S$({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 Z$({accessToken:J.access,fetchImpl:Z(),now:this.now,...X.identity?{accountId:X.identity}:{},accountKey:X.id}),G=S0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.vault=$.vault??new Q8({host:"pi",stateDir:$Z(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??Y5(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=JB($.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=$8($).then((J)=>{return this.storageCache={key:Z,storage:J},J},()=>this.storageCache?.storage??null);this.storageRead={key:Z,promise:X}}return WZ(this.storageRead.promise,this.deps.readBudgetMs??GB,()=>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 B=this.main.quotaMap();Z.push({id:R0,token:X,...J?{identity:J}:{},...B?{quota:B}:{}})}let G=this.pool.peek(),Q=this.now();if(G.active)for(let B of D5(G.rows,$,Q,J,z))Z.push({id:B.id,token:this.pool.usableToken(B,Q),...B.identity?{identity:B.identity}:{},...B.quota!==void 0?{quota:B.quota}:{}})}poolRowById($){return this.pool.peek().rows.find((Z)=>Z.id===$)}requestPull($){if($===R0)return this.main.requestReading();if(this.vault.owns($))return this.vault.requestReading($);return this.pool.requestReading($)}rememberVaultToken($,Z){this.vaultTokens.delete($),this.vaultTokens.set($,Z);while(this.vaultTokens.size>QB){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=n2(J),G=r2(J),Q=this.vaultTokens.get(Z);if(Q?.id===$)this.vault.recordSnapshot($,z,G,Q.receipt);else if($===R0)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=HB($);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,o2(J))}stream($,Z,X){let J=this.deps.createStream(),z=this.deps.installWebSocket?.()??(()=>{});return(async()=>{try{if(await this.readAuthority()!=="local"&&X?.apiKey!==c$){J.push(i$($,Q5));return}let G=await this.route($,Z,X);if(G.kind==="blocked"){J.push(i$($,G.refusal?Z7(G.refusal,this.vault.name):YB(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(i$($,j1(G,X?.apiKey).message))}finally{J.end(),z()}})(),J}async route($,Z,X){let J=await this.storage(),z=await this.readAuthority()!=="local";if(z)await WZ(this.vault.awaitRequestRoster().then(()=>!0),ZZ,()=>!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,B=0,H=await(()=>K5({accounts:()=>{let V=this.accounts(J);return B=V.length,V},storage:J,mode:G,mainId:z?JZ(this.vault.routes()):void 0,sessionId:X?.sessionId,requestBytes:Buffer.byteLength(JSON.stringify(Z),"utf8"),now:this.now,refreshBackoff:(V)=>this.pool.refreshBackoffFor(V.map((W)=>this.poolRowById(W.id)).filter((W)=>W!==void 0)),requestPull:(V)=>this.requestPull(V),firstReadingWaitMs:this.deps.firstReadingWaitMs??zB,send:(V)=>V.vault?this.vaultAttempt($,Z,X,V.id).then((W)=>{if(!W)Q=!0;return W}):V.token?this.attempt($,Z,X,V.id,V.token):Promise.resolve(void 0),placePin:a7}))();if(H.kind==="blocked"){if(z&&(B===0||Q))return{...H,refusal:Q?"vault-refused":X7(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{let V=X?.fetch??globalThis.fetch;Q=this.deps.streamSimple($,Z,{...X,apiKey:z,fetch:Object.assign(async(W,j)=>{try{return await d7(await V(W,j),z,"event-stream")}catch(D){throw j1(D,z)}},V),onResponse:async(W,j)=>{G=W.status,this.recordHeaders(J,z,W.headers),await X?.onResponse?.(W,j)}})}catch(V){return{head:i$($,j1(V,z).message),rest:void 0}}let B=async function*(){try{for await(let V of Q){if(V.type==="error")V.error.errorMessage=U1(V.error.errorMessage??"",z);yield V}}catch(V){yield i$($,j1(V,z).message)}}(),Y=await B.next(),H=Y.done?void 0:Y.value;return{...G!==void 0?{status:G}:{},head:H,rest:Y.done||H?.type==="error"?void 0:B}}async vaultAttempt($,Z,X,J){let z;return await this.vault.send(J,async(Q,B)=>{return this.rememberVaultToken(Q,{id:J,receipt:{credentialId:B.credentialId,accountIdentitySource:B.accountIdentitySource,...B.accountIdentity!==void 0?{accountIdentity:B.accountIdentity}:{},...B.expectedAccountIdentity!==void 0?{expectedAccountIdentity:B.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:R0,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 n$="https://chatgpt.com/backend-api",N5;class m8 extends k8{constructor($,Z){let X=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),X);let J=N5;if(J)this.addEventListener("message",(z)=>{let G=z?.data;if(typeof G==="string")J(X,G)})}}var a$=0,v8;function UB(){let $=globalThis;if(a$===0)v8=$.WebSocket,$.WebSocket=m8;return a$++,()=>{if(a$=Math.max(0,a$-1),a$===0){if($.WebSocket===m8)$.WebSocket=v8;v8=void 0}}}var jB=[{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:n$,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:n$,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:n$,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:n$,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 q5($,Z){$.registerProvider("openai-codex",{baseUrl:n$,api:"openai-codex-responses",name:"OpenAI Codex (CortexKit)",...Z.vaultMode()?{apiKey:c$}:{},models:jB,streamSimple:(X,J,z)=>Z.stream(X,J,z)})}function KB(){return new h8({streamSimple:($,Z,X)=>VB($,Z,X),createStream:WB,installWebSocket:UB})}async function qB($){let Z=KB();N5=(Q,B)=>Z.observeWebSocketMessage(Q,B);let X,J,z=(Q=!0)=>Z.syncVaultSlot(X?async()=>{q5($,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(H5($,{pool:Z.commandSupport(),afterApply:z,onContext:(Q)=>{X=()=>Q.modelRegistry.refresh(),J=(B,Y)=>Q.ui.notify(B,Y)}}),await z().catch(()=>{}),q5($,Z),setInterval(G,DB).unref?.(),typeof $.on==="function")$.on("session_start",async(Q,B)=>{X=()=>B.modelRegistry.refresh(),J=(Y,H)=>B.ui.notify(Y,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 B.modelRegistry.getApiKeyForProvider("openai-codex"))}catch{}})}export{q5 as registerPiProvider,UB as installRawCodexWebSocket,qB as default,KB as createPiOpenAIRuntime};