@cortexkit/opencode-openai-auth 1.5.0 → 1.6.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/bin.js +2 -2
- package/dist/{codex-request-BjGT9yWg.d.ts → codex-request-D_In8uaR.d.ts} +43 -26
- package/dist/{index-gmmakhbt.js → index-1qxz4s8a.js} +2 -2
- package/dist/{index-2rw81dtm.js → index-79y7w9bz.js} +1 -1
- package/dist/{index-2yszc75z.js → index-7nmdsmpp.js} +2 -2
- package/dist/{index-3y453wg4.js → index-8xq099qf.js} +2 -2
- package/dist/index-agaatt62.js +65 -0
- package/dist/{index-mhfja8yr.js → index-b0ty9qam.js} +2 -2
- package/dist/index-ge60xry3.js +90 -0
- package/dist/{index-krcqvyqf.js → index-jkpg9d1p.js} +1 -1
- package/dist/index-k5anexvs.js +69 -0
- package/dist/{index-e416r885.js → index-rf0ht3gc.js} +2 -2
- package/dist/{index-4w0nsq5s.js → index-x9nffaye.js} +1 -1
- package/dist/{index-7vkn2e46.js → index-ya9c5e4m.js} +1 -1
- package/dist/{index-djnfq652.js → index-z8bptbrk.js} +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{model-BMq5SCUB.d.ts → model-D22uj0OB.d.ts} +1 -1
- package/dist/{port-file-CjMFUWcX.d.ts → port-file-8ElfwDcq.d.ts} +1 -1
- package/dist/{protocol-BC3ndToM.d.ts → protocol-CK9guiFy.d.ts} +1 -1
- package/dist/rpc/port-file.d.ts +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +3 -3
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{sidebar-state-DfYyqiOH.d.ts → sidebar-state-Bb9L9oPq.d.ts} +4 -4
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-nyvn9866.js +1 -0
- package/dist/{token-ycw7dyev.js → token-xtq3457d.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +2 -2
- package/dist/v2/server.d.ts +2 -2
- package/dist/v2/server.js +2 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +4 -54
- package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +39 -25
- package/src/tui-compiled/raw/shared/a910277ac43a8626-pull.js +3 -1
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +18 -3
- package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +298 -0
- package/src/tui-compiled/raw/shared/e1c5e56df0ba4053-pending.js +48 -0
- package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +4 -54
- package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +39 -25
- package/src/tui-compiled/runtime/shared/a910277ac43a8626-pull.js +3 -1
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +18 -3
- package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +298 -0
- package/src/tui-compiled/runtime/shared/e1c5e56df0ba4053-pending.js +48 -0
- package/dist/index-2p3gcjsa.js +0 -69
- package/dist/index-6fdmqk6p.js +0 -90
- package/dist/index-fztcacjr.js +0 -65
- package/dist/token-util-ed4az5gg.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`;try{G?.({channel:Q,level:I,message:S,data:K})}catch{}if(H===void 0)return;if(U.push(r),U.length>=50){let F=R(!1);if(F instanceof Promise)F.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(I,X)=>x(Q,"error",I,X),warn:(I,X)=>x(Q,"warn",I,X),info:(I,X)=>x(Q,"info",I,X),debug:(I,X)=>x(Q,"debug",I,X),trace:(I,X)=>x(Q,"trace",I,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,U=[],V)clearTimeout(V),V=void 0;H=void 0,Z=void 0,$=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var O=BJ();function L(J){O.configure(J);let{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}=O;return{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}}function v(J){O.setLogLevel(J)}function u(){return O.flushLogs()}function c(J){return O.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,pJ=d.redactStrings;function hJ(J){L({...J,extraSecretKeys:f})}function uJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function fJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",xJ="openai-auth-state.json";function oJ(J){return MJ(J)===AJ?qJ(TJ(J),xJ):`${J}.state.json`}import{spawn as _J}from"node:child_process";function nJ(J,H=process.platform,Z=_J){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),U=Z("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}let $=Z(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore"});return $.on("error",()=>{}),$.unref(),$.pid!==void 0}catch{return!1}}export{T as
|
|
1
|
+
import{$e as w,We as q,Ye as _,_e as A,bf as k,df as p}from"./index-7nmdsmpp.js";import{appendFileSync as QJ,chmodSync as UJ,existsSync as W,renameSync as g,statSync as ZJ}from"node:fs";import{open as $J}from"node:fs/promises";import{dirname as VJ,resolve as IJ}from"node:path";var i=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,e=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function JJ(J){return J instanceof Error||Object.prototype.toString.call(J)==="[object Error]"}function T(J={}){let H=[e,...J.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function Z(G){let U=G.toLowerCase().replace(/[-_]/g,"");return i.test(G)||U.includes("apikey")||U.endsWith("secret")||U.endsWith("password")||U.endsWith("token")&&!U.endsWith("tokens")||!!J.extraSecretKeys?.(U)}function $(G){let U=G,V=[["name",G.name],["message",G.message],["stack",G.stack]];for(let j of["code","status","cause"])if(U[j]!==void 0)V.push([j,U[j]]);let Y=new Set(V.map(([j])=>j));for(let j of Object.entries(G))if(!Y.has(j[0]))V.push(j);return V}function B(G,U,V,Y=0){if(typeof G==="string")return H.reduce((j,C)=>j.replace(C,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(V.has(G))return"[Circular]";V.add(G);try{if(Array.isArray(G))return G.map((N)=>B(N,U,V,Y));let j=JJ(G);if(j&&Y>=8)return"[Truncated]";let C=j?Y+1:Y;return Object.fromEntries((j?$(G):Object.entries(G)).map(([N,z])=>[N,U&&Z(N)?"***REDACTED***":B(z,U,V,C)]))}finally{V.delete(G)}}return{redact:(G)=>B(G,!0,new WeakSet),redactStrings:(G)=>B(G,!1,new WeakSet)}}var E=T(),GJ=E.redact,HJ=E.redactStrings;var D={error:0,warn:1,info:2,debug:3,trace:4},h=5242880,m=3;function b(J){try{UJ(J,384)}catch{}}function jJ(J){try{if(!(W(J)&&ZJ(J).size>=h))return;for(let Z=m-1;Z>=1;Z--)if(W(`${J}.${Z}`)){let $=`${J}.${Z+1}`;g(`${J}.${Z}`,$),b($)}let H=`${J}.1`;g(J,H),b(H)}catch{}}async function M(J){let{file:H,handle:Z}=J;if(J.file=void 0,J.handle=void 0,H&&Z)await _(H,"log-close",()=>Z.close())}async function y(J,H){await w(VJ(H));try{await A(H,"file",!0)}catch(Z){if(Z.code!=="ENOENT")throw Z;try{await k(H,"")}catch($){if($.code!=="EEXIST")throw $;await A(H,"file",!0)}}return J.handle=await _(H,"log-open",()=>$J(H,"a")),J.file=H,J.handle}async function XJ(J,H,Z){H=IJ(H);try{if(J.file!==H)await M(J);let $=J.handle??await y(J,H);if((await _(H,"log-stat",()=>$.stat())).size>=h){await M(J);for(let G=m-1;G>=0;G--){let U=G===0?H:`${H}.${G}`,V=`${H}.${G+1}`;try{await A(U,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await A(V,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await p(U,V),await A(V,"file")}$=await y(J,H)}await _(H,"log-append",()=>$.appendFile(Z,"utf8"))}catch($){throw await M(J).catch(()=>{}),$}}function YJ(J){try{return` ${JSON.stringify(J)}`}catch{return" [unserializable]"}}function BJ(J){let H,Z,$,B=T(),G,U=[],V,Y=Promise.resolve(),j,C={};function N(Q){let I=Y.then(Q);return Y=I.catch((X)=>{j=X}),I}function z(Q){if(q&&Q.file!==H)N(()=>M(C)).catch(()=>{});H=Q.file,Z=Q.level,B=T(Q),G=Q.captureSink}function s(Q){if(Q===void 0||Q in D)$=Q}function o(){if(H===void 0)return;return(typeof H==="function"?H():H)||void 0}function t(){if($)return $;let Q=typeof Z==="function"?Z():Z;if(Q&&Q in D)return Q;return"info"}function R(Q=!0){if(V)clearTimeout(V),V=void 0;if(!U.length){if(q)return N(async()=>{if(Q)await M(C);if(j)throw j});return}let I;try{I=o()}catch{if(U=[],q&&Q)return N(()=>M(C));return}let X=U.join("");if(U=[],!I){if(q&&Q)return N(()=>M(C));return}if(q)return N(async()=>{try{await XJ(C,I,X)}finally{if(Q)await M(C)}});try{if(jJ(I),W(I))b(I);QJ(I,X,{encoding:"utf8",mode:384})}catch{}}function a(){if(!V)V=setTimeout(()=>{V=void 0;let Q=R(!1);if(Q instanceof Promise)Q.catch(()=>{})},500)}function x(Q,I,X,P){if(H===void 0&&G===void 0)return;try{if(D[I]>D[t()])return;let S=B.redactStrings(X),K;try{K=B.redact(P)}catch{K="[unserializable]"}let r=`[${new Date().toISOString()}] ${I.toUpperCase()} [${Q}] ${S}`+(P===void 0?"":YJ(K))+`
|
|
2
|
+
`;try{G?.({channel:Q,level:I,message:S,data:K})}catch{}if(H===void 0)return;if(U.push(r),U.length>=50){let F=R(!1);if(F instanceof Promise)F.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(I,X)=>x(Q,"error",I,X),warn:(I,X)=>x(Q,"warn",I,X),info:(I,X)=>x(Q,"info",I,X),debug:(I,X)=>x(Q,"debug",I,X),trace:(I,X)=>x(Q,"trace",I,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,U=[],V)clearTimeout(V),V=void 0;H=void 0,Z=void 0,$=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var O=BJ();function L(J){O.configure(J);let{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}=O;return{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}}function v(J){O.setLogLevel(J)}function u(){return O.flushLogs()}function c(J){return O.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,pJ=d.redactStrings;function hJ(J){L({...J,extraSecretKeys:f})}function uJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function fJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",xJ="openai-auth-state.json";function oJ(J){return MJ(J)===AJ?qJ(TJ(J),xJ):`${J}.state.json`}import{spawn as _J}from"node:child_process";function nJ(J,H=process.platform,Z=_J){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),U=Z("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}let $=Z(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore"});return $.on("error",()=>{}),$.unref(),$.pid!==void 0}catch{return!1}}export{T as Ke,GJ as Le,v as Me,u as Ne,c as Oe,pJ as Pe,hJ as Qe,AJ as Re,oJ as Se,uJ as Te,fJ as Ue,nJ as Ve};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import{qe as m,te as C,ue as s0,we as n0}from"./index-8xq099qf.js";import{Ne as T0,Oe as I,Qe as J6,Te as x4}from"./index-b0ty9qam.js";import{$e as HZ,We as D$,Xe as i0,Ze as p3,af as Q0,ef as l3}from"./index-7nmdsmpp.js";var P="all",f0=Object.freeze(["primary"]);function cZ($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function M$($,Z){return JSON.stringify([$,Z])}function c($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R($){return typeof $==="number"&&Number.isFinite($)}function dZ($){return typeof $==="string"&&$.length>0}function S($,Z,z){return $[Z]===void 0||z($[Z])}function K6($){return R($)&&$>0}function b0($){return typeof $==="string"}function W6($){if(!c($)||!dZ($.scope)||!dZ($.label))return!1;switch($.kind){case"reading":return R($.checkedAt)&&R($.usedPercent)&&S($,"resetsAt",b0)&&S($,"windowMinutes",K6);case"retired":return R($.retiredAt);case"absent":return R($.checkedAt);default:return!1}}function Q6($){if(!c($)||!R($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&S($,"remainingPercent",R)&&S($,"usedPercent",R)&&S($,"resetsAt",b0)&&S($,"limit",R)&&S($,"used",R)&&S($,"remaining",R)&&S($,"unit",b0)}function uZ($){return c($)&&R($.value)&&Number.isInteger($.value)&&$.value>=0&&R($.checkedAt)}function k0($){return c($)&&Object.values($).every(uZ)}function U6($){return typeof $==="boolean"}function w($){return c($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&S($,"balance",R)&&S($,"overageLimitReached",U6)&&R($.checkedAt)}function y0($){if(!c($))return;let Z=Object.entries($).filter(([,z])=>uZ(z));return Z.length===0?void 0:Object.fromEntries(Z)}function Y$($){if(X$($))return $;if(!c($))return;let{counters:Z,credits:z,...X}=$;if(!X$(X))return;let Y=y0(Z),G=w(z)?z:void 0;return{...X,...Y===void 0?{}:{counters:Y},...G===void 0?{}:{credits:G}}}function X$($){if(!c($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let z of $.limits){if(!W6(z))return!1;let X=M$(z.scope,z.label);if(Z.has(X))return!1;Z.add(X)}return S($,"budget",Q6)&&S($,"counters",k0)&&S($,"credits",w)}var aZ=900000,oZ="no quota reading yet",rZ="no limits reported";function tZ($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let Y=Math.floor(Z/60),G=Z%60;return G===0?`${Y}h`:`${Y}h${G}m`}let z=Math.floor(Z/1440),X=Math.floor(Z%1440/60);return X===0?`${z}d`:`${z}d${X}h`}function eZ($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function $3($){if($.scope!==P||$.windowMinutes===void 0)return $.label;return eZ($.windowMinutes)}function h0($){return Math.min(100,Math.max(0,$))}function c$($){return Math.round(h0($))}function iZ($){return`${c$($)}% left`}function sZ($,Z,z){let X=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(X)&&X>z?{resetIn:tZ(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>Z&&X<=z}}function D6($,Z){let z=$.windowMinutes,X=Z.windowMinutes;if(z!==void 0&&X!==void 0&&z!==X)return z-X;if(z===void 0!==(X===void 0))return z===void 0?1:-1;if($.scope!==Z.scope){if($.scope===P)return-1;if(Z.scope===P)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function Z3($,Z){let{windows:z,age:X}=w0($,Z),Y=z.map(({part:G})=>G);return X===void 0?{windows:Y}:{windows:Y,age:X}}function V6($){let Z=z3($.filter(({part:z,scope:X})=>z.kind==="window"&&X!==P).map(({scope:z})=>z));for(let z of $)z.part.short=z.part.kind==="budget"?"cr":z.scope===P?z.part.name:Z.get(z.scope)??z.scope;return $}function w0($,Z){if(!$)return{windows:[]};let{now:z}=Z,Y=$.limits.filter((J)=>J.kind==="reading"&&J.remainingPercent!==void 0).sort(D6).map((J)=>{let B=h0(J.remainingPercent??0);return{scope:J.scope,...J.windowMinutes===void 0?{}:{windowMinutes:J.windowMinutes},part:{kind:"window",name:$3(J),short:"",figure:iZ(J.remainingPercent??0),remainingPercent:B,checkedAt:J.checkedAt,...sZ(J.resetsAt,J.checkedAt,z)}}}),G=$.budget;if(G){let J=G.remainingPercent,B=G.reached?"credits spent":J!==void 0?`credits ${iZ(J)}`:"credits available";Y.push({scope:P,spent:G.reached,part:{kind:"budget",name:"credits",short:"",figure:B,...J===void 0?{}:{remainingPercent:h0(J)},checkedAt:G.checkedAt,...sZ(G.resetsAt,G.checkedAt,z)}})}if(V6(Y),Y.length>0){let J=z-Math.min(...Y.map(({part:B})=>B.checkedAt));if(J>(Z.staleAfterMs??aZ))return{windows:Y,age:`checked ${tZ(J)} ago`}}return{windows:Y}}function F6($,Z){return w0($,Z).age!==void 0}function nZ($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function z3($){let Z=[...new Set($.map(nZ))],z=new Map(Z.map((Y)=>[Y,2])),X=(Y)=>Y.slice(0,z.get(Y));for(;;){let Y=new Map;for(let J of Z)Y.set(X(J),[...Y.get(X(J))??[],J]);let G=!1;for(let J of Y.values()){if(J.length<2)continue;for(let B of J){let H=z.get(B)??2;if(H<B.length)z.set(B,H+1),G=!0}}if(!G)break}return new Map($.map((Y)=>[Y,X(nZ(Y))]))}var j6=2;function N6($){let Z=$.map((X)=>X.label.trim()||X.scope),z=z3(Z);return Z.map((X)=>z.get(X)??X)}function q6($,Z){if(!$||$.length===0)return;let z=Z.filter(({part:B})=>B.kind==="window");if(z.some(({scope:B})=>B===P))return;let X=$.flatMap((B,H)=>{let K=z.filter(({scope:W})=>W===B.scope).reduce((W,U)=>W===void 0||(U.part.remainingPercent??0)<(W.part.remainingPercent??0)?U:W,void 0);return K?[{group:B,listed:H,window:K}]:[]});if(X.length===0)return;let Y=N6($),G=(B)=>B.window.part.remainingPercent??0,J=[...X].sort((B,H)=>G(B)-G(H)||B.listed-H.listed).slice(0,j6).sort((B,H)=>B.listed-H.listed);return J.map((B,H)=>{let{windowMinutes:Q}=B.window,K=[Y[B.listed]??B.group.scope,...Q===void 0?[]:[eZ(Q)],`${c$(G(B))}%`].join(" ");return H===J.length-1?`${K} left`:K})}function M6($,Z){let{windows:z}=w0($,Z),X=q6($?.groups,z);if(X)return X;let Y=z.filter(({part:W,scope:U})=>W.kind==="window"&&U===P),G=z.filter(({part:W,scope:U})=>W.kind==="window"&&U!==P),J=z.find(({part:W})=>W.kind==="budget"),B=J?.spent?0:J?.part.remainingPercent,Q=[...G.map(({part:W})=>({label:W.short,remaining:W.remainingPercent??0})),...B===void 0||J===void 0?[]:[{label:J.part.short,remaining:B}]].reduce((W,U)=>W===void 0||U.remaining<W.remaining?U:W,void 0),K=Y.map(({part:W})=>`${W.name} ${c$(W.remainingPercent??0)}%`);if(Q)K.push(`${Q.label} ${c$(Q.remaining)}%`);if(K.length===0)return z.map(({part:W})=>W.figure);return K.map((W,U)=>U===K.length-1?`${W} left`:W)}function X3($,Z){if(Z.form==="narrow")return M6($,Z);let z=Z3($,Z),X=(Z.form??"full")==="full",Y=z.windows.map((G)=>{let J=X&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${J}`});return z.age===void 0?Y:[...Y,z.age]}function O6($,Z){let z=X3($,Z);if(z.length>0)return z.join(" · ");return $&&$.limits.length>0?rZ:oZ}function _6($){if($===void 0)return;if($.unlimited)return"Unlimited";if(!$.hasCredits)return;let{balance:Z}=$;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?`${Math.round(Z)} credits`:"Available"}function P6($){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 L6($,Z){let z=$.windowMinutes!==void 0,X=Z.windowMinutes!==void 0;if(z!==X)return z?-1:1;if(z&&X&&$.windowMinutes!==Z.windowMinutes)return(Z.windowMinutes??0)-($.windowMinutes??0);if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function R6($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function A($,Z=P){let z=new Map;for(let K of $?.limits??[]){if(K.scope!==Z&&K.scope!==P)continue;let W=z.get(K.label);if(W===void 0){z.set(K.label,K);continue}let U=K.scope===P?W:K,N=K.scope===P?K:W;z.set(K.label,U.kind==="reading"?U:N)}let X=[...z.values()].map(P6).sort(L6),Y=X.filter((K)=>K.kind==="reading"),G=Y.length>0?Y:X,J=G.length>0?Math.min(...G.map((K)=>K.checkedAt)):void 0,B=$?.budget?.kind==="reading"?R6($.budget):void 0,H=y0($?.counters),Q=w($?.credits)?$.credits:void 0;return{scope:Z,limits:X,...J===void 0?{}:{checkedAt:J},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H},...Q===void 0?{}:{credits:Q}}}function G$($,Z){let z=$?.budget;if(z?.reached!==!0||typeof z.resetsAt!=="string")return;let X=Date.parse(z.resetsAt);if(!Number.isFinite(X)||X<=Z)return;return{resetsAt:z.resetsAt,resetAtMs:X}}function m0($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function u$($,Z){if(typeof $.resetsAt!=="string")return;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z>Z?z:void 0}class i$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function n$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function s$($){return typeof $==="number"&&Number.isFinite($)}function Y3($){return $===void 0||typeof $==="string"&&$!==""}function G3($){return typeof $==="string"&&$!==""}function S$($,Z){return $[Z]===void 0||s$($[Z])}function g0($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function S6($){return n$($)&&Y3($.scope)&&G3($.label)&&s$($.usedPercent)&&g0($,"resetsAt")&&($.windowMinutes===void 0||s$($.windowMinutes)&&$.windowMinutes>0)}function x6($){return n$($)&&Y3($.scope)&&G3($.label)}function T6($){if(!n$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&S$($,"remainingPercent")&&S$($,"usedPercent")&&g0($,"resetsAt")&&S$($,"limit")&&S$($,"used")&&S$($,"remaining")&&g0($,"unit")}function O$($){if(!n$($)||!s$($.checkedAt))return!1;let Z=$.readings??[],z=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(z))return!1;let X=new Set;for(let Y of Z){if(!S6(Y))return!1;let G=M$(Y.scope??P,Y.label);if(X.has(G))return!1;X.add(G)}if(!z.every(x6))return!1;return($.budget===void 0||T6($.budget))&&($.counters===void 0||k0($.counters))&&($.credits===void 0||w($.credits))}function E6($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function A6($,Z,z){if(Z===void 0)return $;if($!==void 0&&z<$.checkedAt)return $;return{...Z,checkedAt:z}}function C6($,Z){let z=new Map(Object.entries($??{}));for(let[X,Y]of Object.entries(Z??{})){let G=z.get(X);if(G===void 0||Y.checkedAt>=G.checkedAt)z.set(X,Y)}return z.size===0?void 0:Object.fromEntries(z)}function I6($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function x$($,Z){let z=$===void 0?void 0:Y$($);if($!==void 0&&z===void 0)throw new i$("stored quota map is malformed");if(!O$(Z))throw new i$("quota observation is malformed");let X=z??{limits:[]},Y=Z.checkedAt,G=new Map;for(let q of X.limits)G.set(M$(q.scope,q.label),q);let J=(q)=>{let L=G.get(q);return L===void 0||Y>=cZ(L)},B=new Set;for(let q of Z.readings??[]){let L=q.scope??P,T=M$(L,q.label);if(B.add(T),!J(T))continue;G.set(T,{scope:L,label:q.label,kind:"reading",checkedAt:Y,usedPercent:q.usedPercent,...q.resetsAt===void 0?{}:{resetsAt:q.resetsAt},...q.windowMinutes===void 0?{}:{windowMinutes:q.windowMinutes}})}for(let q of Z.coverage??[]){let L=q.scope??P,T=M$(L,q.label);if(B.has(T)||!J(T))continue;let p=G.get(T);G.set(T,p===void 0||p.kind==="absent"?{scope:L,label:q.label,kind:"absent",checkedAt:Y}:{scope:L,label:q.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:Q,counters:K,credits:W,...U}=X,N=A6(X.budget,Z.budget,Y),D=C6(X.counters,Z.counters),M=I6(X.credits,Z.credits);return{...U,limits:[...G.values()].sort(E6),...N===void 0?{}:{budget:N},...D===void 0?{}:{counters:D},...M===void 0?{}:{credits:M}}}var b6=Object.freeze({validate:X$,decode:Y$,merge:x$});function J3($,Z,z){let X=Z.rateLimitMarks?.get($);if(X!==void 0&&z<X)return{id:$,reason:"rate-limited",until:X};let Y=Z.refreshBackoff?.get($);if(Y!==void 0&&z<Y)return{id:$,reason:"refresh-backoff",until:Y};return}function f6($,Z,z,X){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let G of z)if(!Z.limits.some((J)=>J.label===G))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:G},pullRequested:!0};let Y=Z.limits.filter(m0);for(let G of Y)if(u$(G,X)===void 0)return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of Y){let J=u$(G,X);if(J!==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:J}}return}function y($){let Z=$.scope??P,z=$.requiredLabels??f0,X=[],Y=[],G=[];for(let U of $.rows){let N=J3(U.id,$,$.now);if(N){X.push(N);continue}if(U.kind==="api-key"){G.push({id:U.id,kind:U.kind});continue}let D=A(U.quota,Z),M=f6(U.id,D,z,$.now);if(M){Y.push(M);continue}G.push({id:U.id,kind:U.kind,projection:D})}let J=new Map(G.flatMap((U)=>{let N=G$(U.projection,$.now);return N?[[U.id,N]]:[]})),B=J.size>0&&J.size===G.length,H=[];for(let U of G){let N=J.get(U.id);if(N===void 0)H.push(U);else if(B)H.push({...U,lastPath:!0});else Y.push({id:U.id,stage:2,reason:"budget-spent",...N})}let Q=new Map($.rows.map((U,N)=>[U.id,N])),K=(U,N)=>(Q.get(U.id)??0)-(Q.get(N.id)??0);Y.sort(K);let W=Y.filter((U)=>("pullRequested"in U)).map((U)=>U.id);for(let U of W)$.requestPull?.(U);return{admitted:H,refused:Y,excluded:X,pulls:W}}var B3="main";function k6($){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 a$($,Z,z=B3){if(Z==="roster"||!$.includes(z))return[...$];let X=$.filter((Y)=>Y!==z);return Z==="main-first"?[z,...X]:[...X,z]}function v0($){let Z=y($),z=new Set(Z.admitted.map((Y)=>Y.id));return{order:a$($.rows.map((Y)=>Y.id),$.placement??"roster",$.formerMainId).filter((Y)=>z.has(Y)&&$.killswitch?.get(Y)!==!1),admission:Z}}function y6($,Z,z){let X=Z.at(-1);if(X!==void 0){if(X.status===void 0||!z.includes(X.status))return}let Y=new Set(Z.map((G)=>G.id));return $.find((G)=>!Y.has(G))}function p0($,Z,z){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof z==="string"&&$.wireIdentity!==z)}function h6($,Z,z){let X=new Map;for(let[Y,G]of $){if(Y===z)continue;if(G.quotaCheckedAt!==Z.get(G.accountId))continue;X.set(G.accountId,(X.get(G.accountId)??0)+(G.inputBytes??0))}return X}var T$=900000,K3=0.016666666666666666,l0=0.000001;function o$($,Z){for(let z of[$?.checkedAt,Z])if(typeof z==="number"&&Number.isFinite(z))return z;return}function W3($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function Q3($){return $.limits.filter((Z)=>Z.kind==="reading").sort((Z,z)=>{let X=Z.windowMinutes!==void 0,Y=z.windowMinutes!==void 0;if(X!==Y)return X?-1:1;if(X&&Y)return(z.windowMinutes??0)-(Z.windowMinutes??0);return 0})}function c0($){let Z=($.classifyStatus??W3)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let z=o$($.quota,$.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||$.now-z>T$)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of Q3($.quota)){let G=Y.remainingPercent;if(typeof G==="number"&&Number.isFinite(G)&&G<=0)return{action:"migrate",reason:"exhausted",window:{scope:Y.scope,label:Y.label},...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{}}}let X=G$($.quota,$.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:Z}}function d0($,Z,z){let X=Math.max(0,$.remainingPercent-Z);if(X<=0)return 0;if(!$.resetsAt)return X;let Y=Date.parse($.resetsAt);if(!Number.isFinite(Y)||Y<=z)return X;let G=Math.max((Y-z)/3600000,K3);return X/G}function H3($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function w6($,Z){if(!$.quota)return;let z=o$($.quota,$.quotaCheckedAt);if(z===void 0||Z-z>T$)return;let X=Q3($.quota).map((J)=>d0({remainingPercent:J.remainingPercent??Number.NaN,...J.resetsAt===void 0?{}:{resetsAt:J.resetsAt}},$.reservePercent[J.label]??0,Z)),Y=$.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))X.push(d0({remainingPercent:Y.remainingPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt}},0,Z));let G=X.length>0?Math.min(...X):0;return G>0?{candidate:$,quotaCheckedAt:z,weight:G}:void 0}function U3($){let Z=$.candidates.filter((Y)=>Y.killswitchPasses!==!1);if($.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(Z.length===0)return;let z=Z.map((Y)=>w6(Y,$.now)).filter((Y)=>Y!==void 0);if(z.length>0){z.sort((G,J)=>{let B=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,l0),H=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,l0);return B-H||G.candidate.configuredOrder-J.candidate.configuredOrder||H3(G.candidate.accountId,J.candidate.accountId)});let Y=z[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let X=[...Z].sort((Y,G)=>{let J=(Y.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-J||Y.configuredOrder-G.configuredOrder||H3(Y.accountId,G.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:o$(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function u0($){let Z=y($),z=new Map(Z.admitted.map((D)=>[D.id,D])),X=new Map(Z.refused.map((D)=>[D.id,D])),Y=new Set(Z.excluded.map((D)=>D.id)),G=new Set($.rows.map((D)=>D.id)),J=$.pin!==void 0&&p0($.pin,G,$.identities?.get($.pin.accountId));if(J&&$.pin){let D=z.get($.pin.accountId);if(D&&$.killswitch?.get(D.id)!==!1)return{outcome:"dispatch",accountId:D.id,source:"pin",...D.projection?.checkedAt===void 0?{}:{quotaCheckedAt:D.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let B=$.pin?X.get($.pin.accountId):void 0,H=J&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),Q=(D)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(D):$.rowReservePercent?.get(D.id))??$.reservePercent??{}},K=$.scope,W=$.rows.map((D,M)=>({row:D,configuredOrder:M})).filter(({row:D})=>!Y.has(D.id)).map(({row:D,configuredOrder:M})=>{let q=$.killswitch?.get(D.id),L=$.resetCreditsApplicable?.get(D.id);return{accountId:D.id,quota:D.kind==="api-key"?void 0:z.get(D.id)?.projection??A(D.quota,K),reservePercent:Q(D),configuredOrder:M,...L===void 0?{}:{resetCreditsApplicable:L},...q===void 0?{}:{killswitchPasses:q}}}),U=[],N=J?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(W.length>0){let D=U3({candidates:W,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!D)break;let M=X.get(D.accountId);if(M){U.push(M),W=W.filter((L)=>L.accountId!==D.accountId);continue}let q=$.identities?.get(D.accountId);return{outcome:"dispatch",accountId:D.accountId,source:D.source,...D.quotaCheckedAt===void 0?{}:{quotaCheckedAt:D.quotaCheckedAt},pin:J&&!H?{action:"retain"}:{action:"assign",pin:{accountId:D.accountId,inputBytes:$.requestBytes,...q===void 0?{}:{wireIdentity:q},...D.quotaCheckedAt===void 0?{}:{quotaCheckedAt:D.quotaCheckedAt}}},refusedSelections:U,admission:Z}}return{outcome:"no-admissible-account",pin:N,refusedSelections:U,admission:Z}}import{createHash as m6}from"node:crypto";var g6=86400000,v6=300000,p6=3600000,l6=60000,d6=900000,c6=300000;function a0($){return $ instanceof Error?$.message:String($)}function u6($){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 o0($){let Z=a0($),z=$?.status;if(typeof z==="number")return z===429||z>=500;if(!($ instanceof Error))return!1;let X=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function D3($){return m6("sha256").update($).digest("hex")}function V3($){let Z=D3($.refreshToken),X=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,Y,G=$.error?.retryAfter;if(typeof G==="number"&&G>0)Y=G*1000;else if(u6($.error))Y=Math.min(p6,v6*2**Math.min(X-1,6));else Y=g6;return{message:a0($.error),checkedAt:$.now,nextRetryAt:$.now+Y,retryCount:X,tokenHash:Z}}function J$($,Z,z){if(!$?.nextRetryAt||$.nextRetryAt<=z)return!1;if(!Z)return!0;return $.tokenHash===D3(Z)}function r$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function E$($){let z=($.previous?.retryCount??0)+1,X,Y=$.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(o0($.error))X=Math.min(d6,l6*2**Math.min(z-1,6));else X=c6;return{message:a0($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:z}}function _$($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function r0($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let z=Date.parse($);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{createServer as F3}from"node:http";import{setTimeout as i6}from"node:timers/promises";var Z0="app_EMoamEEZ73f0CkXaXp7hrann",K$="https://auth.openai.com",C$=1455,s6=3000,n6="cortexkit-opencode-openai-auth";function M3($){return`${n6}/${$}`}var O3="main",a6=`"${O3}" is a reserved account id; choose a different label.`;function _3($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function o6(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=_3(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:z}}function j3($){if($.length>16384)return;let Z=$.split(".");if(Z.length!==3)return;let z=Z[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function N3($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let z=$["https://api.openai.com/auth"];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.chatgpt_account_id==="string"&&z.chatgpt_account_id.length>0)return z.chatgpt_account_id;let X=$.organizations;if(Array.isArray(X)){let Y=X[0];if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&typeof Y.id==="string"&&Y.id.length>0)return Y.id}return}function e$($){if($.id_token){let Z=j3($.id_token),z=Z&&N3(Z);if(z)return z}if($.access_token){let Z=j3($.access_token);return Z?N3(Z):void 0}return}function r6($){return typeof $==="string"&&$.toLowerCase()===O3}function t0($){if(r6($))throw Error(a6);return $}function t6($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:Z0,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:z,originator:"opencode"});return`${K$}/oauth/authorize?${X.toString()}`}async function e6($,Z,z){let X=await fetch(`${K$}/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:Z0,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function $8($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var Z8=`<!doctype html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<title>CortexKit OpenAI Auth - Authorization Successful</title>
|
|
5
|
+
<style>
|
|
6
|
+
body {
|
|
7
|
+
font-family:
|
|
8
|
+
system-ui,
|
|
9
|
+
-apple-system,
|
|
10
|
+
sans-serif;
|
|
11
|
+
display: flex;
|
|
12
|
+
justify-content: center;
|
|
13
|
+
align-items: center;
|
|
14
|
+
height: 100vh;
|
|
15
|
+
margin: 0;
|
|
16
|
+
background: #131010;
|
|
17
|
+
color: #f1ecec;
|
|
18
|
+
}
|
|
19
|
+
.container {
|
|
20
|
+
text-align: center;
|
|
21
|
+
padding: 2rem;
|
|
22
|
+
}
|
|
23
|
+
h1 {
|
|
24
|
+
color: #f1ecec;
|
|
25
|
+
margin-bottom: 1rem;
|
|
26
|
+
}
|
|
27
|
+
p {
|
|
28
|
+
color: #b7b1b1;
|
|
29
|
+
}
|
|
30
|
+
</style>
|
|
31
|
+
</head>
|
|
32
|
+
<body>
|
|
33
|
+
<div class="container">
|
|
34
|
+
<h1>Authorization Successful</h1>
|
|
35
|
+
<p>You can close this window and return to OpenCode.</p>
|
|
36
|
+
</div>
|
|
37
|
+
<script>
|
|
38
|
+
setTimeout(() => window.close(), 2000)
|
|
39
|
+
</script>
|
|
40
|
+
</body>
|
|
41
|
+
</html>`,t$=($)=>`<!doctype html>
|
|
42
|
+
<html>
|
|
43
|
+
<head>
|
|
44
|
+
<title>CortexKit OpenAI Auth - Authorization Failed</title>
|
|
45
|
+
<style>
|
|
46
|
+
body {
|
|
47
|
+
font-family:
|
|
48
|
+
system-ui,
|
|
49
|
+
-apple-system,
|
|
50
|
+
sans-serif;
|
|
51
|
+
display: flex;
|
|
52
|
+
justify-content: center;
|
|
53
|
+
align-items: center;
|
|
54
|
+
height: 100vh;
|
|
55
|
+
margin: 0;
|
|
56
|
+
background: #131010;
|
|
57
|
+
color: #f1ecec;
|
|
58
|
+
}
|
|
59
|
+
.container {
|
|
60
|
+
text-align: center;
|
|
61
|
+
padding: 2rem;
|
|
62
|
+
}
|
|
63
|
+
h1 {
|
|
64
|
+
color: #fc533a;
|
|
65
|
+
margin-bottom: 1rem;
|
|
66
|
+
}
|
|
67
|
+
p {
|
|
68
|
+
color: #b7b1b1;
|
|
69
|
+
}
|
|
70
|
+
.error {
|
|
71
|
+
color: #ff917b;
|
|
72
|
+
font-family: monospace;
|
|
73
|
+
margin-top: 1rem;
|
|
74
|
+
padding: 1rem;
|
|
75
|
+
background: #3c140d;
|
|
76
|
+
border-radius: 0.5rem;
|
|
77
|
+
}
|
|
78
|
+
</style>
|
|
79
|
+
</head>
|
|
80
|
+
<body>
|
|
81
|
+
<div class="container">
|
|
82
|
+
<h1>Authorization Failed</h1>
|
|
83
|
+
<p>An error occurred during authorization.</p>
|
|
84
|
+
<div class="error">${$8($)}</div>
|
|
85
|
+
</div>
|
|
86
|
+
</body>
|
|
87
|
+
</html>`,$0=[],A$,g=new Map;function q3($,Z){return new Promise((z,X)=>{let Y=(J)=>{$.off("listening",G),X(J)},G=()=>{$.off("error",Y),z()};$.once("error",Y),$.once("listening",G),$.listen(C$,Z)})}function P3($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function B$(){return g.size}function W$($){if(g.delete($),B$()===0)H$()}async function z8(){let $=`http://localhost:${C$}/auth/callback`;if($0.length>0)return{port:C$,redirectUri:$};if(A$)return A$;A$=(async()=>{let Z=(G,J)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${C$}`);if(B.pathname==="/auth/callback"){let H=B.searchParams.get("code"),Q=B.searchParams.get("state"),K=B.searchParams.get("error"),W=B.searchParams.get("error_description");if(K){let N=W||K;if(Q){let D=g.get(Q);if(D)D.reject(Error(N)),W$(Q);else if(B$()===0)H$()}else if(B$()===0)H$();J.writeHead(200,{"Content-Type":"text/html"}),J.end(t$(N));return}if(!Q){if(B$()===0)H$();J.writeHead(400,{"Content-Type":"text/html"}),J.end(t$("Missing state parameter"));return}if(!H){if(B$()===0)H$();J.writeHead(400,{"Content-Type":"text/html"}),J.end(t$("Missing authorization code"));return}let U=g.get(Q);if(!U){if(B$()===0)H$();J.writeHead(400,{"Content-Type":"text/html"}),J.end(t$("Unknown state — authorization may have expired"));return}W$(Q),e6(H,$,U.pkce).then((N)=>U.resolve(N)).catch((N)=>U.reject(N)),J.writeHead(200,{"Content-Type":"text/html"}),J.end(Z8);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),Q=H?[H]:[...g.keys()];J.writeHead(200),J.end("Login cancelled");for(let K of Q){let W=g.get(K);if(!W)continue;W.reject(Error("Login cancelled")),W$(K)}if(B$()===0)H$();return}J.writeHead(404),J.end("Not found")},z=F3(Z);await q3(z,"127.0.0.1");let X=[z],Y=F3(Z);try{await q3(Y,"::1"),X.push(Y)}catch(G){let J=G.code;if(J!=="EADDRNOTAVAIL"&&J!=="EAFNOSUPPORT")throw P3(z),G}return $0=X,{port:C$,redirectUri:$}})();try{return await A$}finally{A$=void 0}}function H$(){let $=$0;$0=[];for(let Z of $)P3(Z)}function X8($,Z,z=300000,X){return new Promise((Y,G)=>{if(X?.aborted){W$(Z),G(Error("Login cancelled"));return}let J=setTimeout(()=>{if(g.get(Z))W$(Z),G(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(J),g.get(Z))W$(Z),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);g.set(Z,{pkce:$,state:Z,resolve:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);G(H)}})})}async function Y8($){let Z=await fetch(`${K$}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":M3($)},body:JSON.stringify({client_id:Z0})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${K$}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function G8($,Z,z){let X=Math.max(parseInt($.interval,10)||5,1)*1000,Y=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(Y)&&Y>0?Y*1000:900000,J=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-J>G)throw Error("Device authorization expired");let B=await fetch(`${K$}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":M3(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let K=await B.json(),W=await fetch(`${K$}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:K.authorization_code,redirect_uri:`${K$}/deviceauth/callback`,client_id:Z0,code_verifier:K.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 H=G-(Date.now()-J);if(H<=0)throw Error("Device authorization expired");let Q=Math.min(X+s6,H);try{await i6(Q,void 0,{signal:z})}catch(K){if(K instanceof Error&&K.name==="AbortError")throw Error("Device authorization cancelled");throw K}}}async function B2($){let{label:Z,headless:z=!1,signal:X,version:Y}=$;if(t0(Z),z){let{deviceData:K,url:W,instructions:U}=await Y8(Y),N=(async()=>{let D=await G8(K,Y,X),M=Date.now(),q=e$(D);return{id:t0(Z||q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:D.access_token,refresh:D.refresh_token,expires:M+(D.expires_in??3600)*1000,enabled:!0,addedAt:M,lastUsed:M,lastRefreshedAt:M,accountId:q}})();return{url:W,instructions:U,completion:N}}let{redirectUri:G}=await z8(),J=await o6(),B=_3(crypto.getRandomValues(new Uint8Array(32)).buffer),H=t6(G,J,B),Q=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let K=await X8(J,B,void 0,X),W=Date.now(),U=e$(K);return{id:t0(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:K.access_token,refresh:K.refresh_token,expires:W+(K.expires_in??3600)*1000,enabled:!0,addedAt:W,lastUsed:W,lastRefreshedAt:W,accountId:U}}finally{W$(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}function z0($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let X=Z<100000000000?Z*1000:Z,Y=new Date(X);return Number.isNaN(Y.getTime())?void 0:Y.toISOString()}let z=new Date($);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function e0($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function L3($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function R3($,Z){let z=$.get(Z);if(z===null||z.trim()==="")return;let X=Number(z);if(!Number.isFinite(X)||X<0||X>100)return;let Y=Z.slice(0,-13),G=e0($.get(`${Y}-window-minutes`)),J=z0($.get(`${Y}-reset-at`)??void 0);if(X===0&&$.get(`${Y}-window-minutes`)==="0"&&!J)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:J,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var E3=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function A3($,Z){let z=$.get(Z);if(z===null)return"absent";if(z.trim()==="")return"invalid";let X=Number(z);return Number.isFinite(X)&&X>=0&&X<=100?"valid":"invalid"}function K2($){if(E3.some((G)=>A3($,G)==="invalid"))return{};let Z={},z=R3($,"x-codex-primary-used-percent");if(z)Z.primary=z;let X=R3($,"x-codex-secondary-used-percent");if(X)Z.secondary=X;let Y=J8($);if(Y)Z.credits=Y;return Z}function S3($,Z){let z=$.get(Z)?.trim();if(z===void 0)return;if(z.toLowerCase()==="true"||z==="1")return!0;if(z.toLowerCase()==="false"||z==="0")return!1;return}function J8($){let Z=S3($,"x-codex-credits-has-credits"),z=S3($,"x-codex-credits-unlimited");if(Z===void 0||z===void 0)return;let X=u($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:z,...X!==void 0?{balance:X}:{},checkedAt:Date.now()}}function W2($){let Z=E3.map((z)=>A3($,z));return Z.includes("valid")&&!Z.includes("invalid")}function x3($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=e0($.window_minutes),z=z0($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z}:{}}}function Q2($){let Z={},z=x3($.rate_limits?.primary);if(z)Z.primary=z;let X=x3($.rate_limits?.secondary);if(X)Z.secondary=X;let Y=B8($.credits);if(Y)Z.credits=Y;return Z}function B8($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let z=u(typeof Z.balance==="string"?Z.balance.trim():Z.balance);return{hasCredits:Z.has_credits,unlimited:Z.unlimited,...z!==void 0?{balance:z}:{},...typeof Z.overage_limit_reached==="boolean"?{overageLimitReached:Z.overage_limit_reached}:{},checkedAt:Date.now()}}function u($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function T3($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=e0($.limit_window_seconds),z=z0($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z/60}:{}}}function C3($){let Z={},z=T3($.rate_limit?.primary_window);if(z)Z.primary=z;let X=T3($.rate_limit?.secondary_window);if(X)Z.secondary=X;let Y=L3($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let G=L3($.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)Z.resetCreditsApplicable=G;let J=$.spend_control?.individual_limit;if($.spend_control===null||J===null)Z.spendControlCleared=!0;if(J&&typeof $.spend_control?.reached==="boolean"){let H=u(J.limit),Q=u(J.used),K=u(J.remaining),W=u(J.used_percent),U=u(J.remaining_percent);if(H!==void 0&&Q!==void 0&&K!==void 0&&W!==void 0&&U!==void 0)Z.spendControl={limit:H,used:Q,remaining:K,usedPercent:W,remainingPercent:U,resetsAt:z0(J.reset_at),unit:J.unit,source:J.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 H=u(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as e8}from"@cortexkit/claustrum-client";import{resolve as I3}from"node:path";import{storeIdentity as U8}from"@cortexkit/claustrum-client";import{SubcClient as b3}from"@cortexkit/subc-client";import{ClaustrumCredentialError as H8}from"@cortexkit/claustrum-client";import{SocketClosedError as K8,SocketTimeoutError as W8,SubcCallError as Q8}from"@cortexkit/subc-client";class F extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var $Z=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class Q$ extends F{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function i($){if($ instanceof Q$||$ instanceof K8||$ instanceof W8)return"unreachable";let Z=$ instanceof H8||$ instanceof Q8?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn($Z,Z))return"answered";return $Z[Z]}var ZZ=300000,X0=300000,zZ=1000;class I${#$;#z=0;restart(){this.#z=0}continuous($){let Z=$.kind==="changed"&&$.seq===this.#z+1&&(this.#$===void 0||$.epoch===this.#$);return this.#$=$.epoch,this.#z=$.seq,Z}}class Y0{#$;#z;#Y;#X=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#Y}request(){if(this.#Y)return this.#X=!0,this.#Y;return this.#Y=(async()=>{do{this.#X=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#X)})().finally(()=>{this.#Y=void 0}),this.#Y}}class G0{#$;#z=new I$;#Y;#X="polling";#H;#J;#Z=!1;#W;#Q=!1;#B=0;constructor($){this.#$=$,this.#Y=new Y0(async()=>{let Z=this.#Q;if(this.#Q=!1,Z||this.#W!==this.#$.view())await this.#$.discover(this.#W??"")},(Z)=>{if(!this.#Z)this.#$.onError?.(Z)})}get mode(){return this.#X}start(){if(this.#Z||this.#H||this.#J)return;if(typeof this.#$.client.watchScoped!=="function"){this.#G("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#Z)return;if(this.#Z=!0,this.#J)(this.#$.clearTimeoutImpl??clearTimeout)(this.#J);this.#J=void 0;let $=this.#H;this.#H=void 0,$?.handle.stop()}#G($,Z){if(this.#X===$)return;this.#X=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#J=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#J=void 0,!this.#Z)Z()},$),this.#J.unref?.()}async#V($){let Z;try{Z=await this.#$.enrollmentToken()}catch(J){if(this.#Z)return;this.#$.onError?.(J),this.#j("token-unreadable");return}let z=this.#$.client.watchScoped;if(this.#Z||this.#H||!z)return;this.#z.restart(),this.#Q=$;let X,Y;try{Y=z.call(this.#$.client,(J)=>{if(this.#Z||!X||this.#H!==X)return;if(X.notices++,X.notices===1)this.#$.onReachable?.(),X.acceptedAt=(this.#$.now??Date.now)(),this.#G("watching","accepted");if(!this.#z.continuous(J))this.#Q=!0;this.#W=J.view,this.#Y.request()},{enrollmentToken:Z})}catch(J){this.#$.onError?.(J),this.#j("watch-failed");return}X={handle:Y,notices:0},this.#H=X,this.#G("polling",$?"resubscribing":"opening");let G=X;Y.closed.then((J)=>this.#D(G,J),(J)=>this.#D(G,{kind:"transport_lost",error:J}))}#D($,Z){if(this.#Z||this.#H!==$)return;if(this.#H=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#G("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#j("refused");try{this.#$.onRefused(Z.error)}catch(z){this.#$.onError?.(z)}return}if($.notices>0){let z=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&z-$.acceptedAt>=300000)this.#B=0;let X=Math.min(1000*2**Math.min(this.#B,16),300000);this.#B++,this.#G("polling","resubscribing"),this.#U(X,()=>void this.#V(!0));return}this.#j(Z.kind)}#j($){this.#G("fallback",$),this.#U(300000,()=>void this.#V(!1))}}function k3($){let Z=$.identity??U8($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let z,X=!1,Y,G=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),J=(async()=>{if(z=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await b3.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),X)throw z.close(),Error("insula usage timeout");let B=await z.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await z.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([J,G])}finally{X=!0,clearTimeout(Y),z?.close()}},watchUsage(z){let X,Y,G=!1,J=(async()=>{let B,H=new Promise((K,W)=>{B=setTimeout(()=>W(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),Q=(async()=>{let K=Math.min($.handshakeTimeoutMs??3000,3000),W=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:K}):await b3.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:K});if(X=W,G){W.close();return}let U=await W.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(G){W.close();return}Y=W.subscribe(U,{method:"usage.watch"},z)})();try{await Promise.race([Q,H])}catch(K){throw G=!0,K}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{G=!0,X?.close()});return{stop(){if(G)return;G=!0,Y?.unsubscribe(),X?.close()},closed:J}}}}var B0=60000,f3=4*B0,D8=2*B0,XZ=new Map,J0=new Map;function b$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V8($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!b$(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function F8($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class y3{transport;key;#$=[];#z=!1;#Y=new Set;#X=new Map;#H=new Y0(async()=>{try{let $=await this.transport.getUsage();if(!b$($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>b$(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#Y=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#Y)this.#X.delete(Z)}catch{this.#$=[],this.#z=!1,this.#Y.clear()}},()=>{});#J=new I$;#Z="polling";#W=0;#Q=0;#B=new Map;#G;#U;#V={};#D=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#H.running)return this.#H.running;if(this.#Z==="watching")return Promise.resolve();for(let[z,X]of J0)if($-X>=B0)J0.delete(z);let Z=J0.get(this.key);if(Z!==void 0&&$-Z<B0)return Promise.resolve();return J0.set(this.key,$),this.#H.request()}watchMode(){return this.#Z}watch($={}){this.#W++;let Z=$.provider;if(Z===void 0)this.#Q++;else this.#B.set(Z,(this.#B.get(Z)??0)+1);if(this.#W===1)this.#V=$,this.#K();let z=!1;return()=>{if(z)return;if(z=!0,Z===void 0)this.#Q--;else{let X=(this.#B.get(Z)??1)-1;if(X>0)this.#B.set(Z,X);else this.#B.delete(Z)}if(--this.#W===0)this.#j()}}#j(){if(this.#U)(this.#V.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#G;this.#G=void 0,$?.handle?.stop(),this.#Z="polling"}#F($){this.#U=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#W>0&&!this.#G)this.#K()},$),this.#U.unref?.()}#K(){let $=this.transport.watchUsage;if(!$){this.#Z="fallback";return}this.#Z="polling",this.#J.restart();let Z={notices:0};this.#G=Z;let z;try{z=$.call(this.transport,(X)=>this.#N(Z,X))}catch(X){this.#q(Z,X);return}Z.handle=z,z.closed.then(()=>this.#q(Z,void 0),(X)=>this.#q(Z,X))}#N($,Z){if(this.#G!==$)return;if($.notices++,$.notices===1)this.#Z="watching";if($.notices===2)this.#D=0;let z=V8(Z);if(!z)this.#J.restart();if(!(z?this.#J.continuous(z):!1)||z?.provider===void 0||this.#Q>0||this.#B.has(z.provider))this.#H.request()}#q($,Z){if(this.#G!==$)return;this.#G=void 0;let z=F8(Z);if(z==="unknown_method"||z==="usage_watch_limit"){this.#Z="fallback";return}if($.notices>0){let X=Math.min(zZ*2**Math.min(this.#D,16),X0);this.#D++,this.#Z="polling",this.#F(X);return}if(this.#Z="fallback",this.#H.request(),Z===void 0||i(Z)==="unreachable")this.#F(X0)}current($,Z,z){for(let X of this.#$){if(X.provider!==$||typeof X.account!=="string"||X.account.trim()!==Z)continue;if(X.stale!==void 0||X.errorClass!==void 0||!b$(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=f3)continue;return{entry:X,context:{fetchedAt:Y,...typeof X.source==="string"&&{source:X.source}}}}return}lookup($,Z,z){if(!this.#z)return{miss:"unreachable"};let X=this.#$.find((J)=>J.provider===$&&typeof J.account==="string"&&J.account.trim()===Z),Y=(X??this.#$.find((J)=>J.provider===$&&J.account===void 0&&J.errorClass!==void 0))?.errorClass;if(Y==="upstream_failed")return{miss:"upstream-failed"};if(Y==="credential_absent"||Y==="credential_unusable"||Y==="credential_rejected")return{miss:"credential"};if(Y!==void 0)return{miss:"unreachable"};if(X){let J=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!b$(X.usage)||!Number.isFinite(J))return{miss:"unreachable"};let B={entry:X,context:{fetchedAt:J,...typeof X.source==="string"&&{source:X.source}}};return z>=J+f3||X.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#Y.has($))return{miss:"absent"};let G=this.#X.get($)??z;return this.#X.set($,G),{miss:z-G>=D8?"unreachable":"cold"}}}function YZ($,Z){let z=JSON.stringify([I3($.connectionFile),I3(Z)]),X=XZ.get(z);if(!X)X={source:new y3($,z),refs:0},XZ.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)XZ.delete(z)}}}import{ClaustrumCredentialError as E7}from"@cortexkit/claustrum-client";function GZ($){let Z=new AbortController,z=[],X=!1,Y=()=>{if(X)return;X=!0;for(let{source:B,listener:H}of z)B.removeEventListener("abort",H);z.length=0},G=(B)=>{if(X||Z.signal.aborted)return;Z.abort(B),Y()},J=$.find((B)=>B.aborted);if(J)return Z.abort(J.reason),{signal:Z.signal,dispose:Y};for(let B of $){if(Z.signal.aborted)break;let H=()=>G(B.reason);if(z.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)G(B.reason)}return{signal:Z.signal,dispose:Y}}import{ClaustrumCredentialError as J4}from"@cortexkit/claustrum-client";import{createHash as j8,randomBytes as N8,randomUUID as q8}from"node:crypto";import{constants as h3}from"node:fs";import{chmod as M8,mkdir as O8,open as d3,readFile as JZ,realpath as _8,rename as P8,stat as c3,unlink as KZ}from"node:fs/promises";import{basename as u3,dirname as n,extname as w3,isAbsolute as m3,join as WZ,resolve as L8}from"node:path";import{ClaustrumCredentialError as R8,ClaustrumClient as S8,writeEnrollmentTokenFile as x8}from"@cortexkit/claustrum-client";var T8=1,K0=16384,i3=30000,QZ=/^[0-9a-f]{64}$/,s3="unknown_method",n3=new Set([s3,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),a3=new Set(["pending_queue_full"]);function BZ($){if(!($ instanceof R8))return;if(n3.has($.code))return{code:$.code,disposition:"terminal"};if(a3.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function E8($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new F("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function A8($){return S8.connect($)}function o3($){let Z=w3($)||".json",z=u3($,w3($));return{statePath:WZ(n($),`${z}-state${Z}`),tokenPath:$}}function C8($){let Z=$.override?.trim();if(Z&&!m3(Z)&&!$.cwd)throw new F("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=Z?m3(Z)?Z:L8($.cwd,Z):WZ($.stateDir,`${$.host}-enrollment.json`);return o3(z)}function r3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H0($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function t3($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function f$(){return new F("invalid-state","invalid Claustrum enrollment state")}function U0($){if(!r3($)||$.version!==T8||typeof $.proposedName!=="string"||$.proposedName.length===0)throw f$();if($.phase==="pending"){if(!QZ.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!H0($.createdAt)||!H0($.updatedAt))throw f$();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)||!t3($.tokenGeneration)||!H0($.updatedAt))throw f$();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"||!H0($.updatedAt))throw f$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw f$()}function UZ($){if(!r3($)||!QZ.test(String($.token??""))||!t3($.token_generation))throw new F("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function I8($){if(!$.isFile())throw new F("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new F("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new F("unsafe-file","Claustrum enrollment file must be owned by the current user")}function g3($){try{return JSON.parse($)}catch{throw new F("invalid-state","Claustrum enrollment file is not valid JSON")}}async function a($){if(D$)try{await HZ(n($));let z=await Q0($,!0);if(Buffer.byteLength(z)>K0)throw new F("unsafe-file","Claustrum enrollment file is too large");return g3(z)}catch(z){if(z.code==="ENOENT")return;throw z}let Z;try{Z=await d3($,h3.O_RDONLY|h3.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new F("unsafe-file","Claustrum enrollment file could not be opened safely")}try{I8(await Z.stat());let z=Buffer.alloc(K0+1),{bytesRead:X}=await Z.read(z,0,z.byteLength,0);if(X>K0)throw new F("unsafe-file","Claustrum enrollment file is too large");return g3(z.subarray(0,X).toString("utf8"))}finally{await Z.close()}}function v3($,Z){let z=[];for(let X of $.split(`
|
|
88
|
+
`)){if(X.trim()===""||X.startsWith("#"))continue;let Y=X.split(":");if(Y.length!==Z||!/^[^\s:,]+$/.test(Y[0]??"")||!/^\d+$/.test(Y[2]??"")||!Number.isSafeInteger(Number(Y[2]))||Z===7&&(!/^\d+$/.test(Y[3]??"")||!Number.isSafeInteger(Number(Y[3])))||Z===4&&Y[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(Y[3]??""))return;z.push(Y)}return z}async function b8($,Z,z){try{let[X,Y]=await Promise.all([JZ(z.passwdPath??"/etc/passwd","utf8"),JZ(z.groupPath??"/etc/group","utf8")]),G=v3(X,7),J=v3(Y,4);if(!G||!J)return!1;let B=G.filter((W)=>Number(W[2])===$),H=J.filter((W)=>Number(W[2])===Z);if(B.length!==1||H.length!==1)return!1;let Q=B[0]?.[0],K=H[0]?.[3]??"";return(K===""||K.split(",").every((W)=>W===Q))&&!G.some((W)=>Number(W[2])!==$&&Number(W[3])===Z)}catch{return!1}}function e3($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>JZ(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function $4($,Z={}){if(!D$){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await _8($)}catch{return}let G;for(;;){let J=await c3(Y).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0){if(G===void 0)G=X!==void 0&&await b8(z,X,Z);if((J.mode&2)!==0||J.uid!==z||J.gid!==X||!G)throw new F("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=n(Y);if(B===Y)return;Y=B}}try{await p3($,e3(Z))}catch(z){if(!(z instanceof i0))throw z;throw new F("unsafe-file",`Claustrum enrollment parent refused: ${z.path} (${z.reason??z.code}). Use a folder that other users cannot write or replace.`)}}async function W0($,Z={}){if(D$){await HZ($,!1,e3(Z));return}await O8($,{recursive:!0,mode:448});let z=await c3($),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new F("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((z.mode&63)!==0)await M8($,448)}async function U$($,Z,z={}){let X=n($);await W0(X,z),await $4(X,z);let Y=`${JSON.stringify(Z)}
|
|
89
|
+
`;if(Buffer.byteLength(Y)>K0)throw new F("invalid-state","Claustrum enrollment state is too large");if(D$)return l3($,Y);let G=WZ(X,`.${u3($)}.${process.pid}.${q8()}.tmp`),J,B=!1;try{J=await d3(G,"wx",384),B=!0,await J.writeFile(Y,"utf8"),await J.chmod(384),await J.sync(),await J.close(),J=void 0,await P8(G,$),B=!1}finally{if(await J?.close().catch(()=>{}),B)await KZ(G).catch(()=>{})}}async function DZ($,Z){let z=await a($.tokenPath),X=z===void 0?void 0:UZ(z),Y=await a($.statePath),G=Y===void 0?void 0:U0(Y);if(X)return{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:X.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return s(G)}async function f8($,Z){let z;try{z=await DZ($,Z)}catch(X){if(!(X instanceof F)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await a($.statePath);if(Y===void 0)return"unreadable";let G=U0(Y);return G.phase==="approved"&&G.proposedName===Z?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in z&&z.proposedName!==Z)return"unreadable";if(z.state==="approved"||z.state==="blocked"&&z.code==="missing_token")return"vault";return"local"}async function o($){let Z=await a($);if(Z===void 0)throw new F("not-enrolled","Claustrum enrollment is not configured");return UZ(Z)}function s($){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 Z4(){return new F("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class z4{#$;#z;#Y;#X;#H;#J;#Z;constructor($){this.#Z=$.ancestorOptions??{},this.#$=$.client,this.#z=$.paths,this.#Y=$.proposedName,this.#X=$.now??Date.now,this.#H=$.mintSecret??(()=>N8(32).toString("hex")),this.#J=$.writeTokenFile??x8}async status(){return DZ(this.#z,this.#Y)}async resetTerminal(){return X4(this.#z,this.#Y)}async#W($,Z){let z={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#X()};return await U$(this.#z.statePath,z,this.#Z),s(z)}async reconcile(){await W0(n(this.#z.statePath),this.#Z);let $=await C({name:"ceremony",path:this.#z.statePath,ttlMs:i3,renew:!0});if(!$)return{state:"busy"};try{let Z=await a(this.#z.tokenPath),z=Z===void 0?void 0:UZ(Z),X=await a(this.#z.statePath),Y=X===void 0?void 0:U0(X);if(Y&&Y.proposedName!==this.#Y)throw Z4();if(z){if(!Y||Y.phase==="pending"){let J={version:1,phase:"approved",proposedName:Y?.proposedName??this.#Y,tokenGeneration:z.token_generation,updatedAt:this.#X()};await U$(this.#z.statePath,J,this.#Z),Y=J}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:z.token_generation}}if(Y?.phase==="approved"){let J={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await U$(this.#z.statePath,J,this.#Z),s(J)}if(Y&&Y.phase!=="pending")return s(Y);if(!Y){let J=this.#X();if(Y={version:1,phase:"pending",proposedName:this.#Y,requestSecret:this.#H(),createdAt:J,updatedAt:J},!QZ.test(Y.requestSecret))throw new F("invalid-state","invalid minted Claustrum enrollment secret");await U$(this.#z.statePath,Y,this.#Z)}if(!Y.requestId)try{let J=j8("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B=await this.#$.enrollPropose({name:Y.proposedName,requestSecretHash:J});Y={...Y,requestId:B.requestId,updatedAt:this.#X()},await U$(this.#z.statePath,Y,this.#Z)}catch(J){let B=BZ(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};if(B.code===s3)return await $.assertOwned(),await KZ(this.#z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:Y.proposedName,code:B.code};return this.#W(Y,B.code)}let G=Y.requestId;if(!G)return s(Y);try{let J=await this.#$.enrollPoll({requestId:G,requestSecret:Y.requestSecret});if(J.status==="pending")return s(Y);if(J.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#X()};return await U$(this.#z.statePath,H,this.#Z),s(H)}await W0(n(this.#z.tokenPath),this.#Z),await $4(n(this.#z.tokenPath),this.#Z),await this.#J(this.#z.tokenPath,{token:J.token,token_generation:J.tokenGeneration});let B={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:J.name,tokenGeneration:J.tokenGeneration,updatedAt:this.#X()};return await U$(this.#z.statePath,B,this.#Z),s(B)}catch(J){let B=BZ(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:G,retryCode:B.code};return this.#W(Y,B.code)}}finally{await $.release()}}}async function X4($,Z){await W0(n($.statePath));let z=await C({name:"ceremony",path:$.statePath,ttlMs:i3,renew:!0});if(!z)return"busy";try{if(await a($.tokenPath)!==void 0)return"refused-approved";let X=await a($.statePath);if(X===void 0)return"idle";let Y=U0(X);if(Y.proposedName!==Z)throw Z4();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await KZ($.statePath),"reset"}finally{await z.release()}}var k$="claustrum-tombstone:v1:";function D0($){return`${k$}${$}`}function VZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V0($){return typeof $==="string"&&$.startsWith(k$)}function Y4($,Z){if(!VZ($)||$.type!=="oauth")return!1;return $.refresh===D0(Z)}function G4($,Z){if(Y4($,Z))return"placeholder";if(VZ($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!V0($.refresh))return"login";if(VZ($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function k8($){let Z=G4($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new F("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 F("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function B4($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function y8($,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 jZ=I("claustrum");function qZ($,Z,z,X=jZ){let Y=B4(Z,z);return X.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:y8(Z,z)}),Y}var NZ=300000,H4=60000;function FZ(){return new F("invalid-material","Claustrum returned invalid credential material")}function h8($){let Z=$.trim();if(Z.startsWith("{")){let z;try{z=JSON.parse(Z)}catch{throw FZ()}if(!z||typeof z!=="object")throw FZ();let X=z,Y=X.access_token??X.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(k$))throw FZ();return Z}function w8($,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 m8($){let{grants:Z,grantTuples:z}=$;if(Z===void 0||z===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(z.map(({selectorKind:X,selector:Y,operation:G})=>Object.freeze({selectorKind:X,selector:Y,operation:G})))})}class F0{#$;#z;#Y;#X;#H;#J;#Z;#W=new WeakMap;#Q=new WeakMap;#B=new Map;#G=new WeakMap;#U;#V;#D=!1;#j=new Q$;#F;#K=!1;#N=-1/0;#q=2000;#M=!1;#_;#P=new Set;constructor($){let Z=$.tokenPath;if($.readToken)this.#z=$.readToken;else if(Z)this.#z=()=>o(Z);else throw new F("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#X=$.family,this.#H=$.parseIdentity,this.#J=$.requireAssertion??!1,this.#Y=$.now??Date.now,this.#Z=$.logger??jZ,this.#U=$.setTimeoutImpl??setTimeout,this.#V=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#M||this.#D)return;this.#D=!0,this.#j=$ instanceof J4?$:new Q$,this.#Z.warn("serving kept vault receipt",{reason:"unreachable"}),this.#L()}reachable(){if(this.#M||!this.#D)return;if(this.#D=!1,this.#F)this.#V(this.#F);this.#F=void 0,this.#q=2000;for(let $ of this.#B.values())$.since=null;(this.#Z.info??jZ.info)("vault receipt serving resumed",{reason:"reachable"})}#L(){if(this.#M||!this.#D||this.#F||this.#K)return;this.#F=this.#U(()=>{this.#F=void 0,this.#R(!0)},this.#q),this.#F.unref?.()}#R($=!1){if(this.#M||!this.#D||this.#K)return;if(this.#Y()-this.#N<1000){this.#L();return}this.#N=this.#Y(),this.#K=!0,this.#T().catch(()=>{if($&&this.#D)this.#q=Math.min(this.#q*2,30000)}).finally(()=>{this.#K=!1,this.#L()})}#O($){if(this.#M)throw new F("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#S($){this.#O($);let Z=await this.#z();if(this.#O($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new F("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#x($,Z){this.#O(Z);let z,X;try{let Y=$();z=Z?await Promise.race([Y,new Promise((G,J)=>{let B=()=>J(Z.reason);if(Z.addEventListener("abort",B,{once:!0}),X=()=>Z.removeEventListener("abort",B),Z.aborted)B()})]):await Y}catch(Y){if(this.#O(Z),i(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof J4)throw Y;if(i(Y)==="unreachable")throw new Q$;throw new F("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#O(Z),this.reachable(),z}async discover($){let Z=await this.#T($);return this.#_=Z.view,Z}async#T($){let Z,z;try{z=await this.#S($)}catch(H){throw this.#B.clear(),H}try{Z=await this.#x(()=>this.#$.listScoped(z),$)}catch(H){throw this.listFailed(H),H}let X=[],Y=[],G=new Map;for(let H of Z.rows){let Q=w8(H,this.#X);if(!Q)continue;Y.push({row:H,type:Q}),G.set(H.id,(G.get(H.id)??0)+1)}let J=[];for(let{row:H,type:Q}of Y){let K;if(!H.id.trim())K="empty credential id";else if((G.get(H.id)??0)>1)K="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())K="blank account identity";else if(!H.state.trim())K="empty state";if(K){X.push({...H.id.trim()&&{credentialId:H.id},reason:K});continue}J.push(Object.freeze({credentialId:H.id,credentialType:Q,...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of X)this.#Z.warn("skipped malformed vault record",H);let B=m8(Z);return{view:Z.view,credentials:Object.freeze(J),skipped:Object.freeze(X),...B&&{grantReach:B}}}listFailed($){if(i($)==="unreachable")this.transportLost($);else this.reachable(),this.#B.clear()}forget($){this.#B.delete($)}retain($){let Z=new Map($.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#B){let Y=Z.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}}keptReceiptState(){let $=null;for(let[Z,z]of this.#B){if(!this.#E(z.attempt)){this.forget(Z);continue}if(z.since!==null)$=Math.min($??z.since,z.since)}return Object.freeze({active:$!==null,since:$})}#E($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#Y()>H4}async authorize($,Z,z="vault"){this.#O(Z);let{credentialId:X,credentialType:Y,accountIdentity:G}=$,J=this.#B.get(X);if(J&&(J.attempt.credentialType!==Y||J.attempt.expectedAccountIdentity!==G))this.forget(X),J=void 0;let B;try{B=await this.#S(Z)}catch(H){throw this.#B.clear(),H}if(this.#D&&J)return this.#R(),this.#A(X,J,B,z);try{let H=await this.#C({credentialId:X,credentialType:Y,accountIdentity:G},B,Z);return this.#B.set(X,{attempt:H,routeId:z,since:null}),H}catch(H){if(this.#O(Z),i(H)!=="unreachable")throw this.forget(X),H;return this.#A(X,J,B,z,H)}}#A($,Z,z,X,Y=this.#j){if(!Z||this.#B.get($)!==Z||!this.#E(Z.attempt))throw this.forget($),Y;if(Z.since===null)Z.since=this.#Y();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#W.set(G,z),this.#G.set(G,X),G}async#C($,Z,z){if(!$.credentialId)throw new F("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:G}=$;if(this.#J&&G===void 0)throw new F("identity-unasserted","Claustrum dispatch requires a known account identity");let J=await this.#x(()=>this.#$.getScoped({credentialId:X,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:NZ}}),z);if(J.credentialId!==void 0&&J.credentialId!==X)throw new F("identity-changed","Claustrum served credential identity changed");let B=J.expiresAtMs;if(!Number.isSafeInteger(J.recordVersion)||J.recordVersion<0||B===null&&Y==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#Y()<NZ))throw new F("insufficient-validity","Claustrum served credential has insufficient validity");let H=h8(J.material),Q=J.accountId?.trim()?J.accountId:void 0;if(this.#J&&(J.credentialId===void 0||Q===void 0))throw new F("identity-unasserted","Claustrum served credential did not assert its identity");let K=Q===void 0?this.#H?.(H):void 0,W=Q??K;if(G!==void 0&&W!==void 0&&W!==G)throw new F("identity-changed","Claustrum served credential identity changed");let U=W??G,D=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...U!==void 0&&{accountIdentity:U},accountIdentitySource:Q!==void 0?"asserted":K!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...J.credentialId!==void 0&&{assertedCredentialId:J.credentialId},...Q!==void 0&&{assertedAccountIdentity:Q},...J.projectId!==void 0&&{projectId:J.projectId},recordVersion:J.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#W.set(D,Z),D}async reportFailure($,Z,z){if(Z!==401)return;this.#O();let X=this.#W.get($);if(!X)throw new F("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#G.get($);if(Y!==void 0){this.forget($.credentialId),this.#Z.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let G=this.#B.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let J=this.#Q.get($);if(J)return J;let B=this.#x(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:$.recordVersion,reporterSource:z}));this.#Q.set($,B);try{await B,this.#Z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:z})}catch(H){throw this.#Q.delete($),H}}watchRoster($){this.#O();let Z=new G0({client:this.#$,enrollmentToken:()=>this.#S(),view:$.view??(()=>this.#_),discover:async(z)=>{await $.onView(z)},onRefused:(z)=>{this.listFailed(z),$.onRefused?.(z)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#Z,now:this.#Y,setTimeoutImpl:this.#U,clearTimeoutImpl:this.#V});return this.#P.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#P.delete(Z),Z.stop()}}}close(){if(this.#M)return;if(this.#M=!0,this.#F)this.#V(this.#F);this.#F=void 0;for(let $ of this.#P)$.stop();this.#P.clear(),this.#B.clear(),this.#$.close()}}import{resolve as IZ}from"node:path";function K4($,Z=""){let z=new Map,{observation:X}=$,Y=(B,H,Q)=>z.set(`${Z}:${B}`,{at:H,order:0,publication:{...$,observation:Q}}),G=(B,H)=>JSON.stringify([B??"all",H]),J=new Set;for(let B of X.readings??[]){let H=G(B.scope,B.label);J.add(H),Y(H,X.checkedAt,{checkedAt:X.checkedAt,readings:[{...B}]})}for(let B of X.coverage??[]){let H=G(B.scope,B.label);if(!J.has(H))Y(H,X.checkedAt,{checkedAt:X.checkedAt,coverage:[{...B}]})}if(X.budget)Y("budget",X.checkedAt,{checkedAt:X.checkedAt,budget:{...X.budget}});for(let[B,H]of Object.entries(X.counters??{}))Y(`counter:${B}`,H.checkedAt,{checkedAt:X.checkedAt,counters:{[B]:{...H}}});if(X.credits)Y("credits",X.credits.checkedAt,{checkedAt:X.checkedAt,credits:{...X.credits}});if(!z.size)Y("empty",X.checkedAt,{checkedAt:X.checkedAt});return z}import{createHash as g8}from"node:crypto";import{resolve as U4}from"node:path";function W4($,Z,z){if($.accountIdentity!==void 0&&z!==void 0)return $.accountIdentity===z;return $.credentialId===Z}function MZ($,Z,z){return $.some((X)=>W4(X,Z,z))}function OZ($,Z,z){let X={credentialId:Z,...z!==void 0&&{accountIdentity:z}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==z),X]}function _Z($,Z,z){return $.filter((X)=>!Z.some((Y)=>W4(X,Y,z)))}var D4="vault:";function v8($){return g8("sha256").update($).digest("hex")}function p8($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function l8($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function r($){return[$.credentialId,...$.aliases??[]]}function V4($,Z,z={}){let X=z.now??Date.now(),Y=z.routePrefix??D4,G=z.reservedRouteIds??new Set,J=$?.rows??[],B=[...$?.declined??[]],H=Z.skipped.length===0,Q=new Set(Z.credentials.map((V)=>V.credentialId)),K=new Set(Z.skipped.flatMap((V)=>V.credentialId===void 0?[]:[V.credentialId])),W=Z.skipped.some((V)=>V.credentialId===void 0),U=(V)=>!Q.has(V)&&(K.has(V)||W),N=new Map;for(let V of J){if(V.accountIdentity===void 0)continue;for(let O of r(V))if(!N.has(O))N.set(O,V.accountIdentity)}let D=new Map;for(let V of Z.credentials){let O=V.accountIdentity!==void 0?{credential:V,identity:V.accountIdentity,claimed:!0}:{credential:V,identity:N.get(V.credentialId),claimed:!1},l=l8(O),d=D.get(l)??[];d.push(O),D.set(l,d)}let M=new Set,q=new Set(G),L=[],T=(V,O)=>V.credential.credentialId.localeCompare(O.credential.credentialId),p=[...D.values()].map((V)=>V.toSorted(T)).sort((V,O)=>V[0]&&O[0]?T(V[0],O[0]):0);for(let V of p){let O=V[0]?.identity,l=V.filter((_)=>_.credential.state==="active"),d=l.length?l:V,E0=d.filter((_)=>_.claimed),d$=E0.length?E0:d,A0=new Set(V.map((_)=>_.credential.credentialId)),lZ=J.find((_)=>!M.has(_)&&r(_).some((q$)=>A0.has(q$))&&(_.accountIdentity===void 0||_.accountIdentity===O)),C0=d$.find((_)=>_.credential.credentialId===lZ?.credentialId)??d$[0];if(!C0)continue;let E=C0.credential,k=lZ??(O===void 0?void 0:J.find((_)=>!M.has(_)&&_.accountIdentity===O));if(k)M.add(k);let z$=k?.routeId;if(!z$||G.has(z$)){let _=`${Y}${E.credentialId}${O===void 0?"":`~${v8(O).slice(0,10)}`}`;z$=_;for(let q$=2;q.has(z$);q$++)z$=`${_}~${q$}`}q.add(z$);let B6=k?r(k).filter(U):[],I0=[...new Set([...V.map((_)=>_.credential.credentialId),...B6])].filter((_)=>_!==E.credentialId).sort((_,q$)=>_.localeCompare(q$)),H6=z.mapAccount?.(E)??{};L.push({previousIndex:k?J.indexOf(k):1/0,row:{routeId:z$,credentialId:E.credentialId,credentialType:E.credentialType,...O!==void 0&&{accountIdentity:O},...I0.length&&{aliases:I0},state:E.state,label:H6.label?.trim()||p8(E),...E.email!==void 0&&{email:E.email},...E.orgName!==void 0&&{orgName:E.orgName},enabled:![E.credentialId,...I0].some((_)=>MZ(B,_,O)),addedAt:k?.addedAt??X,...k?.quota!==void 0&&{quota:k.quota},...!C0.claimed&&O!==void 0&&{unclaimed:!0}}})}return J.forEach((V,O)=>{if(M.has(V)||!r(V).some(U))return;if(q.has(V.routeId))return;let[l,...d]=r(V).filter((A0)=>!Q.has(A0));if(l===void 0)return;q.add(V.routeId);let{aliases:E0,...d$}=V;L.push({previousIndex:O,row:{...d$,credentialId:l,...d.length&&{aliases:d},stale:!0}})}),L.sort((V,O)=>V.previousIndex===O.previousIndex?V.row.credentialId.localeCompare(O.row.credentialId):V.previousIndex-O.previousIndex),{version:1,view:Z.view,complete:H,...!H&&{rejected:Z.skipped.map((V)=>({...V.credentialId!==void 0&&{credentialId:V.credentialId},reason:V.reason}))},rows:L.map((V)=>V.row),declined:B}}function PZ($){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 y$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function P$($){return $===void 0||typeof $==="string"}function d8($){let Z=y$($)?Y$($.quota):void 0;if(!y$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!P$($.accountIdentity)||!P$($.email)||!P$($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((z)=>typeof z==="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 c8=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function Q4($){if(!Array.isArray($))return;let Z=[];for(let z of $){if(!y$(z)||!P$(z.credentialId)||typeof z.reason!=="string"||!c8.has(z.reason))return;Z.push(z)}return Z}function u8($){if(!y$($)||$.version!==1||!P$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!Q4($.rejected))throw new F("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let G=d8(Y);if(!G)throw new F("invalid-state","Claustrum roster file is not valid");Z.push(G)}let z=[];for(let Y of $.declined){if(!y$(Y)||typeof Y.credentialId!=="string"||!P$(Y.accountIdentity))throw new F("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=Q4($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...X&&{rejected:X},rows:Z,declined:z}}async function b($){let Z;try{Z=await Q0($,D$)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse(Z)}catch{throw new F("invalid-state","Claustrum roster file is not valid")}return u8(z)}var i8={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},s8={name:"claustrum-roster",ttlMs:30000};async function V$($,Z,z={}){return n0($,{...i8,signal:z.signal},async(X)=>{let Y=await b($),{next:G,result:J}=await Z(Y,{assertOwned:()=>X.assertOwned()});if(G)await X.assertOwned(),await m($,G,{beforeRename:async()=>{await z.beforePublish?.(),z.signal?.throwIfAborted(),await X.assertOwned()}});return J})}function LZ($,Z){return V$($,(z)=>{let X=z?.rows.find((G)=>G.routeId===Z);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");let Y=OZ(z.declined,X.credentialId,X.accountIdentity);return{next:{...z,declined:Y,rows:z.rows.map((G)=>G===X?{...G,enabled:!1}:G)},result:void 0}})}function RZ($,Z){return V$($,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===Z);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:_Z(z.declined,r(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function n8($){return new F("invalid-order",$)}function a8($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let z=new Set($.map((G)=>G.routeId)),X=new Set;for(let G of Z){if(typeof G!=="string")return"route ids must be an array of route ids";if(X.has(G))return`route id ${G} appears more than once`;if(!z.has(G))return`route id ${G} is not in the roster`;X.add(G)}let Y=[...z].filter((G)=>!X.has(G)).length;if(Y>0)return`the order leaves out ${Y} roster route id${Y===1?"":"s"}`;return}function SZ($,Z,z={}){return V$($,(X)=>{let Y=X?.rows??[],G=a8(Y,Z);if(G)throw n8(G);let J=new Map;for(let Q of Y){let K=J.get(Q.routeId);if(K)K.push(Q);else J.set(Q.routeId,[Q])}let B=[...Z],H=B.flatMap((Q)=>J.get(Q)??[]);if(!X||H.every((Q,K)=>Q===Y[K]))return{result:{ids:B,outcome:"unchanged"}};return{next:{...X,rows:H},result:{ids:B,outcome:"reordered"}}},{...z.signal&&{signal:z.signal}})}function o8($,Z){if(!r($).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")&&r($).length===1)return"bind";return"refuse"}async function xZ($,Z){let{routeId:z,observation:X,...Y}=Z;return F4($,{routeId:z,observation:X,accountIdentity:Y.accountIdentity,receipt:Y})}async function F4($,Z){if(!O$(Z.observation))return!1;let z=h($,await b($));if(!t(z,Z).kept)return!1;return j4($,Z)}function TZ($,Z){return F4($,Z)}function t($,Z){let z=$?.rows.find((J)=>J.routeId===Z.routeId),X=!z?"refuse":Z.receipt?o8(z,Z.receipt):z.accountIdentity!==void 0&&z.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!z||X==="refuse")return{roster:$,kept:!1};let Y=x$(z.quota,Z.observation),G=X==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((J)=>J===z?{...J,...G,quota:Y}:J)},kept:!0}}var j0=new Map;function EZ($){j0.delete(U4($))}async function AZ($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){EZ($.path);return}let z=await C({...s8,path:$.path,renew:!0});if(!z){let G=await b($.path);if($.signal?.throwIfAborted(),!G?.view)throw new F("roster-busy","Claustrum account discovery is already in progress");return G}let X=U4($.path),Y;try{let G=await b($.path),J=j0.get(X);Y=J&&(J.previousView===G?.view||J.inventory.view===G?.view)?J:{inventory:await $.custody.discover($.signal),previousView:G?.view},j0.delete(X);let{inventory:B}=Y;return $.onInventory?.(B),$.signal?.throwIfAborted(),await V$($.path,async(H)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await z.assertOwned();let Q=typeof $.projection==="function"?$.projection():$.projection,K=V4(H,B,Q);return{...JSON.stringify(H)!==JSON.stringify(K)&&{next:K},result:K}},{beforePublish:async()=>{$.signal?.throwIfAborted(),await z.assertOwned()}})}catch(G){if(G instanceof s0&&Y&&!$.signal?.aborted&&await Z())j0.set(X,Y);throw G}finally{await z.release()}}var L$=new Map,r8=I("claustrum"),N4=100;function q4($){let Z=IZ($),z=L$.get(Z);if(!z)z={path:Z,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,failures:0,draining:!1,order:0},L$.set(Z,z);return z}function M4($,Z){let z=q4($);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():CZ($)})()}function t8($){return K4($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function j4($,Z){if(!O$(Z.observation))return Promise.resolve(!1);let z=q4($),X=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),Y=z.pending.get(X)??new Map;for(let[G,J]of t8(Z)){let B=Y.get(G);if(!B||J.at>=B.at){if(J.order=++z.order,J.publication.observation.coverage)J.priorReading=B?.publication.observation.readings?B.publication:B?.priorReading;Y.set(G,J)}}if(Y.size)z.pending.set(X,Y);for(let G of z.listeners)G(Z);return _4(z,N4),Promise.resolve(!0)}function O4($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,z)=>Z.order-z.order)}function h($,Z){let z=L$.get(IZ($));if(z)for(let X of O4(z.pending)){if(X.priorReading)Z=t(Z,X.priorReading).roster;Z=t(Z,X.publication).roster}return Z}function _4($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;if($.timer=setTimeout(()=>{$.timer=void 0,P4($)},Z),!$.draining)$.timer.unref?.()}function P4($){if($.running||$.abort.signal.aborted)return;let Z=new Map([...$.pending].map(([z,X])=>[z,new Map(X)]));$.running=(async()=>{try{await V$($.path,(z)=>{let X=z;for(let Y of O4(Z)){if(Y.priorReading)X=t(X,Y.priorReading).roster;X=t(X,Y.publication).roster}return{...X!==z&&{next:X},result:void 0}},{signal:$.abort.signal});for(let[z,X]of Z){let Y=$.pending.get(z);for(let[G,J]of X)if(Y?.get(G)===J)Y.delete(G);if(!Y?.size)$.pending.delete(z)}$.failures=0}catch(z){if(!$.abort.signal.aborted&&$.failures++===0)r8.warn("vault quota publication delayed; retrying",{error:z instanceof Error?z.message:String(z)})}finally{$.running=void 0;for(let X of $.wake)X();let z=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):N4;_4($,z)}})()}async function CZ($,Z=1000){let z=IZ($),X=L$.get(z);if(!X)return;X.draining=!0,clearTimeout(X.timer),X.timer=void 0;let Y,G,J=new Promise((B)=>{G=()=>{if(!X.pending.size||X.abort.signal.aborted)B()},X.wake.add(G),G()});try{if(X.pending.size)P4(X);await Promise.race([J,new Promise((B)=>{Y=setTimeout(B,Math.max(0,Z))})])}finally{if(clearTimeout(Y),G)X.wake.delete(G);if(X.draining=!1,!X.listeners.size){if(X.abort.abort(),clearTimeout(X.timer),X.pending.clear(),L$.get(z)===X)L$.delete(z)}}}class L4{#$;#z=new AbortController;#Y;#X;#H;#J;#Z;#W;#Q;#B=!1;#G;#U;#V;#D=new Map;#j;#F;constructor($){this.#$=$,this.#Y=$.logger??I("claustrum"),this.#F=M4($.rosterPath,(Z)=>{this.#Z=t(this.#Z,Z).roster})}#K($){this.#z.signal.throwIfAborted(),$?.throwIfAborted()}async#N(){return await this.#$.isCustodyActive?.()??!0}#q($,Z){let z=GZ([this.#z.signal,...Z?[Z]:[]]);return new Promise((X,Y)=>{let G=()=>{z.signal.removeEventListener("abort",J),z.dispose()},J=()=>{G(),Y(z.signal.reason)};if(z.signal.addEventListener("abort",J,{once:!0}),$.then((B)=>{if(G(),z.signal.aborted)Y(z.signal.reason);else X(B)},(B)=>{G(),Y(B)}),z.signal.aborted)J()})}async#M(){if(this.#K(),this.#X)return this.#X;if(!this.#H)this.#H=this.#$.connect().then(($)=>{if(this.#z.signal.aborted)$.close(),this.#K();if(this.#X=new F0({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Y,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&$.insula)this.#G=YZ($.insula,this.#$.tokenPath);return this.#X}).finally(()=>{this.#H=void 0});return this.#q(this.#H)}snapshot(){return this.#Z}grantReach(){let $=this.#W;return $&&this.#Z?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#U?.mode??"polling",...this.#$.insula&&{insula:this.#G?.source.watchMode()??"polling"}})}#_(){this.#U?.close(),this.#U=void 0,this.#V?.(),this.#V=void 0}keptReceiptState(){return this.#X?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return PZ(this.#Z)}refresh(){if(this.#K(),this.#J)return this.#J;return this.#J=(async()=>{if(!await this.#N()){this.#Z=void 0,this.#W=void 0,this.#_(),this.#X?.close(),this.#X=void 0,this.#G?.release(),this.#G=void 0;return}let $=await this.#M(),Z,z=await AZ({path:this.#$.rosterPath,custody:$,onInventory:(Y)=>{Z=Y},isActive:()=>this.#N(),signal:this.#z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#K();let X=z?.view!==this.#Z?.view;if(this.#Z=h(this.#$.rosterPath,z),$.retain(z?.rows??[]),Z&&z?.view!==void 0)this.#W=Z.grantReach?{view:z.view,reach:Z.grantReach}:void 0;if(z&&X)this.#$.onRoster?.(z);return this.#j=(this.#$.now??Date.now)(),z})().finally(()=>{this.#J=void 0}),this.#J}start(){if(this.#B)return;this.#K(),this.#B=!0;let $=async()=>{try{if(await this.#P())await this.refresh();await this.refreshInsulaQuota(),this.#L()}catch(z){if(!this.#z.signal.aborted)this.#$.onError?.(z)}if(this.#z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#Q=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#Q=void 0,$()},Z),this.#Q.unref?.()};$()}async#P(){if(this.#U?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#j===void 0||$-this.#j>=ZZ)return!0;return!await this.#N()}#L(){let $=this.#X;if(this.#z.signal.aborted||!$)return;if(this.#U??=$.watchRoster({view:()=>this.#Z?.view,onView:async()=>{while(this.#J)await this.#J.catch(()=>{});await this.refresh()},onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#G&&!this.#V)this.#V=this.#G.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#z.signal.aborted||!await this.#N())return;try{await o(this.#$.tokenPath),await this.#M(),await this.#G?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#z.signal.aborted||!await this.#N())return;try{return await o(this.#$.tokenPath),this.#R($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#z.signal.aborted||!await this.#N())return;try{await o(this.#$.tokenPath);let z=h(this.#$.rosterPath,await b(this.#$.rosterPath))?.rows.find((X)=>X.routeId===$);return this.#R(z?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#z.signal.aborted||!await this.#N())return{miss:"unreachable"};try{await o(this.#$.tokenPath);let X=h(this.#$.rosterPath,await b(this.#$.rosterPath))?.rows.find((J)=>J.routeId===$)?.accountIdentity;if(!X||!this.#G)return{miss:"unreachable"};let Y=this.#G.source.lookup(Z.provider,X,(this.#$.now??Date.now)()),G=Y.reading&&Z.normalize(Y.reading.entry,Y.reading.context);if(Y.miss)return{miss:Y.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let z=await this.lookupInsulaQuotaForRoute($);if(z.miss==="cold"||z.miss==="upstream-failed"){if(this.#D.get($)!==z.miss)this.#D.set($,z.miss),this.#Y.warn("skipped insula provider poll",{reason:z.miss});return}return this.#D.delete($),z.miss?Z():z.reading}#R($){if(!this.#$.insula||!$)return;let Z=this.#G?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#K(Z);let z=this.#Z??await this.#q(this.refresh(),Z);if(!z||!await this.#N())throw this.#X?.close(),this.#X=void 0,this.#_(),this.#G?.release(),this.#G=void 0,new F("not-active","Claustrum scoped custody is not active");let X=h(this.#$.rosterPath,await b(this.#$.rosterPath));this.#K(Z);let Y=z.rows.find((H)=>H.routeId===$),G=X?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(Y)this.#X?.forget(Y.credentialId);throw new F("route-declined","Claustrum route is disabled")}if(!Y||!G||G.state!=="active"||G.credentialId!==Y.credentialId||G.accountIdentity!==Y.accountIdentity||G.credentialType!==Y.credentialType){if(Y)this.#X?.forget(Y.credentialId);throw new F("route-unavailable","Claustrum route is disabled, removed or changed")}let J=await this.#q(this.#M(),Z),B=GZ([this.#z.signal,...Z?[Z]:[]]);try{return await J.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},B.signal,$)}finally{B.dispose()}}async reportFailure($,Z,z){if(this.#K(),!this.#X)throw new F("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.reportFailure($,Z,z)}async send($,Z,z){let X=z.signal,Y=await this.authorize($,X),G=await Z(Y,X);if(G.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,z.reporterSource??"direct"),G;if(G.status===401&&!X?.aborted){let J;try{J=await this.authorize($,X),X?.throwIfAborted()}catch(B){if(X?.aborted)throw B}if(qZ(z.site,Y,J,this.#Y))await G.body?.cancel().catch(()=>{}),Y=J,G=await Z(J,X)}if(G.status===401)await this.reportFailure(Y,401,z.reporterSource??"direct").catch((J)=>this.#$.onError?.(J)),Promise.resolve().then(()=>this.refresh()).catch((J)=>{if(!this.#z.signal.aborted)this.#$.onError?.(J)});return G}async decline($){this.#K(),await LZ(this.#$.rosterPath,$),this.#Z=h(this.#$.rosterPath,await b(this.#$.rosterPath)),this.#X?.retain(this.#Z?.rows??[])}async accept($){this.#K(),await RZ(this.#$.rosterPath,$),this.#Z=h(this.#$.rosterPath,await b(this.#$.rosterPath))}async reorder($){this.#K();let Z=await SZ(this.#$.rosterPath,$);return this.#Z=h(this.#$.rosterPath,await b(this.#$.rosterPath)),Z}async recordQuota($,Z,z){return this.#K(),xZ(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:z.credentialId,accountIdentitySource:z.accountIdentitySource,...z.accountIdentity!==void 0&&{accountIdentity:z.accountIdentity},...z.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:z.expectedAccountIdentity}})}async recordAccountQuota($,Z,z){return this.#K(),TZ(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:z})}close(){if(this.#z.signal.aborted)return;if(this.#z.abort(new F("closed","Claustrum consumer is closed")),this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0,this.#_(),this.#X?.close(),this.#G?.release(),this.#G=void 0,this.#Z=void 0,this.#W=void 0,this.#F(),EZ(this.#$.rosterPath)}async dispose(){this.close(),await this.#F()}}async function S7($){let Z=await e8.connect($);return Object.assign(Z,{insula:k3($)})}var R4=D0("openai");function S4($){return V0($)}function F$($){if(!$||$.corrupt===!0)return!1;return S4($.refresh)}class h$ 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 N0($){if(S4($))throw new h$}var $9=I("quota"),bZ="primary",fZ="secondary",Z9="app_EMoamEEZ73f0CkXaXp7hrann",z9="https://auth.openai.com";async function s7($){N0($.refreshToken);let Z=await $.fetchImpl(`${z9}/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:Z9}).toString()});if(!Z.ok){let Y=r0(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:Y,isRefreshError:!0})}let z=await Z.json();if(!z||typeof z.access_token!=="string"||!z.access_token||typeof z.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});if(z.refresh_token!==void 0&&typeof z.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});let X=typeof z.refresh_token==="string"&&z.refresh_token?z.refresh_token:$.refreshToken;return{access:z.access_token,refresh:X,expires:$.now()+z.expires_in*1000,expiresIn:z.expires_in}}var X9="https://chatgpt.com/backend-api/wham/usage";async function n7($){let Z=$.logger??$9,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await $.fetchImpl(X9,{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(!Y.ok){let J=r0(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:J})}let G=C3(await Y.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:Y.status,elapsedMs:Date.now()-X}),G}catch(Y){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof Y?.status==="number"?Y.status:"error",elapsedMs:Date.now()-X,error:x4(Y)}),Y}}import{createHash as Y9}from"node:crypto";var G9=globalThis.setTimeout,J9=5;function w$($){let Z=$?.quota?.checkIntervalMinutes??J9;return Math.max(1,Z)*60000}function B9($){return $?.quota?.enabled!==!1}function q0($,Z){if(!$?.resetsAt)return!1;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z<=Z}function Z5($,Z,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let G=Z===bZ?$?.primary:Z===fZ?$?.secondary:void 0,J=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(J)&&J>z)return J;return z+X}function H9($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function T4($,Z,z){if(!B9(Z))return z+w$(Z);let X=H9(Z),Y=[];for(let G of["primary","secondary"]){let J=$?.[G];if(!J)continue;if(J.remainingPercent>=X[G])continue;let B=J.resetsAt?Date.parse(J.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=z)return z+w$(Z);Y.push(B)}if(!Y.length)return z+w$(Z);return Math.min(...Y)+60000}function K9($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function W9($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function f($){return Y9("sha256").update($).digest("hex").slice(0,16)}class e{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!==f($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let z=this.fallbacks.get($)??null;if(!Z||!z)return z;if(this.fallbackTokenFps.get($)!==f(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!E4(Z.quota))return;if(this.mainTokenFp=f($),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=Z,kZ(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let z=this.fallbacks.get($)??null;if(Z&&z?.accountId&&z.accountId!==Z)return null;return z}setFallback($,Z,z,X=!1,Y){if(!X&&!E4(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(Y&&G&&Y!==G)this.clearRateLimited($);let J=Y??G;if(this.fallbacks.set($,{...Z,accountId:J}),z)this.fallbackTokenFps.set($,f(z));else this.fallbackTokenFps.delete($);if(kZ(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let z=this.rateLimitedUntilMap.get($);if(z!==void 0&&z>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=f($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let z=e.fallbackInflightKey($,Z),X=this.inflightFallbacks.get(z);if(X)return X;if(this.isFallbackBackedOff($,Z)){let G=this.getFallback($,Z);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let Y=this._fetchFallback($,Z);return this.inflightFallbacks.set(z,Y),Y}async refreshAllFallbacks($){let Z=this.now();for(let z of $){if(z.enabled===!1)continue;if(F$(z)||!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&Z<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground($){let Z=f($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale($,Z){let z=this.getFallback($,Z);if(!z)return!0;return this.now()>=z.refreshAfter}shouldRefreshOnRequestCount($){let Z=W9(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($){return this.isMainStale()||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let z=K9($);if(!z)return;let X=Z?f(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:T4(z.quota,$,z.checkedAt),checkedAt:z.checkedAt};if(this.main&&this.main.checkedAt>=Y.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=Y,this.mainTokenFp=z.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&_$(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=w$(this.storage);for(let z of $){if(z.enabled===!1)continue;if(!z.quota)continue;let X=Math.max(z.quota.primary?.checkedAt??0,z.quota.secondary?.checkedAt??0);if(X<=0)continue;let Y=this.getFallback(z.id,z.access);if(Y&&Y.checkedAt>=X)continue;this.setFallback(z.id,{quota:z.quota,refreshAfter:X+Z,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return _$(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==f(Z))return!1}return _$(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,f(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let X=this.now()-this.lastApiCallAt;if(X<e.API_CALL_GAP_MS)await new Promise((Y)=>{let G=G9(Y,e.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},z=this.apiGate.then(Z,Z);return this.apiGate=z.catch(()=>{}),z}async _fetchMain($){let Z=f($);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let z=await C({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!z){let X=this.main;if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=this.now(),Y=await this._fetchQuota($),G=this.now();if(this.mainTokenFp=f($),this.main={quota:Y,refreshAfter:T4(Y,this.storage,G),checkedAt:G},kZ(Y))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(Y,G,this.mainTokenFp,X),Y}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback($,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff($,Z)){let X=this.getFallback($,Z);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let z=await C({name:e.quotaLockName($),ttlMs:30000,path:this.configPath});if(!z){let X=this.getFallback($,Z);if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=await this._fetchQuota(Z),Y=this.now();return this.setFallback($,{quota:X,refreshAfter:Y+w$(this.storage),checkedAt:Y},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError($,Z,z),z}finally{this.inflightFallbacks.delete(e.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(e.isAuthError($))return;this.mainLastApiError=E$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(e.isAuthError(z))return;let X=f(Z),Y=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,E$({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,X)}}function E4($){return Boolean($.primary||$.secondary)}function kZ($){let{primary:Z,secondary:z}=$;if(!Z&&!z)return!1;if(Z&&Z.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{createHash as Q9,randomUUID as U9}from"node:crypto";import{setTimeout as D9}from"node:timers/promises";import{readFile as x9}from"node:fs/promises";var j$=I("refresh"),O0=I("accounts"),V9=1e4,F9=15000,yZ=50;function v($){return $.type==="oauth"&&$.corrupt!==!0}function j9($){let Z=$?.trim();if(!Z)return!1;try{let z=new URL(Z);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}var N9="floors-v1";function j5($){return $.costZeroing?.enabled!==!1}class _0 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var q9=[401,403,429],A4={primary:0,secondary:0},M9=!1,wZ={primary:5,secondary:10};function j($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var O9=new Set(["__proto__","constructor","prototype"]);function _9($){return $.length>0&&!O9.has($)}function P9($){return $ instanceof _0||j($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function M0($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():U9(),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 C4($){if(!j($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let z=Number($.nextRetryAt),X=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function L9($){if(!j($))return;let Z={};for(let Y of["primary","secondary"]){let G=$[Y];if(!j(G))continue;let J=Number(G.usedPercent),B=Number(G.remainingPercent),H=Number(G.checkedAt);if(!Number.isFinite(J)||!Number.isFinite(B)||!Number.isFinite(H))continue;let Q=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[Y]={usedPercent:J,remainingPercent:B,checkedAt:H,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(Q)&&Q>0?{windowMinutes:Q}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[Y]==="number"?$[Y]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[Y]=G}let z=$.spendControl;if(j(z)){let Y=Number(z.limit),G=Number(z.used),J=Number(z.remaining),B=Number(z.usedPercent),H=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(G)&&Number.isFinite(J)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof z.reached==="boolean")Z.spendControl={limit:Y,used:G,remaining:J,usedPercent:B,remainingPercent:H,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=$.credits;if(j(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&(X.overageLimitReached===void 0||typeof X.overageLimitReached==="boolean")){let Y=Number(X.balance),G=typeof X.checkedAt==="number"?X.checkedAt:Number.NaN;Z.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,...typeof X.overageLimitReached==="boolean"?{overageLimitReached:X.overageLimitReached}:{},...Number.isFinite(Y)?{balance:Y}:{},...Number.isFinite(G)?{checkedAt:G}:{}}}return Object.keys(Z).length?Z:void 0}function R9($){if(!j($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!j9(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...M0($),type:"api",apiKey:z||void 0,baseURL:Z,authHeader:X}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...M0($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...M0($),type:"oauth",corrupt:!0}}return{...M0($),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:C4($.lastRefreshError),lastQuotaRefreshError:C4($.lastQuotaRefreshError),quota:L9($.quota)}}function S9($){if(!j($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!_9(z)||!j(X))continue;let Y={};if(j(X.inFlight))Y.inFlight={...X.inFlight};if(j(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))Y.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...j(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))Y.cooldownUntil=X.cooldownUntil;if(Object.keys(Y).length>0)Z[z]=Y}return Object.keys(Z).length>0?Z:void 0}var I4=new Set;function m4($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(I4.has(Z))return;I4.add(Z),O0.warn("account load-dropped, preserved on disk",{droppedIds:$})}function g4($){if(!j($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(R9).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let J of Z)if(j(J)&&typeof J.id==="string"&&J.id.trim())X.add(J.id.trim());let Y=new Set(z.map((J)=>J.id)),G=[];for(let J of X)if(!Y.has(J))G.push(J);m4(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:j($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:j($.refresh)?$.refresh:void 0,quota:j($.quota)?$.quota:void 0,reset:S9($.reset),dump:j($.dump)?$.dump:void 0,costZeroing:j($.costZeroing)?$.costZeroing:void 0,killswitch:j($.killswitch)?$.killswitch:void 0,logging:j($.logging)?$.logging:void 0,cachekeep:j($.cachekeep)?$.cachekeep:void 0,cacheKeep:j($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:z}}function v4($){if(!("claustrum"in $))return $;let{claustrum:Z,...z}=$;return z}async function $$($){try{return{exists:!0,value:JSON.parse(await x9($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function Z$($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function T9($){let Z;try{Z=(await $$($)).value}catch{return null}return pZ(Z)}function p4($,Z){if(!j($))return $;let z=j(Z)?Z:{},X=j(z.main)?z.main:void 0,Y=j(z.accounts)?z.accounts:{},G=j($.quota)?$.quota:{},J=j($.refresh)?$.refresh:{},B=X??G,H=X??J,K=J.mainRefreshLeaseId!==void 0?{id:J.mainRefreshLeaseId,until:J.mainRefreshLeaseUntil,tokenHash:J.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},U=Array.isArray($.accounts)?$.accounts.map((N)=>{if(!j(N))return N;let D=typeof N.id==="string"&&j(Y[N.id])?Y[N.id]:{};return{...N,...D}}):void 0;return l4({...$,refresh:Z$({...J,mainLastRefreshError:J.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:K.id,mainRefreshLeaseUntil:K.until,mainRefreshLeaseTokenHash:K.tokenHash}),quota:Z$({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:U})}async function E9($){let Z=await $$($.configPath);if(!Z.exists)return null;let z=await $$($.statePath);return g4(p4(Z.value,z.value))}function l4($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function A9($){return Z$({id:$.id,label:$.label,type:$.type,corrupt:$.type==="oauth"&&$.corrupt===!0?!0:void 0,enabled:$.enabled,addedAt:$.addedAt,accountId:$.accountId,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function d4($){if($.type==="api")return Z$({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return Z$({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function P0($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function m$($,Z,z){if(z in Z)$[z]=Z[z];else delete $[z]}function C9($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function I9($,Z){if(!C9($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var b9=300000;function b4($,Z){if($===void 0)return 0;return $>Z+b9?0:$}function f9($,Z,z){let X=Date.now(),Y=b4(Z.lastRefreshedAt,X),G=b4(z.lastRefreshedAt,X),J=Z.expires??0,B=z.expires??0,H=G>Y?z:Y>G?Z:B>J?z:J>B?Z:I9(Z,z);m$($,H,"access"),m$($,H,"refresh"),m$($,H,"expires"),m$($,H,"lastRefreshedAt"),m$($,H,"lastRefreshError")}function k9($,Z){if(!j($))return Z;let z=$,X=P0(z.quota),Y=P0(Z.quota),G=X>Y,J=G?{...z,...Z,quota:z.quota,lastQuotaRefreshError:z.lastQuotaRefreshError}:{...z,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete J.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete J.lastRefreshError;if(typeof z.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||z.lastUsed>Z.lastUsed))J.lastUsed=z.lastUsed;return f9(J,z,Z),J}function c4($){let Z=$.refresh?Z$({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?Z$({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return l4({version:1,main:$.main,routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:z,reset:$.reset,dump:$.dump,costZeroing:$.costZeroing,killswitch:$.killswitch,logging:$.logging,cachekeep:$.cachekeep,cacheKeep:$.cacheKeep,mainAccountId:$.mainAccountId,accounts:$.accounts.map(A9)})}async function p$($,Z=!1){let z=Date.now(),X=z+F9,Y=0;while(Date.now()<=X){Y++;let B=await C({name:"save",ttlMs:V9,path:$,renew:Z});if(B)return B;let H=X-Date.now();if(H<=0)break;await D9(Math.min(yZ+a4(yZ),H))}let G=Date.now()-z,J=Math.round(G/Math.max(1,Y));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${Y} attempts, ~${J}ms apart; retry interval is ${yZ}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 u4($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,d4(z)]));return{version:1,main:Z$({quota:$.quota?.mainQuota,quotaCheckedAt:$.quota?.mainQuotaCheckedAt,quotaToken:$.quota?.mainQuotaToken,lastQuotaApiError:$.quota?.mainLastQuotaApiError,lastRefreshError:$.refresh?.mainLastRefreshError,refreshLeaseId:$.refresh?.mainRefreshLeaseId,refreshLeaseUntil:$.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:$.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}function pZ($){if(!j($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!j(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function y9($,Z,z,X){if(!j($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],G=[];for(let J of Z){if(z.has(J))continue;if(X.has(J))continue;let B=$.accounts.find((H)=>j(H)&&typeof H.id==="string"&&H.id.trim()===J);if(!B)continue;Y.push(B),G.push(J)}return{preservedRawEntries:Y,preservedIds:G}}function h9($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!j(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function w9($,Z,z){let X=pZ($);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:G}=y9($,X,Z,z);return m4(G),Y}async function q5($,Z,z={}){let{configPath:X,statePath:Y}=Z,G=await p$(X);try{let J=await p$(Y);try{let B=await $$(X),H=await $$(Y),Q=(B.exists?g4(p4(B.value,H.value)):null)??m9(),K=new Set(Q.accounts.map((V)=>V.id)),W=pZ(B.value)??new Set,U=$(Q,{rawRosterIds:[...W],loadedRosterIds:[...K]})??Q,N=new Set(z.allowDrop??[]),D=w9(B.value,K,N),M=c4(U),q=new Set((Array.isArray(M.accounts)?M.accounts:[]).map((V)=>j(V)&&typeof V.id==="string"?V.id.trim():"").filter(Boolean)),L=D.filter((V)=>{if(!j(V))return!1;if(typeof V.id!=="string")return!1;return!q.has(V.id.trim())}),T=j(B.value)?B.value:{},p={...v4(T),...M,accounts:[...Array.isArray(M.accounts)?M.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return Q;if(await m(X,p),z.canWrite&&!z.canWrite())return Q;return await m(Y,u4(U)),O0.debug("account config written",{accountCount:p.accounts.length,accountIds:h9(p.accounts)}),U}finally{await J.release()}}finally{await G.release()}}function m9(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function g9($,Z){$.main=$.main??{};let z=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:P0($.main.quota),X=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:P0(Z.quota?.mainQuota);if(z>X)return;$.main.quota=Z.quota?.mainQuota,$.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,$.main.quotaToken=Z.quota?.mainQuotaToken,$.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function v9($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function mZ($){if(Array.isArray($))return $.map(mZ);if(!j($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,z])=>[Z,mZ(z)]))}async function p9($,Z,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=Z.statePath,G=await p$(Y);try{let J=(await $$(Y)).value,B=j(J)?{...J,version:1}:{version:1};if(z.mainQuota)g9(B,$);if(z.mainRefresh)v9(B,$);if(z.accounts){let H=z.accounts===!0?null:new Set(z.accounts),Q=await T9(Z.configPath);B.accounts={...j(B.accounts)?B.accounts:{}};for(let K of $.accounts){if(H&&!H.has(K.id))continue;if(Q&&!Q.has(K.id))continue;B.accounts[K.id]=k9(B.accounts[K.id],d4(K))}if(H){for(let K of H)if(!$.accounts.some((W)=>W.id===K))delete B.accounts[K]}if(Q){for(let K of Object.keys(B.accounts))if(!Q.has(K))delete B.accounts[K]}}if(X&&!X())return;await m(Y,mZ(B))}finally{await G.release()}}function l9($){return $?.fallbackOn?.length?$.fallbackOn:q9}function M5($,Z){return l9(Z).includes($)}function d9($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??A4.primary,secondary:Z.secondary??Z["1w"]??A4.secondary}}function gZ($){return $?.quota?.enabled!==!1}function l$($){return $?.quota?.failClosedOnUnknownQuota??M9}function i4($,Z,z=Date.now()){if(!gZ(Z))return!0;if(!$)return!l$(Z);let X=d9(Z),Y=l$(Z);for(let G of["primary","secondary"]){let J=$[G];if(!J)continue;if(q0(J,z)){if(Y)return!1;continue}if(J.remainingPercent<X[G])return!1}return!0}function L0($){return $?.killswitch?.enabled===!0}function f4($){return{primary:$?.primary??$?.["5h"]??wZ.primary,secondary:$?.secondary??$?.["1w"]??wZ.secondary}}function O5($){return $?.cacheKeep??$?.cachekeep}function k4($){return typeof $==="number"&&Number.isFinite($)?$:0}function s4($,Z){if(!$?.killswitch)return wZ;if($.killswitch.schema===N9){let{accounts:z,defaults:X}=$.killswitch,Y=Z??"main",G=j(z)&&Object.hasOwn(z,Y)&&j(z[Y])?z[Y]:j(X)?X:void 0;return{primary:k4(G?.primary),secondary:k4(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return f4($.killswitch.accounts[Z]);return f4($.killswitch.main)}function n4($,Z,z,X=Date.now()){if(!L0(Z))return!0;if(!$)return!l$(Z);let Y=s4(Z,z),G=l$(Z);for(let J of["primary","secondary"]){let B=$[J];if(!B)continue;if(q0(B,X)){if(G)return!1;continue}if(B.remainingPercent<Y[J])return!1}return!0}function _5($,Z,z,X){if(!L0(X))return 300;let Y=[],G=[{accountId:void 0,quota:$},...Z];for(let{accountId:B,quota:H}of G){if(!H)continue;let Q=s4(X,B),K=[],W=!1;for(let U of["primary","secondary"]){let N=H[U];if(!N||q0(N,z))continue;if(N.remainingPercent>=Q[U])continue;let D=N.resetsAt?Date.parse(N.resetsAt):NaN;if(!Number.isFinite(D)||D<=z){W=!0;break}K.push(D)}if(W||K.length===0)continue;Y.push(Math.max(...K))}if(Y.length===0)return 300;let J=Math.min(...Y);return Math.max(1,Math.ceil((J-z)/1000))}function y4($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function P5($,Z){let{configPath:z,statePath:X}=Z;if(!$)return;try{let G=await $$(z);if(G.exists&&j(G.value)&&y4(G.value))return}catch{}let Y=await p$(z);try{let G=await p$(X);try{let J=await $$(z);if(J.exists&&j(J.value)){if(y4(J.value))return}if(!$)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let K=e$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(K)B.mainAccountId=K}let H=J.exists&&j(J.value)?J.value:{},Q={...v4(H),...c4(B)};await m(z,Q),await m(X,u4(B))}finally{await G.release()}}finally{await Y.release()}}function c9($){return $?.refresh?.enabled!==!1}function u9($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function a4($){return Math.floor(Math.random()*($+1))}function N$($,Z,z){return!$.access||!$.expires||$.expires-z<=u9(Z)}function i9($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function g$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class o4 extends Error{constructor($){super(`Refusing to refresh account ${$}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}var s9="common-auth-placeholder:v1:openai",r4="main";function L5($){return j($)&&$.type==="oauth"&&($.refresh===s9||$.refresh===R4)}function R5($){return $?.accounts.find((Z)=>Z.id===r4&&Z.enabled!==!1&&v(Z))}function S5($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==r4)}}function x($,Z){let z=$.accounts.findIndex((X)=>X.id===Z.id);if(z!==-1)$.accounts[z]=Z}function v$($){return $ instanceof Error?$.message:String($)}function vZ($,Z,z){if(Z instanceof h$)return;$.lastRefreshError=V3({error:Z,now:z,refreshToken:$.refresh,previous:$.lastRefreshError})}function hZ($,Z,z){if(Z instanceof h$)return;if($.lastQuotaRefreshError=E$({error:Z,now:z,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)vZ($,Z,z)}function h4($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return Number.isFinite(z)?z>Z:!0}function n9($,Z){if(!$)return!1;return h4($.primary,Z)||h4($.secondary,Z)}function a9($,Z,z){if(!$)return!1;let X=Z?.quota?.checkIntervalMinutes??5,Y=Math.max(1,X)*60000,G=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return z-G<Y}function w4($,Z,z){return!a9($.quota,Z,z)}function o9($,Z,z,X){return o0(z)&&i4($.quota,Z,X)&&n9($.quota,X)}function r9($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var t9=60000,e9=60000,$1=600000;function Z1($){return`fallback-oauth-refresh-${Q9("sha256").update($).digest("base64url").slice(0,16)}`}var z1=1e4,X1=100;class Y1{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($)N0($.refresh)}seedFallbackQuota($,Z){if(!this.quotaManager)return;if(!$.quota)return;let z=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(z<=0)return;let X=this.quotaManager.getFallback($.id,$.access);if(X&&X.checkedAt>=z)return;this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:z+r9(Z),checkedAt:z},$.access,!1,$.accountId)}async load(){return E9(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await p9($,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(()=>{})},t9+a4(e9)),"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 z=[],X=!1;for(let Y of Z.accounts){if(Y.enabled===!1||!v(Y))continue;if(g$(Z,Y))continue;if(F$(Y))continue;let G=!1,J=Y;try{if(N$(J,Z,this.now())){let B=J.lastRefreshError;if(B&&J$(B,J.refresh,this.now()))throw G=!0,Error(r$(B,this.now()));try{J=await this.refreshAccount(J,Z),X=!0}catch(H){if(P9(H))continue;G=!0;let Q=Z.accounts.find((K)=>K.id===Y.id&&v(K));if(Q&&!J$(Q.lastRefreshError,Q.refresh,this.now()))vZ(Q,H,this.now()),x(Z,Q),X=!0;throw H}}if(this.seedFallbackQuota(J,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),Z))z.push(J)}catch(B){let H=i9(J,this.now());if(G){if(!H)continue}else if(!H)continue;if(o9(J,Z,B,this.now()))j$.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:J.id,error:v$(B)}),z.push(J);else if(!l$(Z))z.push(J)}}if(X){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((G)=>{O0.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:v$(G)})})}return z}async markUsed($){try{let Z=await this.load();if(!Z)return;let z=Z.accounts.find((X)=>X.id===$.id);if(!z)return;z.lastUsed=this.now(),await this.save(Z,[z.id])}catch(Z){O0.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:v$(Z)})}}accountPassesQuotaPolicy($,Z){return i4($.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(!$||!c9($))return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!v(z))continue;if(g$($,z))continue;if(F$(z))continue;if(!N$(z,$,this.now()))continue;if(J$(z.lastRefreshError,z.refresh,this.now()))continue;try{j$.debug("fallback oauth background due",{pid:process.pid,accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),await this.refreshAccount(z,$),Z=!0}catch(X){j$.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:v$(X)}),vZ(z,X,this.now()),x($,z),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!gZ($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!v(z))continue;if(g$($,z))continue;if(F$(z))continue;let X=z;try{if(N$(X,$,this.now())){if(J$(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,$),Z=!0}if(_$(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,$),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):w4(X,$,this.now())))continue;await this.refreshAccountQuota(X,$),Z=!0}catch(Y){hZ(z,Y,this.now()),x($,z),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),z=[];if(!Z||!gZ(Z))return{storage:Z,errors:z};if(!this.options.fetchQuotaFn)return{storage:Z,errors:z};let X=$.force??!1,Y=!1;for(let G of Z.accounts){if(G.enabled===!1||!v(G))continue;if(g$(Z,G))continue;if(F$(G))continue;let J=G;try{if(N$(J,Z,this.now())){let B=J.lastRefreshError;if(B&&J$(B,J.refresh,this.now()))throw Error(r$(B,this.now()));J=await this.refreshAccount(J,Z),Y=!0}if(!X&&!w4(J,Z,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,x(Z,J),Y=!0;continue}await this.refreshAccountQuota(J,Z),Y=!0}catch(B){hZ(G,B,this.now()),x(Z,G),Y=!0,z.push({accountId:G.id,message:v$(B)})}}if(Y)await this.save(Z);return{storage:Z,errors:z}}async refreshAccount($,Z,z={}){let X=this.refreshPromises.get($.id);if(X){let J=await X;return x(Z,J),J}let Y=this.refreshAccountNow($,Z,z).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let G=await Y;return x(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,z,X){let Y=Date.now()+z1;while(Date.now()<Y){await new Promise((Q)=>setTimeout(Q,X1));let G=await this.load(),J=G?.accounts.find((Q)=>Q.id===$.id&&v(Q));if(!J)continue;if(this.assertNotTombstoned(J),(J.access!==z.access||J.refresh!==z.refresh||(J.expires??0)>(z.expires??0)+60000)&&(X.force||!N$(J,G,this.now())))return x(Z,J),j$.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let H=J.lastRefreshError;if(H&&J$(H,J.refresh,this.now()))throw x(Z,J),Error(r$(H,this.now()))}return null}assertNotShieldedMainRow($,Z,z){if(z.asPoolMain||!Z)return;if(g$($,Z))throw new o4(Z.id)}async refreshAccountNow($,Z,z){let X=await this.load(),Y=X?.accounts.find((B)=>B.id===$.id&&v(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!N$(Y,X,this.now()))return x(Z,Y),Y;let G=Y??$,J=await C({name:Z1(G.id),ttlMs:$1,path:this.paths.configPath,renew:!0});if(!J){j$.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let B=await this.waitForConcurrentFallbackRefresh($,Z,G,z);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),Y=X?.accounts.find((K)=>K.id===$.id&&v(K)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!N$(Y,X,this.now()))return x(Z,Y),Y;if(!Y)throw new _0($.id);G=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});j$.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:z.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let H=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=H.access,G.refresh=H.refresh,G.expires=H.expires,G.lastRefreshedAt=H.expires-H.expiresIn*1000,G.lastRefreshError=void 0,x(Z,G),await this.save(Z),!(await this.load())?.accounts.some((K)=>K.id===$.id))throw new _0($.id);return j$.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await J.release()}}async refreshAccountQuota($,Z){let z=$;if(this.assertNotTombstoned(z),!z.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 X=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),Y=(G)=>this.quotaManager?this.quotaManager.refreshFallback(z.id,G):X({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!z.access)throw Error(`Fallback account ${$.id} has no access token`);let G=await Y(z.access);z.quota=G,z.lastQuotaRefreshError=void 0,x(Z,z),await this.save(Z)}catch(G){throw hZ($,G,this.now()),x(Z,$),G}}}var t4=["primary","secondary"];function R0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function R$($){return typeof $==="number"&&Number.isFinite($)}function G1($,Z){if(!R0(Z))return;let z=Z.usedPercent;if(!R$(z)||z<0||z>100)return;return{label:$,usedPercent:z,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...R$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function J1($){let Z=$.spendControl;if(R0(Z)&&typeof Z.reached==="boolean"){let z=(X)=>R$(Z[X])?{[X]:Z[X]}:{};return{kind:"reading",reached:Z.reached,...z("remainingPercent"),...z("usedPercent"),...z("limit"),...z("used"),...z("remaining"),...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...typeof Z.unit==="string"?{unit:Z.unit}:{}}}if($.spendControlCleared===!0)return{kind:"cleared"};return}function B1($,Z){if(!R0($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...R$($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function E5($,Z,z){if(!R0($)||!R$(Z))return;let X=[],Y=[];for(let Q of t4){let K=G1(Q,$[Q]);if(K)X.push(K);else if(z)Y.push({label:Q})}let G=J1($),J=$.resetCreditsAvailable,B=typeof J==="number"&&Number.isSafeInteger(J)&&J>=0?{resetCredits:{value:J,checkedAt:Z}}:void 0,H=B1($.credits,Z);if(X.length===0&&Y.length===0&&!G&&!B&&!H)return;return{checkedAt:Z,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...G?{budget:G}:{},...B?{counters:B}:{},...H?{credits:H}:{}}}function e4($){if(!X$($))return;let Z=A($),z={};for(let X of t4){let Y=Z.limits.find((J)=>J.label===X&&J.kind==="reading");if(!Y||!R$(Y.usedPercent))continue;let G={usedPercent:Y.usedPercent,remainingPercent:100-Y.usedPercent,checkedAt:Y.checkedAt,...Y.resetsAt!==void 0?{resetsAt:Y.resetsAt}:{},...Y.windowMinutes!==void 0?{windowMinutes:Y.windowMinutes}:{}};z[X]=G}return z.primary||z.secondary?z:void 0}var Z6="main";function k5($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function y5($,Z,z){let X=new Map;if(L0(Z))for(let Y of $)X.set(Y.id,n4(e4(Y.quota),Z,Y.id===Z6?void 0:Y.id,z));return X}var h5=5,H1=5000;function w5($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function m5($,Z=H1){let z=$.rows.filter((J)=>J.kind==="oauth"&&$.killswitch.get(J.id)!==!1&&A(J.quota).limits.length===0);if(z.length===0)return;if(y({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((J)=>$.killswitch.get(J.id)!==!1))return;let Y=[];if(y({rows:z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(J)=>{let B=$.requestPull(J);if(B)Y.push(B.catch(()=>{}))}}),Y.length===0)return;let G;return Promise.race([Promise.all(Y),new Promise((J)=>{G=setTimeout(J,Z)})]).then(()=>{}).finally(()=>clearTimeout(G))}function S0($){return $.reason==="exhausted"||$.reason==="budget-spent"}function K1($,Z){if(!w($))return!1;let z=$;if(!(Z-z.checkedAt<=T$))return!1;if(z.overageLimitReached===!0)return!1;if(z.unlimited)return!0;return z.hasCredits&&(z.balance===void 0||z.balance>0)}function x0($,Z,z){let X=(B)=>Z.killswitch.get(B)!==!1,Y=new Set(z.admitted.filter((B)=>B.lastPath!==!0&&X(B.id)).map((B)=>B.id)),G=new Map(z.refused.map((B)=>[B.id,B])),J=$.filter((B)=>{if(B.kind!=="oauth"||!X(B.id))return!1;if(G.get(B.id)?.reason!=="exhausted")return!1;let H=A(B.quota);if(G$(H,Z.now))return!1;return K1(H.credits,Z.now)}).map((B)=>B.id);return{free:Y,credits:J}}function W1($,Z=$.rows){return y({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class Q1{#$=new Set;served($,Z,z){let X=W1($),Y=x0($.rows,$,X),G=new Set(Y.credits);if(Y.free.has(Z)){this.#$.clear();return}for(let J of[...this.#$])if(!G.has(J))this.#$.delete(J);if(!G.has(Z)||this.#$.has(Z))return;this.#$.add(Z),z?.info("serving requests on prepaid credits",{accountId:Z,reason:"free quota used up"})}has($){return this.#$.has($)}ids(){return new Set(this.#$)}}function z6($,Z,z){if($===void 0)return{reason:"no-credential"};if(z.get($)===!1)return{reason:"killswitch"};let X=Z.excluded.find((G)=>G.id===$);if(X?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:X.until};if(X)return{reason:"no-credential"};let Y=Z.refused.find((G)=>G.id===$);if(Y&&"resetAtMs"in Y)return{reason:"quota-exhausted",resetAtMs:Y.resetAtMs};if(Y)return{reason:"quota-unknown"};return{reason:"no-credential"}}function $6($,Z,z){if(Z.refused.find((Y)=>!S0(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return z6($[0],Z,z)}function g5($){let Z=$.replayable!==!1,z=$.mainId===void 0?Z6:$.mainId??"",X=Z?$.placement:"main-first",Y=v0({rows:$.rows,placement:X,formerMainId:z,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),G=a$($.rows.map((W)=>W.id),X,z),J=new Set(Y.admission.refused.filter((W)=>S0(W)&&$.killswitch.get(W.id)!==!1).map((W)=>W.id)),B=G.filter((W)=>J.has(W)),H=x0($.rows,$,Y.admission),Q=Y.order.filter((W)=>H.free.has(W)),K=G.filter((W)=>H.credits.includes(W));if(!Z){let W=G.includes(z),U=W?z:Q[0]??K[0]??Y.order[0]??B[0];if(U!==void 0&&Y.order.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&K.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&J.has(U))return{kind:"send",order:[U],lastPath:!0};return{kind:"block",block:W?z6(z,Y.admission,$.killswitch):$6(G,Y.admission,$.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(K.length>0){let W=Y.order.length>0?Y.order:B;return{kind:"send",order:[...K,...W.filter((U)=>!K.includes(U))],lastPath:!1}}if(Y.order.length>0)return{kind:"send",order:Y.order,lastPath:!1};if(B.length>0)return{kind:"send",order:B,lastPath:!0};return{kind:"block",block:$6(G,Y.admission,$.killswitch)}}function v5($){let Z=y({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),z=new Map;for(let X of $.rows)z.set(X.id,A(X.quota));for(let X of Z.admitted)if(X.projection)z.set(X.id,X.projection);return{projections:z,excluded:new Set(Z.excluded.map((X)=>X.id))}}function X6($,Z,z){let X=z.exclude,Y=X?$.rows.filter((J)=>!X.has(J.id)):$.rows,G=new Map;for(let J of Y){let B=Z.resetCredits(J.id);if(B!==void 0)G.set(J.id,B)}return u0({rows:Y,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...z.pendingBytes?{pendingBytes:z.pendingBytes}:{},rowReservePercent:(J)=>Z.reservePercent(J.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...z.pin===void 0?{}:{pin:{accountId:z.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function p5($,Z,z,X){let Y=X6($,Z,{exclude:z,pendingBytes:X}),G=$.rows.filter((K)=>!z.has(K.id)),J=x0(G,$,Y.admission),B=Y.outcome==="dispatch"&&Y.source!=="pin"?{accountId:Y.accountId,source:Y.source,...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}:void 0;if(B&&J.free.has(B.accountId))return B;let H=J.credits[0];if(H===void 0)return B;let Q=A(G.find((K)=>K.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function l5($,Z,z){let X=$.killswitch.get(z)===!1,Y={kind:"move",reason:X?"killswitch":"exhausted"},G=X6($,Z,{pin:z}),J=x0($.rows,$,G.admission),B=J.credits.includes(z),H=J.credits.some((W)=>W!==z);if(G.outcome==="dispatch"){let W=!J.free.has(G.accountId);if(G.pin.action==="assign"){if(W&&B)return{kind:"serve"};return Y}if(G.accountId!==z)return{kind:"detour"};if(W&&H)return Y;return{kind:"serve"}}let Q=G.admission.refused.find((W)=>W.id===z),K=X||Q!==void 0&&S0(Q);if(B)return{kind:"serve"};if(H)return K?Y:{kind:"detour"};if(!X&&Q&&S0(Q))return{kind:"last-path"};return{kind:"none"}}function d5($,Z,z,X){let Y=$.killswitch.get(z);return c0({quota:Z.projections.get(z),now:$.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as Y6}from"node:os";import{join as G6}from"node:path";var U1=["error","warn","info","debug","trace"];function D1(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?G6(Y6(),"opencode-openai-auth","opencode-openai-auth.log"):G6(Y6(),"opencode-openai-auth.log"))}function V1(){let $=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return $&&U1.includes($)?$:void 0}J6({file:D1,level:V1});if(process.once("beforeExit",async()=>{try{await T0()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>T0());
|
|
90
|
+
export{X$ as yc,x$ as zc,b6 as Ac,$3 as Bc,F6 as Cc,X3 as Dc,O6 as Ec,_6 as Fc,A as Gc,B3 as Hc,k6 as Ic,a$ as Jc,y6 as Kc,p0 as Lc,h6 as Mc,g6 as Nc,u6 as Oc,D3 as Pc,V3 as Qc,J$ as Rc,r$ as Sc,M3 as Tc,_3 as Uc,o6 as Vc,j3 as Wc,N3 as Xc,e$ as Yc,t6 as Zc,W$ as _c,z8 as $c,X8 as ad,Y8 as bd,G8 as cd,B2 as dd,K2 as ed,W2 as fd,Q2 as gd,F as hd,GZ as id,s3 as jd,E8 as kd,A8 as ld,C8 as md,DZ as nd,f8 as od,z4 as pd,k8 as qd,b as rd,L4 as sd,S7 as td,F$ as ud,h$ as vd,s7 as wd,n7 as xd,Z5 as yd,f as zd,e as Ad,v as Bd,N9 as Cd,j5 as Dd,wZ as Ed,_9 as Fd,T9 as Gd,E9 as Hd,q5 as Id,p9 as Jd,l9 as Kd,M5 as Ld,i4 as Md,L0 as Nd,O5 as Od,s4 as Pd,n4 as Qd,_5 as Rd,P5 as Sd,u9 as Td,g$ as Ud,r4 as Vd,L5 as Wd,R5 as Xd,S5 as Yd,$1 as Zd,Z1 as _d,Y1 as $d,E5 as ae,e4 as be,Z6 as ce,k5 as de,y5 as ee,h5 as fe,w5 as ge,m5 as he,K1 as ie,Q1 as je,g5 as ke,v5 as le,p5 as me,l5 as ne,d5 as oe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{jf as Z,lf as W}from"./index-ya9c5e4m.js";var R=Z(($G,E)=>{var{defineProperty:N,getOwnPropertyDescriptor:Kz,getOwnPropertyNames:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,G)=>{for(var H in G)N(z,H,{get:G[H],enumerable:!0})},Yz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Qz(G))if(!Wz.call(z,K)&&K!==H)N(z,K,{get:()=>G[K],enumerable:!(Q=Kz(G,K))||Q.enumerable})}return z},Zz=(z)=>Yz(N({},"__esModule",{value:!0}),z),O={};Xz(O,{VercelOidcTokenError:()=>S});E.exports=Zz(O);class S extends Error{constructor(z,G){super(z);this.name="VercelOidcTokenError",this.cause=G}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var P=Z((qG,y)=>{var{create:$z,defineProperty:L,getOwnPropertyDescriptor:qz,getOwnPropertyNames:vz,getPrototypeOf:Bz}=Object,Fz=Object.prototype.hasOwnProperty,Uz=(z,G)=>{for(var H in G)L(z,H,{get:G[H],enumerable:!0})},C=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of vz(G))if(!Fz.call(z,K)&&K!==H)L(z,K,{get:()=>G[K],enumerable:!(Q=qz(G,K))||Q.enumerable})}return z},I=(z,G,H)=>(H=z!=null?$z(Bz(z)):{},C(G||!z||!z.__esModule?L(H,"default",{value:z,enumerable:!0}):H,z)),Lz=(z)=>C(L({},"__esModule",{value:!0}),z),x={};Uz(x,{findRootDir:()=>Jz,getUserDataDir:()=>Nz});y.exports=Lz(x);var B=I(W("path")),bz=I(W("fs")),A=I(W("os")),Vz=R();function Jz(){try{let z=process.cwd();while(z!==B.default.dirname(z)){let G=B.default.join(z,".vercel");if(bz.default.existsSync(G))return z;z=B.default.dirname(z)}}catch(z){throw new Vz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Nz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return B.default.join(A.default.homedir(),"Library/Application Support");case"linux":return B.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var i=Z((vG,c)=>{var{create:Rz,defineProperty:b,getOwnPropertyDescriptor:Az,getOwnPropertyNames:Iz,getPrototypeOf:Dz}=Object,wz=Object.prototype.hasOwnProperty,Tz=(z,G)=>{for(var H in G)b(z,H,{get:G[H],enumerable:!0})},u=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Iz(G))if(!wz.call(z,K)&&K!==H)b(z,K,{get:()=>G[K],enumerable:!(Q=Az(G,K))||Q.enumerable})}return z},l=(z,G,H)=>(H=z!=null?Rz(Dz(z)):{},u(G||!z||!z.__esModule?b(H,"default",{value:z,enumerable:!0}):H,z)),jz=(z)=>u(b({},"__esModule",{value:!0}),z),g={};Tz(g,{isValidAccessToken:()=>Ez,readAuthConfig:()=>Oz,writeAuthConfig:()=>Sz});c.exports=jz(g);var F=l(W("fs")),h=l(W("path")),Mz=f();function k(){let z=(0,Mz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(z,"auth.json")}function Oz(){try{let z=k();if(!F.existsSync(z))return null;let G=F.readFileSync(z,"utf8");if(!G)return null;return JSON.parse(G)}catch(z){return null}}function Sz(z){let G=k(),H=h.dirname(G);if(!F.existsSync(H))F.mkdirSync(H,{mode:504,recursive:!0});F.writeFileSync(G,JSON.stringify(z,null,2),{mode:384})}function Ez(z,G=0){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let H=Math.floor(Date.now()/1000),Q=G/1000;return z.expiresAt>=H+Q}});var a=Z((BG,s)=>{var{defineProperty:T,getOwnPropertyDescriptor:Cz,getOwnPropertyNames:xz}=Object,yz=Object.prototype.hasOwnProperty,Pz=(z,G)=>{for(var H in G)T(z,H,{get:G[H],enumerable:!0})},uz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of xz(G))if(!yz.call(z,K)&&K!==H)T(z,K,{get:()=>G[K],enumerable:!(Q=Cz(G,K))||Q.enumerable})}return z},lz=(z)=>uz(T({},"__esModule",{value:!0}),z),d={};Pz(d,{processTokenResponse:()=>iz,refreshTokenRequest:()=>cz});s.exports=lz(d);var D=W("os"),gz="https://vercel.com",hz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",p=`@vercel/oidc node-${process.version} ${(0,D.platform)()} (${(0,D.arch)()}) ${(0,D.hostname)()}`,w=null;async function kz(){if(w)return w;let z=`${gz}/.well-known/openid-configuration`,G=await fetch(z,{headers:{"user-agent":p}});if(!G.ok)throw Error("Failed to discover OAuth endpoints");let H=await G.json();if(!H||typeof H.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let Q=H.token_endpoint;return w=Q,Q}async function cz(z){let G=await kz();return await fetch(G,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":p},body:new URLSearchParams({client_id:hz,grant_type:"refresh_token",...z})})}async function iz(z){let G=await z.json();if(!z.ok){let H=typeof G==="object"&&G&&"error"in G?String(G.error):"Token refresh failed";return[Error(H)]}if(typeof G!=="object"||G===null)return[Error("Invalid token response")];if(typeof G.access_token!=="string")return[Error("Missing access_token in response")];if(G.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof G.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,G]}});var t=Z((FG,r)=>{var{defineProperty:j,getOwnPropertyDescriptor:fz,getOwnPropertyNames:dz}=Object,pz=Object.prototype.hasOwnProperty,sz=(z,G)=>{for(var H in G)j(z,H,{get:G[H],enumerable:!0})},az=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of dz(G))if(!pz.call(z,K)&&K!==H)j(z,K,{get:()=>G[K],enumerable:!(Q=fz(G,K))||Q.enumerable})}return z},_z=(z)=>az(j({},"__esModule",{value:!0}),z),_={};sz(_,{AccessTokenMissingError:()=>m,RefreshAccessTokenFailedError:()=>n});r.exports=_z(_);class m extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login).");this.name="AccessTokenMissingError"}}class n extends Error{constructor(z){super("Failed to refresh authentication token.",{cause:z});this.name="RefreshAccessTokenFailedError"}}});var f=Z((UG,Hz)=>{var{create:mz,defineProperty:V,getOwnPropertyDescriptor:nz,getOwnPropertyNames:rz,getPrototypeOf:tz}=Object,ez=Object.prototype.hasOwnProperty,oz=(z,G)=>{for(var H in G)V(z,H,{get:G[H],enumerable:!0})},o=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of rz(G))if(!ez.call(z,K)&&K!==H)V(z,K,{get:()=>G[K],enumerable:!(Q=nz(G,K))||Q.enumerable})}return z},zz=(z,G,H)=>(H=z!=null?mz(tz(z)):{},o(G||!z||!z.__esModule?V(H,"default",{value:z,enumerable:!0}):H,z)),zG=(z)=>o(V({},"__esModule",{value:!0}),z),Gz={};oz(Gz,{assertVercelOidcTokenResponse:()=>M,findProjectInfo:()=>QG,getTokenPayload:()=>YG,getVercelDataDir:()=>GG,getVercelOidcToken:()=>KG,getVercelToken:()=>HG,isExpired:()=>ZG,loadToken:()=>XG,saveToken:()=>WG});Hz.exports=zG(Gz);var U=zz(W("path")),X=zz(W("fs")),v=R(),J=P(),$=i(),e=a(),q=t();function GG(){let G=(0,J.getUserDataDir)();if(!G)return null;return U.join(G,"com.vercel.cli")}async function HG(z){let G=(0,$.readAuthConfig)();if(!G?.token)throw new q.AccessTokenMissingError;if((0,$.isValidAccessToken)(G,z?.expirationBufferMs))return G.token;if(!G.refreshToken)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError("No refresh token available");try{let H=await(0,e.refreshTokenRequest)({refresh_token:G.refreshToken}),[Q,K]=await(0,e.processTokenResponse)(H);if(Q||!K)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError(Q);let Y={token:K.access_token,expiresAt:Math.floor(Date.now()/1000)+K.expires_in};if(K.refresh_token)Y.refreshToken=K.refresh_token;return(0,$.writeAuthConfig)(Y),Y.token}catch(H){if((0,$.writeAuthConfig)({}),H instanceof q.AccessTokenMissingError||H instanceof q.RefreshAccessTokenFailedError)throw H;throw new q.RefreshAccessTokenFailedError(H)}}async function KG(z,G,H){let Q=`https://api.vercel.com/v1/projects/${G}/token?source=vercel-oidc-refresh${H?`&teamId=${H}`:""}`,K=await fetch(Q,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!K.ok)throw new v.VercelOidcTokenError(`Failed to refresh OIDC token: ${K.statusText}`);let Y=await K.json();return M(Y),Y}function M(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function QG(){let z=(0,J.findRootDir)();if(!z)throw new v.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let G=U.join(z,".vercel","project.json");if(!X.existsSync(G))throw new v.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let H=JSON.parse(X.readFileSync(G,"utf8"));if(typeof H.projectId!=="string"&&typeof H.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:H.projectId,teamId:H.orgId}}function WG(z,G){let H=(0,J.getUserDataDir)();if(!H)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Q=U.join(H,"com.vercel.token",`${G}.json`),K=JSON.stringify(z);X.mkdirSync(U.dirname(Q),{mode:504,recursive:!0}),X.writeFileSync(Q,K),X.chmodSync(Q,432);return}function XG(z){let G=(0,J.getUserDataDir)();if(!G)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=U.join(G,"com.vercel.token",`${z}.json`);if(!X.existsSync(H))return null;let Q=JSON.parse(X.readFileSync(H,"utf8"));return M(Q),Q}function YG(z){let G=z.split(".");if(G.length!==3)throw new v.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let H=G[1].replace(/-/g,"+").replace(/_/g,"/"),Q=H.padEnd(H.length+(4-H.length%4)%4,"=");return JSON.parse(Buffer.from(Q,"base64").toString("utf8"))}function ZG(z,G=0){return z.exp*1000<Date.now()+G}});
|
|
2
2
|
export{R as a,f as b};
|