@cortexkit/opencode-openai-auth 1.10.0 → 1.11.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 +8 -8
- package/dist/{codex-request-BLzSBegI.d.ts → codex-request-DFeGDzpN.d.ts} +2 -2
- package/dist/index-0kpq9310.js +76 -0
- package/dist/{index-361xxyg2.js → index-2p3st53v.js} +2 -2
- package/dist/{index-dcyhv7eh.js → index-3x7q1rj8.js} +2 -2
- package/dist/{index-mkda7acs.js → index-4daebegf.js} +1 -1
- package/dist/{index-w37815v4.js → index-4rzatybc.js} +1 -1
- package/dist/{index-mf3dqvbn.js → index-7at0fc03.js} +2 -2
- package/dist/{index-fd3f8vw2.js → index-afpxnan1.js} +2 -2
- package/dist/{index-29ztc0ay.js → index-bxxjwt4q.js} +2 -2
- package/dist/index-cy6km6cz.js +64 -0
- package/dist/{index-17rh67pr.js → index-d5v2rn54.js} +1 -1
- package/dist/{index-95z5dpe1.js → index-dp68014q.js} +2 -2
- package/dist/index-h2z9jb3g.js +91 -0
- package/dist/{index-dkhy2peg.js → index-smzgsx6x.js} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-e49kkftr.js +1 -0
- package/dist/{token-pd3t5f20.js → token-wgntcjq1.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +4 -4
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +26 -15
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +14 -5
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +5 -2
- package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +2 -0
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +7 -0
- package/src/tui-compiled/raw/shared/c97089ed4243981c-host.js +113 -0
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +2 -1
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +26 -15
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +14 -5
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +5 -2
- package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +2 -0
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +7 -0
- package/src/tui-compiled/runtime/shared/c97089ed4243981c-host.js +113 -0
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +2 -1
- package/dist/index-3p1tc2e2.js +0 -91
- package/dist/index-3r9thx6n.js +0 -76
- package/dist/index-ya96m6wr.js +0 -64
- package/dist/token-util-807rzwws.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{bc as X,dc as V}from"./index-0kpq9310.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
|
|
2
2
|
`,{mode:W??384}),await $(B,W??384),await L(B,b)}catch(Y){throw await T(B,{force:!0}).catch(()=>{}),Y}return z.set(q,R(j.body)),!0},async all(){let j=await Q(b);if(!j||Object.keys(j).length===0)return{[x]:!0};return j}}}
|
|
3
3
|
export{_ as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{B as
|
|
1
|
+
import{lg as y}from"./index-4daebegf.js";import{randomUUID as k}from"node:crypto";import{lstat as N,readFile as f,rename as F,unlink as I}from"node:fs/promises";import{tmpdir as P}from"node:os";import{dirname as W,join as E,resolve as K}from"node:path";var B=process.platform==="win32",L=new Set;function V(j){if(j?.reason==="io-error"){if(j.win32Code===2||j.win32Code===3)return"ENOENT";if(j.win32Code===80||j.win32Code===183)return"EEXIST"}return j?.code??"ERR_PRIVATE_FILE"}var _;var b="native-addon-unavailable";function v(j){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:j}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:b})}function g(j,x){return x instanceof j.PrivateFilesUnavailableError||x?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function m(j){try{await j.verifyPrivatePath(E(P(),`.common-auth-private-files-probe-${k()}`),"file")}catch(x){if(g(j,x))throw v(x)}}function $(){return _??=import("@cortexkit/private-files").then(async(j)=>{if(B)await m(j);return j},(j)=>{throw B?v(j):j}),_}class Q extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor(j,x,z){let q=z;super(q?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${x}: ${j} (${b}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${x}: ${j} (${q?.reason??q?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:z});this.path=j,this.stage=x,this.name="PrivateFileError",this.code=V(q),this.win32Code=q?.win32Code,this.reason=q?.reason}}function p(j){return B&&j instanceof Q&&j.reason==="io-error"&&(j.win32Code===32||j.win32Code===303)}async function T(j,x,z){try{return await z()}catch(q){if(q instanceof Q)throw q;throw new Q(j,x,q)}}var c;async function Y(j,x){j=K(j),x??=c,await T(j,"safe-parent",async()=>{let z=await(await $()).verifySafeParent(j,x);if(z.ok===!1){if(z.reason==="io-error"||z.reason==="wrong-kind")await N(j);throw new Q(z.level??z.path,"safe-parent",{...z,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function S(j,x,z=!1){if(j=K(j),x==="directory")return Y(j);await T(j,"verify",async()=>{let q=await $(),H=await q.verifyOwnerOnly(j),C=!1;if(!H.ok){let{reason:J}=H.refusal;if(J==="io-error")await q.verifyPrivatePath(j,x);if(z&&[q.EXTRA_ACE,q.NOT_PROTECTED,q.NULL_DACL,q.EMPTY_DACL].includes(J))await Y(W(j)),await q.securePrivatePath(j,x),C=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:J,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await q.verifyPrivatePath(j,x),C&&!L.has(j))L.add(j),process.emitWarning(`Private permissions tightened: ${j}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function w(j,x=!1,z){j=K(j),await T(j,"directory",async()=>{let q=await $();try{return await N(j),await Y(j,z)}catch(C){if(V(C)!=="ENOENT")throw C}let H=W(j);if(H===j)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await w(H,!1,z);try{await q.createOwnerOnly(j,{kind:"dir"})}catch(C){if(V(C)!=="EEXIST")throw C}await Y(j,z)})}async function e(j,x=!1){if(!B)return f(j,"utf8");return(await u(j,x)).toString("utf8")}async function u(j,x=!1){if(!B)return f(j);if(j=K(j),x)await Y(W(j)),await S(j,"file",!0);return T(j,"read",async()=>(await $()).readOwnerOnly(j))}async function d(j,x){await Y(W(K(j))),await T(j,"create",async()=>{await(await $()).createPrivateFile(K(j),x)})}async function r(j){await Y(W(K(j))),await T(j,"directory-create",async()=>{await(await $()).createOwnerOnly(K(j),{kind:"dir"})})}async function l(j,x,z={}){j=K(j),x=K(x);let q=z.now??(()=>performance.now()),H=q(),C=z.deadline??1/0,J,Z=[0,10,20,40,80,100],U,G=0;for(let D of Z){let R=Math.min(J??1/0,C);if(q()>=R)break;if(D)await(z.sleep??((O)=>new Promise((X)=>setTimeout(X,O))))(Math.min(D,Math.max(0,R-q())));if(q()>=R)break;let A=q();if(await z.beforeRename?.(),J!==void 0)J+=q()-A;if(q()>=C)break;G++;try{return await(z.rename??F)(j,x),{attempts:G,elapsedMs:q()-H}}catch(O){U??=O;let X=O;if(!(X.win32Code!==void 0?X.win32Code===32||X.win32Code===33:["EBUSY","EPERM","EACCES"].includes(X.code??"")&&!X.reason))break;J??=q()+500}}let M=new Q(x,"rename",U??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw M.attempts=G,M.elapsedMs=q()-H,M}async function a(j,x,z={}){j=K(j),await w(W(j));try{await S(j,"file",!0)}catch(G){if(G.code!=="ENOENT")throw G}let q=K(z.stagePath??`${j}.${k()}.tmp`);if(W(q)!==W(j))throw new Q(j,"stage-directory",{code:"EXDEV"});let H=!1,C=!1,J={attempts:0,elapsedMs:0},Z="stage-create",U=(G)=>{try{z.onOutcome?.({path:j,stage:G?.stage??"published",published:C,fileDurable:C,durabilityConfirmed:!1,attempts:G?.attempts??J.attempts,elapsedMs:G?.elapsedMs??J.elapsedMs,...G&&{code:G.code,win32Code:G.win32Code}})}catch{}};try{if(await d(q,x),H=!0,Z="before-rename",J=await l(q,j,z),H=!1,C=!0,Z="published-callback",z.onRenamed?.(),Z="published-verify",await S(j,"file"),z.durable&&z.durability!=="file-only-on-windows")throw new Q(j,"directory-sync-unsupported",{code:"ENOTSUP"});U()}catch(G){let M=G instanceof Q?G:new Q(j,Z,G);if(M.published=C,M.fileDurable=C,C)Object.assign(M,J);if(H){try{await I(q)}catch{M.orphanPath=q}H=!1}throw U(M),M}finally{if(H)await I(q).catch(()=>{})}}
|
|
2
|
+
export{B as Vf,Q as Wf,p as Xf,T as Yf,Y as Zf,S as _f,w as $f,e as ag,d as bg,r as cg,l as dg,a as eg};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import{lf as u,of as w,pf as N3,qf as M$,rf as q3,sf as M3}from"./index-3x7q1rj8.js";import{Lf as o$,Mf as C,Of as z8,Sf as j6}from"./index-7at0fc03.js";import{$f as I3,Vf as s,Wf as d0,Zf as q4,ag as k$,eg as M4}from"./index-dp68014q.js";var P="all",X3=Object.freeze(["primary"]);function MZ($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function T0($,Z){return JSON.stringify([$,Z])}function t($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function A($){return typeof $==="number"&&Number.isFinite($)}function qZ($){return typeof $==="string"&&$.length>0}function E($,Z,z){return $[Z]===void 0||z($[Z])}function J8($){return A($)&&$>0}function z3($){return typeof $==="string"}function G8($){if(!t($)||!qZ($.scope)||!qZ($.label))return!1;switch($.kind){case"reading":return A($.checkedAt)&&A($.usedPercent)&&E($,"resetsAt",z3)&&E($,"windowMinutes",J8);case"retired":return A($.retiredAt);case"absent":return A($.checkedAt);default:return!1}}function B8($){if(!t($)||!A($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&E($,"remainingPercent",A)&&E($,"usedPercent",A)&&E($,"resetsAt",z3)&&E($,"limit",A)&&E($,"used",A)&&E($,"remaining",A)&&E($,"unit",z3)}function _Z($){return t($)&&A($.value)&&Number.isInteger($.value)&&$.value>=0&&A($.checkedAt)}function Y3($){return t($)&&Object.values($).every(_Z)}function K8($){return typeof $==="boolean"}function c($){return t($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&E($,"balance",A)&&E($,"overageLimitReached",K8)&&A($.checkedAt)}function J3($){if(!t($))return;let Z=Object.entries($).filter(([,z])=>_Z(z));return Z.length===0?void 0:Object.fromEntries(Z)}function W0($){if(H0($))return $;if(!t($))return;let{counters:Z,credits:z,...X}=$;if(!H0(X))return;let Y=J3(Z),G=c(z)?z:void 0;return{...X,...Y===void 0?{}:{counters:Y},...G===void 0?{}:{credits:G}}}function H0($){if(!t($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let z of $.limits){if(!G8(z))return!1;let X=T0(z.scope,z.label);if(Z.has(X))return!1;Z.add(X)}return E($,"budget",B8)&&E($,"counters",Y3)&&E($,"credits",c)}var xZ=900000,RZ="no quota reading yet",SZ="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 AZ($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function G3($){if($.scope!==P||$.windowMinutes===void 0)return $.label;return AZ($.windowMinutes)}function B3($){return Math.min(100,Math.max(0,$))}function Q$($){return Math.round(B3($))}function OZ($){return`${Q$($)}% left`}function jZ($,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 H8($,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 W8($){let Z=EZ($.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 LZ($){return Number.isFinite($.remainingPercent)&&Number.isFinite($.checkedAt)}function K3($,Z,z=!1){if(!$)return{windows:[]};let{now:X}=Z,G=$.limits.filter((K)=>K.kind==="reading"&&(z||LZ(K))).sort(H8).map((K)=>{let Q=LZ(K)?{kind:"window",reading:"known",name:G3(K),short:"",figure:OZ(K.remainingPercent),remainingPercent:B3(K.remainingPercent),checkedAt:K.checkedAt,...jZ(K.resetsAt,K.checkedAt,X)}:{kind:"window",reading:"unknown",name:G3(K),short:"",figure:"no reading",resetSinceReading:!1};return{scope:K.scope,...K.windowMinutes===void 0?{}:{windowMinutes:K.windowMinutes},part:Q}}),J=$.budget;if(J){let K=J.remainingPercent,Q=J.reached?"credits spent":K!==void 0?`credits ${OZ(K)}`:"credits available";G.push({scope:P,spent:J.reached,part:{kind:"budget",reading:"known",name:"credits",short:"",figure:Q,...K===void 0?{}:{remainingPercent:B3(K)},checkedAt:J.checkedAt,...jZ(J.resetsAt,J.checkedAt,X)}})}W8(G);let B=G.flatMap(({part:K})=>K.reading==="known"&&K.checkedAt!==void 0?[K.checkedAt]:[]);if(B.length>0){let K=X-Math.min(...B);if(K>(Z.staleAfterMs??xZ))return{windows:G,age:`checked ${TZ(K)} ago`}}return{windows:G}}function Q8($,Z){return K3($,Z).age!==void 0}function PZ($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function EZ($){let Z=[...new Set($.map(PZ))],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 K=z.get(B)??2;if(K<B.length)z.set(B,K+1),G=!0}}if(!G)break}return new Map($.map((Y)=>[Y,X(PZ(Y))]))}var U8=2;function D8($){let Z=$.map((X)=>X.label.trim()||X.scope),z=EZ(Z);return Z.map((X)=>z.get(X)??X)}function V8($,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,K)=>{let H=z.filter(({scope:W})=>W===B.scope).reduce((W,V)=>W===void 0||(V.part.remainingPercent??0)<(W.part.remainingPercent??0)?V:W,void 0);return H?[{group:B,listed:K,window:H}]:[]});if(X.length===0)return;let Y=D8($),G=(B)=>B.window.part.remainingPercent??0,J=[...X].sort((B,K)=>G(B)-G(K)||B.listed-K.listed).slice(0,U8).sort((B,K)=>B.listed-K.listed);return J.map((B,K)=>{let{windowMinutes:Q}=B.window,H=[Y[B.listed]??B.group.scope,...Q===void 0?[]:[AZ(Q)],`${Q$(G(B))}%`].join(" ");return K===J.length-1?`${H} left`:H})}function F8($,Z){let{windows:z}=K3($,Z),X=V8($?.groups,z);if(X)return X;let Y=z.filter(({part:W,scope:V})=>W.kind==="window"&&V===P),G=z.filter(({part:W,scope:V})=>W.kind==="window"&&V!==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,V)=>W===void 0||V.remaining<W.remaining?V:W,void 0),H=Y.map(({part:W})=>`${W.name} ${Q$(W.remainingPercent??0)}%`);if(Q)H.push(`${Q.label} ${Q$(Q.remaining)}%`);if(H.length===0)return z.map(({part:W})=>W.figure);return H.map((W,V)=>V===H.length-1?`${W} left`:W)}function CZ($,Z){if(Z.form==="narrow")return F8($,Z);let{windows:z,age:X}=K3($,Z),Y=(Z.form??"full")==="full",G=z.map(({part:J})=>{let B=Y&&J.resetIn?`, resets ${J.resetIn}`:"";return`${J.kind==="budget"?"":`${J.name} `}${J.figure}${B}`});return X===void 0?G:[...G,X]}function N8($,Z){let z=CZ($,Z);if(z.length>0)return z.join(" · ");return $&&$.limits.length>0?SZ:RZ}function q8($){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 M8($){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 _8($,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 O8($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function y($,Z=P){let z=new Map;for(let H of $?.limits??[]){if(H.scope!==Z&&H.scope!==P)continue;let W=z.get(H.label);if(W===void 0){z.set(H.label,H);continue}let V=H.scope===P?W:H,D=H.scope===P?H:W;z.set(H.label,V.kind==="reading"?V:D)}let X=[...z.values()].map(M8).sort(_8),Y=X.filter((H)=>H.kind==="reading"),G=Y.length>0?Y:X,J=G.length>0?Math.min(...G.map((H)=>H.checkedAt)):void 0,B=$?.budget?.kind==="reading"?O8($.budget):void 0,K=J3($?.counters),Q=c($?.credits)?$.credits:void 0;return{scope:Z,limits:X,...J===void 0?{}:{checkedAt:J},...B===void 0?{}:{budget:B},...K===void 0?{}:{counters:K},...Q===void 0?{}:{credits:Q}}}function Q0($,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 U$($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function v0($,Z){if(typeof $.resetsAt!=="string")return;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z>Z?z:void 0}class D$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function F$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V$($){return typeof $==="number"&&Number.isFinite($)}function IZ($){return $===void 0||typeof $==="string"&&$!==""}function kZ($){return typeof $==="string"&&$!==""}function g0($,Z){return $[Z]===void 0||V$($[Z])}function H3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function j8($){return F$($)&&IZ($.scope)&&kZ($.label)&&V$($.usedPercent)&&H3($,"resetsAt")&&($.windowMinutes===void 0||V$($.windowMinutes)&&$.windowMinutes>0)}function L8($){return F$($)&&IZ($.scope)&&kZ($.label)}function P8($){if(!F$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&g0($,"remainingPercent")&&g0($,"usedPercent")&&H3($,"resetsAt")&&g0($,"limit")&&g0($,"used")&&g0($,"remaining")&&H3($,"unit")}function A0($){if(!F$($)||!V$($.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(!j8(Y))return!1;let G=T0(Y.scope??P,Y.label);if(X.has(G))return!1;X.add(G)}if(!z.every(L8))return!1;return($.budget===void 0||P8($.budget))&&($.counters===void 0||Y3($.counters))&&($.credits===void 0||c($.credits))}function x8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function R8($,Z,z){if(Z===void 0)return $;if($!==void 0&&z<$.checkedAt)return $;return{...Z,checkedAt:z}}function S8($,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 T8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function p0($,Z){let z=$===void 0?void 0:W0($);if($!==void 0&&z===void 0)throw new D$("stored quota map is malformed");if(!A0(Z))throw new D$("quota observation is malformed");let X=z??{limits:[]},Y=Z.checkedAt,G=new Map;for(let M of X.limits)G.set(T0(M.scope,M.label),M);let J=(M)=>{let L=G.get(M);return L===void 0||Y>=MZ(L)},B=new Set;for(let M of Z.readings??[]){let L=M.scope??P,x=T0(L,M.label);if(B.add(x),!J(x))continue;G.set(x,{scope:L,label:M.label,kind:"reading",checkedAt:Y,usedPercent:M.usedPercent,...M.resetsAt===void 0?{}:{resetsAt:M.resetsAt},...M.windowMinutes===void 0?{}:{windowMinutes:M.windowMinutes}})}for(let M of Z.coverage??[]){let L=M.scope??P,x=T0(L,M.label);if(B.has(x)||!J(x))continue;let f=G.get(x);G.set(x,f===void 0||f.kind==="absent"?{scope:L,label:M.label,kind:"absent",checkedAt:Y}:{scope:L,label:M.label,kind:"retired",retiredAt:Y})}let{limits:K,budget:Q,counters:H,credits:W,...V}=X,D=R8(X.budget,Z.budget,Y),U=S8(X.counters,Z.counters),_=T8(X.credits,Z.credits);return{...V,limits:[...G.values()].sort(x8),...D===void 0?{}:{budget:D},...U===void 0?{}:{counters:U},..._===void 0?{}:{credits:_}}}var A8=Object.freeze({validate:H0,decode:W0,merge:p0});function fZ($,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 E8($,Z,z,X,Y){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let J of z)if(!Z.limits.some((B)=>B.label===J))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:J},pullRequested:!0};let G=Z.limits.filter(U$);for(let J of G)if(v0(J,X)===void 0&&!Y.some((B)=>B.scope===J.scope&&B.label===J.label))return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:J.scope,label:J.label},pullRequested:!0};for(let J of G){let B=v0(J,X);if(B!==void 0&&typeof J.resetsAt==="string")return{id:$,stage:1,gate:5,reason:"exhausted",window:{scope:J.scope,label:J.label},resetsAt:J.resetsAt,resetAtMs:B}}return}function g($){let Z=$.scope??P,z=$.requiredLabels??X3,X=[],Y=[],G=[],J=new Set;for(let D of $.rows){let U=fZ(D.id,$,$.now);if(U){X.push(U);continue}if(D.kind==="api-key"){G.push({id:D.id,kind:D.kind});continue}let _=y(D.quota,Z),M=$.liftedWindows?.get(D.id)??[];if(_.limits.some((x)=>U$(x)&&v0(x,$.now)===void 0&&M.some((f)=>f.scope===x.scope&&f.label===x.label)))J.add(D.id);let L=E8(D.id,_,z,$.now,M);if(L){Y.push(L);continue}G.push({id:D.id,kind:D.kind,projection:_})}let B=new Map(G.flatMap((D)=>{let U=Q0(D.projection,$.now);return U?[[D.id,U]]:[]})),K=B.size>0&&B.size===G.length,Q=[];for(let D of G){let U=B.get(D.id);if(U===void 0)Q.push(D);else if(K)Q.push({...D,lastPath:!0});else Y.push({id:D.id,stage:2,reason:"budget-spent",...U})}let H=new Map($.rows.map((D,U)=>[D.id,U])),W=(D,U)=>(H.get(D.id)??0)-(H.get(U.id)??0);Y.sort(W);for(let D of Y)if("pullRequested"in D)J.add(D.id);let V=$.rows.filter((D)=>J.has(D.id)).map((D)=>D.id);for(let D of V)$.requestPull?.(D);return{admitted:Q,refused:Y,excluded:X,pulls:V}}var bZ="main";function C8($){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 N$($,Z,z=bZ){if(Z==="roster"||!$.includes(z))return[...$];let X=$.filter((Y)=>Y!==z);return Z==="main-first"?[z,...X]:[...X,z]}function W3($){let Z=g($),z=new Set(Z.admitted.map((Y)=>Y.id));return{order:N$($.rows.map((Y)=>Y.id),$.placement??"roster",$.formerMainId).filter((Y)=>z.has(Y)&&$.killswitch?.get(Y)!==!1),admission:Z}}function I8($,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 Q3($,Z,z){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof z==="string"&&$.wireIdentity!==z)}function k8($,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 l0=900000,wZ=0.016666666666666666,U3=0.000001;function q$($,Z){for(let z of[$?.checkedAt,Z])if(typeof z==="number"&&Number.isFinite(z))return z;return}function hZ($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function mZ($){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 V3($){let Z=($.classifyStatus??hZ)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let z=q$($.quota,$.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||$.now-z>l0)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of mZ($.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=Q0($.quota,$.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:Z}}function D3($,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,wZ);return X/G}function yZ($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function f8($,Z){if(!$.quota)return;let z=q$($.quota,$.quotaCheckedAt);if(z===void 0||Z-z>l0)return;let X=mZ($.quota).map((J)=>D3({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(D3({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 vZ($){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)=>f8(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,U3),K=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,U3);return B-K||G.candidate.configuredOrder-J.candidate.configuredOrder||yZ(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||yZ(Y.accountId,G.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:q$(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function F3($){let Z=g($),z=new Map(Z.admitted.map((U)=>[U.id,U])),X=new Map(Z.refused.map((U)=>[U.id,U])),Y=new Set(Z.excluded.map((U)=>U.id)),G=new Set($.rows.map((U)=>U.id)),J=$.pin!==void 0&&Q3($.pin,G,$.identities?.get($.pin.accountId));if(J&&$.pin){let U=z.get($.pin.accountId);if(U&&$.killswitch?.get(U.id)!==!1)return{outcome:"dispatch",accountId:U.id,source:"pin",...U.projection?.checkedAt===void 0?{}:{quotaCheckedAt:U.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let B=$.pin?X.get($.pin.accountId):void 0,K=J&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),Q=(U)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(U):$.rowReservePercent?.get(U.id))??$.reservePercent??{}},H=$.scope,W=$.rows.map((U,_)=>({row:U,configuredOrder:_})).filter(({row:U})=>!Y.has(U.id)).map(({row:U,configuredOrder:_})=>{let M=$.killswitch?.get(U.id),L=$.resetCreditsApplicable?.get(U.id);return{accountId:U.id,quota:U.kind==="api-key"?void 0:z.get(U.id)?.projection??y(U.quota,H),reservePercent:Q(U),configuredOrder:_,...L===void 0?{}:{resetCreditsApplicable:L},...M===void 0?{}:{killswitchPasses:M}}}),V=[],D=J?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(W.length>0){let U=vZ({candidates:W,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!U)break;let _=X.get(U.accountId);if(_){V.push(_),W=W.filter((L)=>L.accountId!==U.accountId);continue}let M=$.identities?.get(U.accountId);return{outcome:"dispatch",accountId:U.accountId,source:U.source,...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt},pin:J&&!K?{action:"retain"}:{action:"assign",pin:{accountId:U.accountId,inputBytes:$.requestBytes,...M===void 0?{}:{wireIdentity:M},...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt}}},refusedSelections:V,admission:Z}}return{outcome:"no-admissible-account",pin:D,refusedSelections:V,admission:Z}}import{createHash as b8}from"node:crypto";var y8=86400000,w8=300000,h8=3600000,m8=60000,v8=900000,g8=300000;function _3($){return $ instanceof Error?$.message:String($)}function p8($){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 O3($){let Z=_3($),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 gZ($){return b8("sha256").update($).digest("hex")}function pZ($){let Z=gZ($.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(p8($.error))Y=Math.min(h8,w8*2**Math.min(X-1,6));else Y=y8;return{message:_3($.error),checkedAt:$.now,nextRetryAt:$.now+Y,retryCount:X,tokenHash:Z}}function U0($,Z,z){if(!$?.nextRetryAt||$.nextRetryAt<=z)return!1;if(!Z)return!0;return $.tokenHash===gZ(Z)}function _$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function c0($){let z=($.previous?.retryCount??0)+1,X,Y=$.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(O3($.error))X=Math.min(v8,m8*2**Math.min(z-1,6));else X=g8;return{message:_3($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:z}}function E0($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function j3($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let 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 lZ}from"node:http";import{setTimeout as l8}from"node:timers/promises";var P$="app_EMoamEEZ73f0CkXaXp7hrann",F0="https://auth.openai.com",i0=1455,d8=3000,c8="cortexkit-opencode-openai-auth";function iZ($){return`${c8}/${$}`}var sZ="main",u8=`"${sZ}" is a reserved account id; choose a different label.`;function aZ($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function i8(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=aZ(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:z}}function dZ($){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 cZ($){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 j$($){if($.id_token){let Z=dZ($.id_token),z=Z&&cZ(Z);if(z)return z}if($.access_token){let Z=dZ($.access_token);return Z?cZ(Z):void 0}return}function s8($){return typeof $==="string"&&$.toLowerCase()===sZ}function L3($){if(s8($))throw Error(u8);return $}function a8($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:P$,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`${F0}/oauth/authorize?${X.toString()}`}async function n8($,Z,z){let X=await fetch(`${F0}/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:P$,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function o8($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var r8=`<!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>`,O$=($)=>`<!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">${o8($)}</div>
|
|
85
|
+
</div>
|
|
86
|
+
</body>
|
|
87
|
+
</html>`,L$=[],u0,i=new Map;function uZ($,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(i0,Z)})}function nZ($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function D0(){return i.size}function N0($){if(i.delete($),D0()===0)V0()}async function t8(){let $=`http://localhost:${i0}/auth/callback`;if(L$.length>0)return{port:i0,redirectUri:$};if(u0)return u0;u0=(async()=>{let Z=(G,J)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${i0}`);if(B.pathname==="/auth/callback"){let K=B.searchParams.get("code"),Q=B.searchParams.get("state"),H=B.searchParams.get("error"),W=B.searchParams.get("error_description");if(H){let D=W||H;if(Q){let U=i.get(Q);if(U)U.reject(Error(D)),N0(Q);else if(D0()===0)V0()}else if(D0()===0)V0();J.writeHead(200,{"Content-Type":"text/html"}),J.end(O$(D));return}if(!Q){if(D0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(O$("Missing state parameter"));return}if(!K){if(D0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(O$("Missing authorization code"));return}let V=i.get(Q);if(!V){if(D0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(O$("Unknown state — authorization may have expired"));return}N0(Q),n8(K,$,V.pkce).then((D)=>V.resolve(D)).catch((D)=>V.reject(D)),J.writeHead(200,{"Content-Type":"text/html"}),J.end(r8);return}if(B.pathname==="/cancel"){let K=B.searchParams.get("state"),Q=K?[K]:[...i.keys()];J.writeHead(200),J.end("Login cancelled");for(let H of Q){let W=i.get(H);if(!W)continue;W.reject(Error("Login cancelled")),N0(H)}if(D0()===0)V0();return}J.writeHead(404),J.end("Not found")},z=lZ(Z);await uZ(z,"127.0.0.1");let X=[z],Y=lZ(Z);try{await uZ(Y,"::1"),X.push(Y)}catch(G){let J=G.code;if(J!=="EADDRNOTAVAIL"&&J!=="EAFNOSUPPORT")throw nZ(z),G}return L$=X,{port:i0,redirectUri:$}})();try{return await u0}finally{u0=void 0}}function V0(){let $=L$;L$=[];for(let Z of $)nZ(Z)}function e8($,Z,z=300000,X){return new Promise((Y,G)=>{if(X?.aborted){N0(Z),G(Error("Login cancelled"));return}let J=setTimeout(()=>{if(i.get(Z))N0(Z),G(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(J),i.get(Z))N0(Z),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);i.set(Z,{pkce:$,state:Z,resolve:(K)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);Y(K)},reject:(K)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);G(K)}})})}async function $9($){let Z=await fetch(`${F0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":iZ($)},body:JSON.stringify({client_id:P$})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${F0}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function Z9($,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(`${F0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":iZ(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let H=await B.json(),W=await fetch(`${F0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:H.authorization_code,redirect_uri:`${F0}/deviceauth/callback`,client_id:P$,code_verifier:H.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 K=G-(Date.now()-J);if(K<=0)throw Error("Device authorization expired");let Q=Math.min(X+d8,K);try{await l8(Q,void 0,{signal:z})}catch(H){if(H instanceof Error&&H.name==="AbortError")throw Error("Device authorization cancelled");throw H}}}async function E7($){let{label:Z,headless:z=!1,signal:X,version:Y}=$;if(L3(Z),z){let{deviceData:H,url:W,instructions:V}=await $9(Y),D=(async()=>{let U=await Z9(H,Y,X),_=Date.now(),M=j$(U);return{id:L3(Z||M||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:U.access_token,refresh:U.refresh_token,expires:_+(U.expires_in??3600)*1000,enabled:!0,addedAt:_,lastUsed:_,lastRefreshedAt:_,accountId:M}})();return{url:W,instructions:V,completion:D}}let{redirectUri:G}=await t8(),J=await i8(),B=aZ(crypto.getRandomValues(new Uint8Array(32)).buffer),K=a8(G,J,B),Q=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let H=await e8(J,B,void 0,X),W=Date.now(),V=j$(H);return{id:L3(Z||V||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:H.access_token,refresh:H.refresh_token,expires:W+(H.expires_in??3600)*1000,enabled:!0,addedAt:W,lastUsed:W,lastRefreshedAt:W,accountId:V}}finally{N0(B)}})();return{url:K,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}function x$($){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 P3($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function oZ($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function rZ($,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=P3($.get(`${Y}-window-minutes`)),J=x$($.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 Z4=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function z4($,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 I7($){if(Z4.some((G)=>z4($,G)==="invalid"))return{};let Z={},z=rZ($,"x-codex-primary-used-percent");if(z)Z.primary=z;let X=rZ($,"x-codex-secondary-used-percent");if(X)Z.secondary=X;let Y=z9($);if(Y)Z.credits=Y;return Z}function tZ($,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 z9($){let Z=tZ($,"x-codex-credits-has-credits"),z=tZ($,"x-codex-credits-unlimited");if(Z===void 0||z===void 0)return;let X=e($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:z,...X!==void 0?{balance:X}:{},checkedAt:Date.now()}}function k7($){let Z=Z4.map((z)=>z4($,z));return Z.includes("valid")&&!Z.includes("invalid")}function eZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=P3($.window_minutes),z=x$($.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 f7($){let Z={},z=eZ($.rate_limits?.primary);if(z)Z.primary=z;let X=eZ($.rate_limits?.secondary);if(X)Z.secondary=X;let Y=X9($.credits);if(Y)Z.credits=Y;return Z}function X9($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let z=e(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 e($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function $4($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=P3($.limit_window_seconds),z=x$($.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 X4($){let Z={},z=$4($.rate_limit?.primary_window);if(z)Z.primary=z;let X=$4($.rate_limit?.secondary_window);if(X)Z.secondary=X;let Y=oZ($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let G=oZ($.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 K=e(J.limit),Q=e(J.used),H=e(J.remaining),W=e(J.used_percent),V=e(J.remaining_percent);if(K!==void 0&&Q!==void 0&&H!==void 0&&W!==void 0&&V!==void 0)Z.spendControl={limit:K,used:Q,remaining:H,usedPercent:W,remainingPercent:V,resetsAt:x$(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 K=e(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...K!==void 0?{balance:K}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as j1}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as Y9}from"@cortexkit/claustrum-client";import{SocketClosedError as J9,SocketTimeoutError as G9,SubcCallError as B9}from"@cortexkit/subc-client";class F extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var x3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",route_busy:"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 R extends F{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function p($){if($ instanceof R||$ instanceof J9||$ instanceof G9)return"unreachable";let Z=$ instanceof Y9||$ instanceof B9?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(x3,Z))return"answered";return x3[Z]}import{resolve as Y4}from"node:path";import{storeIdentity as K9}from"@cortexkit/claustrum-client";import{SubcClient as J4}from"@cortexkit/subc-client";var C0=300000,R$=300000,R3=1000;class s0{#$;#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 S${#$;#Z;#B;#J=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#B}request(){if(this.#B)return this.#J=!0,this.#B;return this.#B=(async()=>{do{this.#J=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#J)})().finally(()=>{this.#B=void 0}),this.#B}}class T${#$;#Z=new s0;#B;#J="polling";#Y;#K;#X=!1;#z;#q=!1;#G=0;constructor($){this.#$=$,this.#B=new S$(async()=>{let Z=this.#q;if(this.#q=!1,Z||this.#z!==this.#$.view())await this.#$.discover(this.#z??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#J}start(){if(this.#X||this.#Y||this.#K)return;if(typeof this.#$.client.watchScoped!=="function"){this.#H("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#K)(this.#$.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let $=this.#Y;this.#Y=void 0,$?.handle.stop()}#H($,Z){if(this.#J===$)return;this.#J=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#K=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,!this.#X)Z()},$),this.#K.unref?.()}async#V($){let Z;try{Z=await this.#$.enrollmentToken()}catch(J){if(this.#X)return;this.#$.onError?.(J),this.#F("token-unreadable");return}let z=this.#$.client.watchScoped;if(this.#X||this.#Y||!z)return;this.#Z.restart(),this.#q=$;let X,Y;try{Y=z.call(this.#$.client,(J)=>{if(this.#X||!X||this.#Y!==X)return;if(X.notices++,X.notices===1)this.#$.onReachable?.(),X.acceptedAt=(this.#$.now??Date.now)(),this.#H("watching","accepted");if(!this.#Z.continuous(J))this.#q=!0;this.#z=J.view,this.#B.request()},{enrollmentToken:Z})}catch(J){this.#$.onError?.(J),this.#F("watch-failed");return}X={handle:Y,notices:0},this.#Y=X,this.#H("polling",$?"resubscribing":"opening");let G=X;Y.closed.then((J)=>this.#Q(G,J),(J)=>this.#Q(G,{kind:"transport_lost",error:J}))}#Q($,Z){if(this.#X||this.#Y!==$)return;if(this.#Y=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#H("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("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.#G=0;let X=Math.min(1000*2**Math.min(this.#G,16),300000);this.#G++,this.#H("polling","resubscribing"),this.#U(X,()=>void this.#V(!0));return}this.#F(Z.kind)}#F($){this.#H("fallback",$),this.#U(300000,()=>void this.#V(!1))}}function B4($){let Z=$.identity??K9($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let z,X=!1,Y,G=new Promise((B,K)=>{Y=setTimeout(()=>K(Error("insula usage timeout")),3000),Y.unref?.()}),J=(async()=>{if(z=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await J4.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,K=new Promise((H,W)=>{B=setTimeout(()=>W(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),Q=(async()=>{let H=Math.min($.handshakeTimeoutMs??3000,3000),W=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:H}):await J4.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:H});if(X=W,G){W.close();return}let V=await W.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(G){W.close();return}Y=W.subscribe(V,{method:"usage.watch"},z)})();try{await Promise.race([Q,K])}catch(H){throw G=!0,H}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 E$=60000,G4=4*E$,H9=2*E$,S3=new Map,A$=new Map;function I0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function W9($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!I0(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 Q9($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class K4{transport;key;#$=[];#Z=!1;#B=new Set;#J=new Map;#Y=new S$(async()=>{try{let $=await this.transport.getUsage();if(!I0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>I0(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#B=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#B)this.#J.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#B.clear()}},()=>{});#K=new s0;#X="polling";#z=0;#q=0;#G=new Map;#H;#U;#V={};#Q=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Y.running)return this.#Y.running;if(this.#X==="watching")return Promise.resolve();for(let[z,X]of A$)if($-X>=E$)A$.delete(z);let Z=A$.get(this.key);if(Z!==void 0&&$-Z<E$)return Promise.resolve();return A$.set(this.key,$),this.#Y.request()}watchMode(){return this.#X}watch($={}){this.#z++;let Z=$.provider;if(Z===void 0)this.#q++;else this.#G.set(Z,(this.#G.get(Z)??0)+1);if(this.#z===1)this.#V=$,this.#x();let z=!1;return()=>{if(z)return;if(z=!0,Z===void 0)this.#q--;else{let X=(this.#G.get(Z)??1)-1;if(X>0)this.#G.set(Z,X);else this.#G.delete(Z)}if(--this.#z===0)this.#F()}}#F(){if(this.#U)(this.#V.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#H;this.#H=void 0,$?.handle?.stop(),this.#X="polling"}#M($){this.#U=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#z>0&&!this.#H)this.#x()},$),this.#U.unref?.()}#x(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#K.restart();let Z={notices:0};this.#H=Z;let z;try{z=$.call(this.transport,(X)=>this.#j(Z,X))}catch(X){this.#L(Z,X);return}Z.handle=z,z.closed.then(()=>this.#L(Z,void 0),(X)=>this.#L(Z,X))}#j($,Z){if(this.#H!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#Q=0;let z=W9(Z);if(!z)this.#K.restart();if(!(z?this.#K.continuous(z):!1)||z?.provider===void 0||this.#q>0||this.#G.has(z.provider))this.#Y.request()}#L($,Z){if(this.#H!==$)return;this.#H=void 0;let z=Q9(Z);if(z==="unknown_method"||z==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let X=Math.min(R3*2**Math.min(this.#Q,16),R$);this.#Q++,this.#X="polling",this.#M(X);return}if(this.#X="fallback",this.#Y.request(),Z===void 0||p(Z)==="unreachable")this.#M(R$)}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||!I0(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=G4)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(!I0(X.usage)||!Number.isFinite(J))return{miss:"unreachable"};let B={entry:X,context:{fetchedAt:J,...typeof X.source==="string"&&{source:X.source}}};if(X.stale!==void 0&&(!I0(X.stale)||X.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:B};return z>=J+G4||X.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#B.has($))return{miss:"absent"};let G=this.#J.get($)??z;return this.#J.set($,G),{miss:z-G>=H9?"unreachable":"cold"}}}function T3($,Z){let z=JSON.stringify([Y4($.connectionFile),Y4(Z)]),X=S3.get(z);if(!X)X={source:new K4($,z),refs:0},S3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)S3.delete(z)}}}import{ClaustrumCredentialError as yz}from"@cortexkit/claustrum-client";function q0($){let Z=new AbortController,z=[],X=!1,Y=()=>{if(X)return;X=!0;for(let{source:B,listener:K}of z)B.removeEventListener("abort",K);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 K=()=>G(B.reason);if(z.push({source:B,listener:K}),B.addEventListener("abort",K,{once:!0}),B.aborted)G(B.reason)}return{signal:Z.signal,dispose:Y}}import{channel as l9}from"node:diagnostics_channel";import{ClaustrumCredentialError as v4}from"@cortexkit/claustrum-client";import{createHash as L9,randomBytes as P9,randomUUID as x9}from"node:crypto";import{constants as Q4}from"node:fs";import{chmod as R9,mkdir as S9,open as _4,readFile as E3,realpath as T9,rename as A9,stat as O4,unlink as k3}from"node:fs/promises";import{basename as j4,dirname as Z0,extname as U4,isAbsolute as D4,join as f3,resolve as E9}from"node:path";import{ClaustrumCredentialError as C9,ClaustrumClient as I9,writeEnrollmentTokenFile as k9}from"@cortexkit/claustrum-client";import{lstat as U9,stat as D9}from"node:fs/promises";import{resolve as V9}from"node:path";async function F9($,Z){try{let z=await(Z?D9($):U9($));return z.isFile()?z:void 0}catch(z){return z.code==="ENOENT"?"absent":void 0}}function N9($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class a0{#$;#Z=new Map;constructor($={}){this.#$=$.followSymlinks??!1}async read($,Z,z){let X=$.map((Q)=>V9(Q)),Y=JSON.stringify(X),G=await Promise.all(X.map((Q)=>F9(Q,this.#$))),J=G.every((Q)=>Q!==void 0)?G:void 0,B=this.#Z.get(Y);if(J&&B&&J.every((Q,H)=>{let W=B.identities[H];return W!==void 0&&N9(Q,W)}))return z?.(J),B.value;this.#Z.delete(Y);let K=await Z(X);if(J){if(this.#Z.size>=64){let Q=this.#Z.keys().next().value;if(Q!==void 0)this.#Z.delete(Q)}this.#Z.set(Y,{identities:J,value:K})}return K}}import{ClaustrumCredentialError as q9}from"@cortexkit/claustrum-client";var M9="Served by Thalamus",_9="This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.",H4=new WeakSet;function W4($){return H4.has($)}function S(){return process.env.CORTEXKIT_VAULT_HOST==="thalamus"}function A3($){if(typeof $!=="object"||$===null)return $;let Z=$;if(typeof Z.code==="string"&&(Z.class==="transient"||Z.class==="permanent"||Z.class==="auth_required"||Z.class==="context_overflow")&&(Z.action==="gone"||Z.action==="reauth"||Z.action==="retry"||Z.action==="reduce_and_retry"))return new q9(Z.code,Z.class,Z.action);if(Z.name==="ClaustrumUnreachableError"||typeof Z.code==="string"&&p(Object.assign(Error(),{code:Z.code}))==="unreachable")return new R;return $}function n0($){try{return $()}catch(Z){throw A3(Z)}}async function M0($){try{return await $()}catch(Z){throw A3(Z)}}function O9($){let Z=$.watchScoped?.bind($),z=$.reportUsageScoped?.bind($);return{listScoped:(...X)=>M0(()=>$.listScoped(...X)),getScoped:(...X)=>M0(()=>$.getScoped(...X)),reportAuthFailureScoped:(...X)=>M0(()=>$.reportAuthFailureScoped(...X)),close:()=>n0(()=>$.close()),...Z&&{watchScoped:(...X)=>{let Y=n0(()=>Z(...X));return{stop:()=>n0(()=>Y.stop()),closed:M0(async()=>{let G=await Y.closed;return G.kind==="refused"||G.kind==="transport_lost"?{...G,error:A3(G.error)}:G})}}},...z&&{reportUsageScoped:(...X)=>M0(()=>z(...X))},...$.insula&&{insula:j9($.insula)}}}function j9($){let Z=$.watchUsage?.bind($);return{connectionFile:$.connectionFile,getUsage:()=>M0(()=>$.getUsage()),...Z&&{watchUsage:(...z)=>{let X=n0(()=>Z(...z));return{stop:()=>n0(()=>X.stop()),closed:M0(()=>X.closed)}}}}}function _0($){if(!S()||!$)throw new R;try{let Z=globalThis[Symbol.for("cortexkit.vault")];if(typeof Z!=="function")throw new R;let z=O9(Z($));return H4.add(z),z}catch{throw new R}}var f9=1,I$=16384,L4=30000,b3=/^[0-9a-f]{64}$/,P4="unknown_method",x4=new Set([P4,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),R4=new Set(["pending_queue_full"]);function C3($){if(!($ instanceof C9))return;if(x4.has($.code))return{code:$.code,disposition:"terminal"};if(R4.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function b9($,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 y9($){return I9.connect($)}function S4($){let Z=U4($)||".json",z=j4($,U4($));return{statePath:f3(Z0($),`${z}-state${Z}`),tokenPath:$}}function w9($){let Z=$.override?.trim();if(Z&&!D4(Z)&&!$.cwd)throw new F("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=Z?D4(Z)?Z:E9($.cwd,Z):f3($.stateDir,`${$.host}-enrollment.json`);return S4(z)}function T4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function C$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function A4($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function o0(){return new F("invalid-state","invalid Claustrum enrollment state")}function f$($){if(!T4($)||$.version!==f9||typeof $.proposedName!=="string"||$.proposedName.length===0)throw o0();if($.phase==="pending"){if(!b3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!C$($.createdAt)||!C$($.updatedAt))throw o0();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)||!A4($.tokenGeneration)||!C$($.updatedAt))throw o0();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"||!C$($.updatedAt))throw o0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw o0()}function y3($){if(!T4($)||!b3.test(String($.token??""))||!A4($.token_generation))throw new F("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function E4($){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 V4($){try{return JSON.parse($)}catch{throw new F("invalid-state","Claustrum enrollment file is not valid JSON")}}async function z0($){if(s)try{await I3(Z0($));let z=await k$($,!0);if(Buffer.byteLength(z)>I$)throw new F("unsafe-file","Claustrum enrollment file is too large");return V4(z)}catch(z){if(z.code==="ENOENT")return;throw z}let Z;try{Z=await _4($,Q4.O_RDONLY|Q4.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new F("unsafe-file","Claustrum enrollment file could not be opened safely")}try{E4(await Z.stat());let z=Buffer.alloc(I$+1),{bytesRead:X}=await Z.read(z,0,z.byteLength,0);if(X>I$)throw new F("unsafe-file","Claustrum enrollment file is too large");return V4(z.subarray(0,X).toString("utf8"))}finally{await Z.close()}}function F4($,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 h9($,Z,z){try{let[X,Y]=await Promise.all([E3(z.passwdPath??"/etc/passwd","utf8"),E3(z.groupPath??"/etc/group","utf8")]),G=F4(X,7),J=F4(Y,4);if(!G||!J)return!1;let B=G.filter((W)=>Number(W[2])===$),K=J.filter((W)=>Number(W[2])===Z);if(B.length!==1||K.length!==1)return!1;let Q=B[0]?.[0],H=K[0]?.[3]??"";return(H===""||H.split(",").every((W)=>W===Q))&&!G.some((W)=>Number(W[2])!==$&&Number(W[3])===Z)}catch{return!1}}function C4($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>E3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function I4($,Z={}){if(!s){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await T9($)}catch{return}let G;for(;;){let J=await O4(Y).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0){if(G===void 0)G=X!==void 0&&await h9(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=Z0(Y);if(B===Y)return;Y=B}}try{await q4($,C4(Z))}catch(z){if(!(z instanceof d0))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 k0($,Z={},z="enrollment directory"){if(s){await I3($,!1,C4(Z));return}await S9($,{recursive:!0,mode:448});let X=await O4($),Y=process.geteuid?.();if(Y!==void 0&&X.uid!==Y)throw new F("unsafe-file",`Claustrum ${z} must be owned by the current user`);if((X.mode&63)!==0)await R9($,448)}async function O0($,Z,z={}){let X=Z0($);await k0(X,z),await I4(X,z);let Y=`${JSON.stringify(Z)}
|
|
89
|
+
`;if(Buffer.byteLength(Y)>I$)throw new F("invalid-state","Claustrum enrollment state is too large");if(s)return M4($,Y);let G=f3(X,`.${j4($)}.${process.pid}.${x9()}.tmp`),J,B=!1;try{J=await _4(G,"wx",384),B=!0,await J.writeFile(Y,"utf8"),await J.chmod(384),await J.sync(),await J.close(),J=void 0,await A9(G,$),B=!1}finally{if(await J?.close().catch(()=>{}),B)await k3(G).catch(()=>{})}}var m9=new a0;async function w3($,Z){let z=s?await N4($,Z):await m9.read([$.tokenPath,$.statePath],async([Y=$.tokenPath,G=$.statePath])=>N4({tokenPath:Y,statePath:G},Z),(Y)=>{for(let G of Y)if(G!=="absent")E4(G)}),X={...z.status};if(z.usesProposedName&&X.state==="approved")X.proposedName=Z;return X}async function N4($,Z){let z=await z0($.tokenPath),X=z===void 0?void 0:y3(z),Y=await z0($.statePath),G=Y===void 0?void 0:f$(Y);if(X)return{usesProposedName:G===void 0,status:{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:X.token_generation}};if(!G)return{status:{state:"idle"},usesProposedName:!1};if(G.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:G.proposedName,code:"missing_token"}};return{status:$0(G),usesProposedName:!1}}async function k4($,Z){let z;try{z=await w3($,Z)}catch(X){if(!(X instanceof F)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await z0($.statePath);if(Y===void 0)return"unreadable";let G=f$(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 v9($,Z){if(S())return"host";return k4($,Z)}async function X0($){let Z=await z0($);if(Z===void 0)throw new F("not-enrolled","Claustrum enrollment is not configured");return y3(Z)}function $0($){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 f4(){return new F("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class b4{#$;#Z;#B;#J;#Y;#K;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#B=$.proposedName,this.#J=$.now??Date.now,this.#Y=$.mintSecret??(()=>P9(32).toString("hex")),this.#K=$.writeTokenFile??k9}async status(){return w3(this.#Z,this.#B)}async resetTerminal(){return y4(this.#Z,this.#B)}async#z($,Z){let z={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#J()};return await O0(this.#Z.statePath,z,this.#X),$0(z)}async reconcile(){await k0(Z0(this.#Z.statePath),this.#X);let $=await w({name:"ceremony",path:this.#Z.statePath,ttlMs:L4,renew:!0});if(!$)return{state:"busy"};try{let Z=await z0(this.#Z.tokenPath),z=Z===void 0?void 0:y3(Z),X=await z0(this.#Z.statePath),Y=X===void 0?void 0:f$(X);if(Y&&Y.proposedName!==this.#B)throw f4();if(z){if(!Y||Y.phase==="pending"){let J={version:1,phase:"approved",proposedName:Y?.proposedName??this.#B,tokenGeneration:z.token_generation,updatedAt:this.#J()};await O0(this.#Z.statePath,J,this.#X),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.#J()};return await O0(this.#Z.statePath,J,this.#X),$0(J)}if(Y&&Y.phase!=="pending")return $0(Y);if(!Y){let J=this.#J();if(Y={version:1,phase:"pending",proposedName:this.#B,requestSecret:this.#Y(),createdAt:J,updatedAt:J},!b3.test(Y.requestSecret))throw new F("invalid-state","invalid minted Claustrum enrollment secret");await O0(this.#Z.statePath,Y,this.#X)}if(!Y.requestId)try{let J=L9("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.#J()},await O0(this.#Z.statePath,Y,this.#X)}catch(J){let B=C3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};if(B.code===P4)return await $.assertOwned(),await k3(this.#Z.statePath).catch((K)=>{if(K.code!=="ENOENT")throw K}),{state:"unavailable",proposedName:Y.proposedName,code:B.code};return this.#z(Y,B.code)}let G=Y.requestId;if(!G)return $0(Y);try{let J=await this.#$.enrollPoll({requestId:G,requestSecret:Y.requestSecret});if(J.status==="pending")return $0(Y);if(J.status==="denied"){let K={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#J()};return await O0(this.#Z.statePath,K,this.#X),$0(K)}await k0(Z0(this.#Z.tokenPath),this.#X),await I4(Z0(this.#Z.tokenPath),this.#X),await this.#K(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.#J()};return await O0(this.#Z.statePath,B,this.#X),$0(B)}catch(J){let B=C3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:G,retryCode:B.code};return this.#z(Y,B.code)}}finally{await $.release()}}}async function y4($,Z){await k0(Z0($.statePath));let z=await w({name:"ceremony",path:$.statePath,ttlMs:L4,renew:!0});if(!z)return"busy";try{if(await z0($.tokenPath)!==void 0)return"refused-approved";let X=await z0($.statePath);if(X===void 0)return"idle";let Y=f$(X);if(Y.proposedName!==Z)throw f4();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await k3($.statePath),"reset"}finally{await z.release()}}var r0="claustrum-tombstone:v1:";function b$($){return`${r0}${$}`}function h3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function y$($){return typeof $==="string"&&$.startsWith(r0)}function w4($,Z){if(!h3($)||$.type!=="oauth")return!1;return $.refresh===b$(Z)}function h4($,Z){if(w4($,Z))return"placeholder";if(h3($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!y$($.refresh))return"login";if(h3($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function g9($){let Z=h4($.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 f0($,Z){let z=!1;return(X)=>{if(z)return;if(!Z||Z.aborted)z=!0;$.warn("claustrum shutdown drain timed out",{pendingOperations:X})}}async function b0($,Z){if(!$.size)return;let z,X=!1,Y=(async()=>{while(!X&&$.size)await Promise.allSettled([...$])})();try{if(await Promise.race([Y,new Promise((G)=>{z=setTimeout(()=>{X=!0,G()},2000)})]),X&&$.size)Z($.size)}finally{X=!0,clearTimeout(z)}}import{ClaustrumCredentialError as p9}from"@cortexkit/claustrum-client";function m4($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class m3{options;#$=new Map;#Z=new Map;#B=new Set;#J;#Y;#K=!1;#X=!1;#z=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#Y!==void 0,dropped:this.#z}}report($,Z){if(this.#K||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#z++;return}if(!m4(Z)||"credentialId"in Z||"vouched"in Z)throw Error("invalid reading");let z=JSON.stringify(Z);if(Buffer.byteLength(z,"utf8")>15360)throw Error("oversized reading");let X=JSON.parse(z);if(!m4(X)||"credentialId"in X||"vouched"in X||typeof X.observedAtMs!=="number"||!Number.isFinite(X.observedAtMs))throw Error("invalid reading");if(X.observedAtMs<=(this.#Z.get($)??-1/0)){this.#z++;return}if(this.#$.has($))this.#z++;if(this.#Z.set($,X.observedAtMs),this.#$.set($,X),!this.#J&&!this.#Y)this.#J=this.options.setTimeout(()=>{this.#J=void 0,this.#q()},1000),this.#J.unref?.()}catch{this.#z++}}forget($){if(this.#$.delete($))this.#z++;this.#Z.delete($)}#q(){if(this.#Y||!this.#$.size||this.#X)return this.#Y;let $=Promise.resolve().then(async()=>{while(!this.#X&&this.#$.size){let Z=this.#$.entries().next().value;if(!Z)break;let[z,X]=Z;this.#$.delete(z);try{let Y=await this.options.token();if(this.#X||!this.options.owns(z)){if(!this.#X)this.#z++;continue}await this.options.client.reportUsageScoped?.({credentialId:z,reading:X,enrollmentToken:Y})}catch(Y){if(!this.#X)this.#z++;this.#G(Y)}}});return this.#Y=$,$.finally(()=>{this.#Y=void 0}),$}#G($){let Z="transport_error";try{if($ instanceof p9)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#B.has(Z))return;this.#B.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#K=!0,this.#J)this.options.clearTimeout(this.#J);return this.#J=void 0,this.#q()}drop(){this.#X=!0,this.#z+=this.#$.size+(this.#Y?1:0),this.#Y=void 0,this.#$.clear(),this.#Z.clear()}}function p4($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function d9($,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 g3=C("claustrum");function g4($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new F("invalid-token","Invalid Claustrum enrollment token");return $.token}var Y0=l9("common-auth.claustrum.phases");function l3($,Z,z,X=g3){let Y=p4(Z,z);return X.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:d9(Z,z)}),Y}var p3=300000,l4=60000;function v3(){return new F("invalid-material","Claustrum returned invalid credential material")}function c9($){let Z=$.trim();if(Z.startsWith("{")){let z;try{z=JSON.parse(Z)}catch{throw v3()}if(!z||typeof z!=="object")throw v3();let X=z,Y=X.access_token??X.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(r0))throw v3();return Z}function u9($,Z){let z={kind:"not-mine"};if(!$.operations.includes("read"))return z;if(!$.categories.includes(Z.category))return z;if("classify"in Z){let X=i9($),Y;switch(X.authMethod){case"apikey":Y="api_key";break;case"chatgpt":case"antigravity":case"oauth":Y="oauth";break;default:return{kind:"refused",code:"unknown-auth-method"}}let G={credentialId:$.id,credentialType:Y,categories:$.categories,refreshAdapter:$.refreshAdapter,...X};if(G.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let J=Z.classify(G);if(J.kind==="not-mine")return z;if(J.kind==="mine"&&typeof J.member==="string")return{kind:"mine",type:Y,member:J.member};if(J.kind==="refused"&&typeof J.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(J.code)&&!J.code.includes(`
|
|
90
|
+
`)&&Z.refusalCodes.includes(J.code))return{kind:"refused",code:J.code}}catch{}return{kind:"refused",code:"unclassified"}}if($.credentialType!=="oauth"&&$.credentialType!=="api_key")return z;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?{kind:"mine",type:"oauth"}:z;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?{kind:"mine",type:"api_key"}:z;return z}function i9($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function s9($){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 y0{#$;#Z;#B;#J;#Y;#K;#X;#z=new WeakMap;#q=new WeakMap;#G=new Map;#H=new WeakMap;#U;#V=new Map;#Q;#F;#M=!1;#x=new R;#j;#L=!1;#W=-1/0;#N=2000;#R=!1;#D;#O=new Set;#P=new Set;#T;#I;#_;constructor($){if(S()&&$.client&&!W4($.client))throw new R;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>X0(Z);else if(S())this.#Z=async()=>{throw new F("not-enrolled","Claustrum enrollment token path is required")};else throw new F("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client??_0($.pluginId),this.#J=$.family,this.#Y=$.parseIdentity,this.#K=$.requireAssertion??!1,this.#B=$.now??Date.now,this.#X=$.logger??g3,this.#T=f0(this.#X),this.#Q=$.setTimeoutImpl??setTimeout,this.#F=$.clearTimeoutImpl??clearTimeout,this.#U=new m3({client:this.#$,owns:(z)=>this.#V.has(z),token:async()=>S()?"":g4(await this.#Z()),logger:this.#X,setTimeout:this.#Q,clearTimeout:this.#F})}transportLost($){if(this.#R||this.#M)return;this.#M=!0,this.#x=$ instanceof v4?$:new R,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#A()}reachable(){if(this.#R||!this.#M)return;if(this.#M=!1,this.#j)this.#F(this.#j);this.#j=void 0,this.#N=2000;for(let $ of this.#G.values())$.since=null;(this.#X.info??g3.info)("vault receipt serving resumed",{reason:"reachable"})}#A(){if(this.#R||!this.#M||this.#j||this.#L)return;this.#j=this.#Q(()=>{this.#j=void 0,this.#C(!0)},this.#N),this.#j.unref?.()}#C($=!1){if(this.#R||!this.#M||this.#L)return;if(this.#B()-this.#W<1000){this.#A();return}this.#W=this.#B(),this.#L=!0,this.#f().catch(()=>{if($&&this.#M)this.#N=Math.min(this.#N*2,30000)}).finally(()=>{this.#L=!1,this.#A()})}#S($){if(this.#R)throw new F("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#S($),S())return"";if(Y0.hasSubscribers)Y0.publish({logger:this.#X,phase:"token read begin"});let Z=this.#Z();this.#P.add(Z);let z;try{z=await Z}finally{if(this.#P.delete(Z),Y0.hasSubscribers)Y0.publish({logger:this.#X,phase:"token read end"})}return this.#S($),g4(z)}async#k($,Z){this.#S(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.#S(Z),p(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof v4)throw Y;if(p(Y)==="unreachable")throw new R;throw new F("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#S(Z),this.reachable(),z}async discover($){let Z=await this.#f($);return this.#D=Z.view,Z}async#f($){let Z,z;try{z=await this.#y($)}catch(H){throw this.#G.clear(),this.#w(),H}if(Y0.hasSubscribers)Y0.publish({logger:this.#X,phase:"list scoped begin"});try{Z=await this.#k(()=>this.#$.listScoped(z),$)}catch(H){throw this.listFailed(H),H}finally{if(Y0.hasSubscribers)Y0.publish({logger:this.#X,phase:"list scoped end"})}let X=[],Y=[],G=0,J=[],B=new Map;for(let H of Z.rows){let W=u9(H,this.#J);if(W.kind==="not-mine"){G++;continue}if(W.kind==="refused"){Y.push({...H.id.trim()&&{credentialId:H.id},code:W.code});continue}J.push({row:H,type:W.type,...W.member!==void 0&&{member:W.member}}),B.set(H.id,(B.get(H.id)??0)+1)}let K=[];for(let{row:H,type:W,member:V}of J){let D;if(!H.id.trim())D="empty credential id";else if((B.get(H.id)??0)>1)D="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())D="blank account identity";else if(!H.state.trim())D="empty state";if(D){X.push({...H.id.trim()&&{credentialId:H.id},...V!==void 0&&{member:V},reason:D});continue}K.push(Object.freeze({credentialId:H.id,credentialType:W,...V!==void 0&&{member:V},...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.#X.warn("skipped malformed vault record",H);let Q=s9(Z);return{view:Z.view,credentials:Object.freeze(K),skipped:Object.freeze(X),..."classify"in this.#J&&{refused:Object.freeze(Y),notMine:G},...Q&&{grantReach:Q}}}listFailed($){if(p($)==="unreachable")this.transportLost($);else this.reachable(),this.#G.clear(),this.#w()}forget($){this.#G.delete($),this.#V.delete($),this.#U.forget($)}#w(){for(let $ of this.#V.keys())this.#U.forget($);this.#V.clear()}retain($){let Z=new Map($.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#G){let Y=Z.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}for(let[z,X]of this.#V){let Y=Z.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.credentialType||Y.accountIdentity!==X.accountIdentity)this.forget(z)}}keptReceiptState(){let $=null;for(let[Z,z]of this.#G){if(!this.#b(z.attempt)){this.forget(Z);continue}if(z.since!==null)$=Math.min($??z.since,z.since)}return Object.freeze({active:$!==null,since:$})}#b($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#B()>l4}async authorize($,Z,z="vault"){this.#S(Z);let{credentialId:X,credentialType:Y,accountIdentity:G}=$,J=this.#G.get(X);if(J&&(J.attempt.credentialType!==Y||J.attempt.expectedAccountIdentity!==G))this.forget(X),J=void 0;let B;try{B=await this.#y(Z)}catch(K){throw this.#G.clear(),this.#w(),K}if(this.#M&&J)return this.#C(),this.#h(X,J,B,z);try{let K=await this.#E({credentialId:X,credentialType:Y,accountIdentity:G},B,Z);return this.#G.set(X,{attempt:K,routeId:z,since:null}),this.#V.set(X,{...$}),K}catch(K){if(this.#S(Z),p(K)!=="unreachable")throw this.forget(X),K;return this.#h(X,J,B,z,K)}}#h($,Z,z,X,Y=this.#x){if(!Z||this.#G.get($)!==Z||!this.#b(Z.attempt))throw this.forget($),Y;if(Z.since===null)Z.since=this.#B();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#z.set(G,this.#z.get(Z.attempt)??{token:z,client:this.#$}),this.#H.set(G,X),G}async#E($,Z,z){if(!$.credentialId)throw new F("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:G}=$;if(this.#K&&G===void 0)throw new F("identity-unasserted","Claustrum dispatch requires a known account identity");let J=await this.#k(()=>this.#$.getScoped({credentialId:X,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:p3}}),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.#B()<p3))throw new F("insufficient-validity","Claustrum served credential has insufficient validity");let K=c9(J.material),Q=J.accountId?.trim()?J.accountId:void 0;if(this.#K&&(J.credentialId===void 0||Q===void 0))throw new F("identity-unasserted","Claustrum served credential did not assert its identity");let H=Q===void 0?this.#Y?.(K):void 0,W=Q??H;if(G!==void 0&&W!==void 0&&W!==G)throw new F("identity-changed","Claustrum served credential identity changed");let V=W??G,U=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...V!==void 0&&{accountIdentity:V},accountIdentitySource:Q!==void 0?"asserted":H!==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:K,enumerable:!1}));return this.#z.set(U,{token:Z,client:this.#$}),U}async reportFailure($,Z,z){if(Z!==401)return;this.#S();let X=this.#z.get($);if(!X)throw new F("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#H.get($);if(Y!==void 0){this.forget($.credentialId),this.#X.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let G=this.#G.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let J=this.#q.get($);if(J)return J;let B=this.#k(()=>X.client.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:X.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:z}));this.#q.set($,B);try{await B,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:z})}catch(K){throw this.#q.delete($),K}}watchRoster($){this.#S();let Z=new T$({client:this.#$,enrollmentToken:()=>this.#y(),view:$.view??(()=>this.#D),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.#X,now:this.#B,setTimeoutImpl:this.#Q,clearTimeoutImpl:this.#F});return this.#O.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#O.delete(Z),Z.stop()}}}reportUsage($){if(this.#R)return;try{this.#U.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#U.state()}close(){if(this.#R)return;if(this.#R=!0,this.#j)this.#F(this.#j);this.#j=void 0;for(let Z of this.#O)Z.stop();this.#O.clear(),this.#G.clear();let $=this.#U.close();if($)this.#P.add($),$.then(()=>this.#P.delete($));else this.#$.close();this.#_=b0(this.#P,(Z)=>(this.#I??this.#T)(Z)).finally(()=>{if(this.#U.drop(),this.#V.clear(),$)this.#$.close()})}async dispose($=this.#T){this.#I=$,this.close(),await this.#_}}import{resolve as m$}from"node:path";var d4=30000,c4={now:()=>performance.now(),schedule($,Z){let z=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(z),unref:()=>z.unref?.()}}};function u4($,Z=""){let z=new Map,{observation:X}=$,Y=(B,K,Q)=>z.set(`${Z}:${B}`,{at:K,order:0,publication:{...$,observation:Q}}),G=(B,K)=>JSON.stringify([B??"all",K]),J=new Set;for(let B of X.readings??[]){let K=G(B.scope,B.label);J.add(K),Y(K,X.checkedAt,{checkedAt:X.checkedAt,readings:[{...B}]})}for(let B of X.coverage??[]){let K=G(B.scope,B.label);if(!J.has(K))Y(K,X.checkedAt,{checkedAt:X.checkedAt,coverage:[{...B}]})}if(X.budget)Y("budget",X.checkedAt,{checkedAt:X.checkedAt,budget:{...X.budget}});for(let[B,K]of Object.entries(X.counters??{}))Y(`counter:${B}`,K.checkedAt,{checkedAt:X.checkedAt,counters:{[B]:{...K}}});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 a9}from"node:crypto";import{stat as n9}from"node:fs/promises";import{resolve as t0}from"node:path";function i4($,Z,z){if($.accountIdentity!==void 0&&z!==void 0)return $.accountIdentity===z;return $.credentialId===Z}function d3($,Z,z){return $.some((X)=>i4(X,Z,z))}function c3($,Z,z){let X={credentialId:Z,...z!==void 0&&{accountIdentity:z}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==z),X]}function u3($,Z,z){return $.filter((X)=>!Z.some((Y)=>i4(X,Y,z)))}function s3($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>l(Z).map((z)=>({credentialId:z,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function o9($,Z){let z=l(Z),X=Z.accountIdentity===void 0?-1:$.order.findIndex((G)=>G.accountIdentity===Z.accountIdentity),Y=X>=0?X:$.order.findIndex((G)=>z.includes(G.credentialId));return Y>=0?Y:1/0}var h$="vault:";function r9($){return a9("sha256").update($).digest("hex")}function t9($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function e9($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function l($){return[$.credentialId,...$.aliases??[]]}function n4($,Z,z={}){let X=z.now??Date.now(),Y=z.routePrefix??h$,G=z.reservedRouteIds??new Set,J=$?.rows??[],B=$?void 0:z.seed,K=[...$?.declined??B?.declined??[]],Q=Z.skipped.length===0,H=new Set(Z.credentials.map((q)=>q.credentialId)),W=new Set(Z.skipped.flatMap((q)=>q.credentialId===void 0?[]:[q.credentialId])),V=Z.skipped.some((q)=>q.credentialId===void 0),D=(q)=>!H.has(q)&&(W.has(q)||V),U=new Map;for(let q of J){if(q.accountIdentity===void 0)continue;for(let O of l(q))if(!U.has(O))U.set(O,q.accountIdentity)}let _=new Map;for(let q of Z.credentials){let O=q.accountIdentity!==void 0?{credential:q,identity:q.accountIdentity,claimed:!0}:{credential:q,identity:U.get(q.credentialId),claimed:!1},o=e9(O),r=_.get(o)??[];r.push(O),_.set(o,r)}let M=new Set,L=new Set(G),x=[],f=(q,O)=>q.credential.credentialId.localeCompare(O.credential.credentialId),m=[..._.values()].map((q)=>q.toSorted(f)).sort((q,O)=>q[0]&&O[0]?f(q[0],O[0]):0);for(let q of m){let O=q[0]?.identity,o=q.filter((j)=>j.credential.state==="active"),r=o.length?o:q,r$=r.filter((j)=>j.claimed),W$=r$.length?r$:r,t$=new Set(q.map((j)=>j.credential.credentialId)),NZ=J.find((j)=>!M.has(j)&&l(j).some((S0)=>t$.has(S0))&&(j.accountIdentity===void 0||j.accountIdentity===O)),e$=W$.find((j)=>j.credential.credentialId===NZ?.credentialId)??W$[0];if(!e$)continue;let b=e$.credential,v=NZ??(O===void 0?void 0:J.find((j)=>!M.has(j)&&j.accountIdentity===O));if(v)M.add(v);let K0=v?.routeId;if(!K0||G.has(K0)){let j=`${Y}${b.credentialId}${O===void 0?"":`~${r9(O).slice(0,10)}`}`;K0=j;for(let S0=2;L.has(K0);S0++)K0=`${j}~${S0}`}L.add(K0);let X8=v?l(v).filter(D):[],$3=[...new Set([...q.map((j)=>j.credential.credentialId),...X8])].filter((j)=>j!==b.credentialId).sort((j,S0)=>j.localeCompare(S0)),Y8=z.mapAccount?.(b)??{};x.push({previousIndex:v?J.indexOf(v):1/0,row:{routeId:K0,credentialId:b.credentialId,credentialType:b.credentialType,...O!==void 0&&{accountIdentity:O},...$3.length&&{aliases:$3},state:b.state,label:Y8.label?.trim()||t9(b),...b.email!==void 0&&{email:b.email},...b.orgName!==void 0&&{orgName:b.orgName},enabled:![b.credentialId,...$3].some((j)=>d3(K,j,O)),addedAt:v?.addedAt??X,...v?.quota!==void 0&&{quota:v.quota},...!e$.claimed&&O!==void 0&&{unclaimed:!0}}});let Z3=x.at(-1);if(B&&Z3)Z3.previousIndex=o9(B,Z3.row)}return J.forEach((q,O)=>{if(M.has(q)||!l(q).some(D))return;if(L.has(q.routeId))return;let[o,...r]=l(q).filter((t$)=>!H.has(t$));if(o===void 0)return;L.add(q.routeId);let{aliases:r$,...W$}=q;x.push({previousIndex:O,row:{...W$,credentialId:o,...r.length&&{aliases:r},stale:!0}})}),x.sort((q,O)=>q.previousIndex===O.previousIndex?q.row.credentialId.localeCompare(O.row.credentialId):q.previousIndex-O.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:Q,...!Q&&{rejected:Z.skipped.map((q)=>({...q.credentialId!==void 0&&{credentialId:q.credentialId},reason:q.reason}))},rows:x.map((q)=>q.row),declined:K}}function a3($){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 e0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function w0($){return $===void 0||typeof $==="string"}function $1($){let Z=e0($)?W0($.quota):void 0;if(!e0($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!w0($.accountIdentity)||!w0($.email)||!w0($.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 Z1=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function s4($){if(!Array.isArray($))return;let Z=[];for(let z of $){if(!e0(z)||!w0(z.credentialId)||typeof z.reason!=="string"||!Z1.has(z.reason))return;Z.push(z)}return Z}function o4($){if(!e0($)||$.version!==1||!w0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!s4($.rejected))throw new F("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let G=$1(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(!e0(Y)||typeof Y.credentialId!=="string"||!w0(Y.accountIdentity))throw new F("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=s4($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...X&&{rejected:X},...$.limits!==void 0&&{limits:$.limits},rows:Z,declined:z}}function n3($){return o4(JSON.parse(JSON.stringify($)))}var z1=new a0({followSymlinks:!0});async function T($){if(s)return i3($);let Z=await z1.read([$],([z=$])=>i3(z));return structuredClone(Z)}async function i3($){let Z;try{Z=await k$($,s)}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 o4(z)}var r4={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},t4={name:"claustrum-roster",ttlMs:30000};async function j0($,Z,z={}){return M3($,{...r4,signal:z.signal},async(X)=>{let Y=await i3($),{next:G,result:J}=await Z(Y,{assertOwned:()=>X.assertOwned()});if(G){await X.assertOwned();try{await u($,G,{beforeRename:async()=>{await z.beforePublish?.(),z.signal?.throwIfAborted(),await X.assertOwned()}})}catch(B){if(B&&typeof B==="object"&&"published"in B&&B.published===!0)z.onPublished?.();throw B}z.onPublished?.()}return J})}function o3($,Z){return j0($,(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=c3(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 r3($,Z){return j0($,(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:u3(z.declined,l(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function X1($){return new F("invalid-order",$)}function Y1($,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 t3($,Z,z={}){return j0($,(X)=>{let Y=X?.rows??[],G=Y1(Y,Z);if(G)throw X1(G);let J=new Map;for(let Q of Y){let H=J.get(Q.routeId);if(H)H.push(Q);else J.set(Q.routeId,[Q])}let B=[...Z],K=B.flatMap((Q)=>J.get(Q)??[]);if(!X||K.every((Q,H)=>Q===Y[H]))return{result:{ids:B,outcome:"unchanged"}};return{next:{...X,rows:K},result:{ids:B,outcome:"reordered"}}},{...z.signal&&{signal:z.signal}})}function J1($,Z){if(!l($).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")&&l($).length===1)return"bind";return"refuse"}async function e3($,Z){let{routeId:z,observation:X,...Y}=Z;return e4($,{routeId:z,observation:X,accountIdentity:Y.accountIdentity,receipt:Y})}async function e4($,Z){if(!A0(Z.observation))return!1;let z=k($,await T($));if(!J0(z,Z).kept)return!1;return Z6($,Z)}function $Z($,Z){return e4($,Z)}function J0($,Z){let z=$?.rows.find((J)=>J.routeId===Z.routeId),X=!z?"refuse":Z.receipt?J1(z,Z.receipt):z.accountIdentity!==void 0&&z.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!z||X==="refuse")return{roster:$,kept:!1};let Y=p0(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 w$=new Map;function $$($){w$.delete(t0($))}function $6($,Z){let z=t0($);if(Z instanceof F)return Z.kind==="roster-busy";if(Z instanceof M$||Z instanceof q3)return t0(Z.details.target)===z;if(Z instanceof d0){let X=t0(Z.path);return[r4.name,t4.name].some((Y)=>{let G=N3(z,Y);return X===G||X.startsWith(`${G}.`)})}return!1}var G1=4;async function a4($){try{let{dev:Z,ino:z,size:X,mtimeMs:Y}=await n9($);return{dev:Z,ino:z,size:X,mtimeMs:Y}}catch{return}}function B1($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function K1($,Z,z){for(let X=0;X<G1;X++){let Y=await a4($),G=await T($),J,B,K;try{({target:J,local:B}=Z(G));let Q=JSON.stringify(z(J));K=JSON.stringify(J)!==Q||B!==void 0&&JSON.stringify(B)!==Q}catch{return"commit"}if(!B1(Y,await a4($)))continue;if(K)return"commit";return z6($)?"commit":"unchanged"}return"commit"}async function Z$($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){$$($.path);return}let z=await w({...t4,path:$.path,renew:!0});if(!z){let J=await T($.path);if($.signal?.throwIfAborted(),!J?.view)throw new F("roster-busy","Claustrum account discovery is already in progress");return J}let X=t0($.path),Y=$.listedOver,G;try{let J=await T($.path),B=Y?void 0:w$.get(X);G=B&&(B.previousView===J?.view||B.inventory.view===J?.view)?B:{inventory:await $.custody.discover($.signal),previousView:J?.view},w$.delete(X);let{inventory:K}=G;$.onInventory?.(K),$.signal?.throwIfAborted();let Q=typeof $.projection==="function"?$.projection():$.projection,H=(D)=>n4(D,K,Q),W=async()=>{return $.signal?.throwIfAborted(),await z.assertOwned(),Z()};if(await K1($.path,(D)=>{if(Y)return{target:D};let U=k($.path,D);return{target:D,...U!==D&&{local:U}}},H)==="unchanged"){if(!await W())return;return await T($.path)}return await j0($.path,async(D)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await z.assertOwned(),Y&&D?.view!==Y.view&&D?.view!==K.view)return{result:D};let U=H(D);return{...JSON.stringify(D)!==JSON.stringify(U)&&{next:U},result:U}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await z.assertOwned()}})}catch(J){if(J instanceof M$&&G&&!Y&&!$.signal?.aborted&&await Z())w$.set(X,G);throw J}finally{await z.release($.signal)}}var L0=new Map,H1=C("claustrum"),Y6=100;function J6($,Z=c4){let z=m$($),X=L0.get(z);if(!X)X={path:z,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},L0.set(z,X);return X}function G6($,Z,z){let X=J6($,z);X.listeners.add(Z);let Y;return()=>Y??=(()=>{return X.listeners.delete(Z),X.listeners.size?Promise.resolve():ZZ($)})()}function W1($){return u4($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function Z6($,Z){if(!A0(Z.observation))return Promise.resolve(!1);let z=J6($),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 W1(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 K6(z,Y6),Promise.resolve(!0)}function B6($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,z)=>Z.order-z.order)}function k($,Z){let z=L0.get(m$($));if(z)for(let X of B6(z.pending)){if(X.priorReading)Z=J0(Z,X.priorReading).roster;Z=J0(Z,X.publication).roster}return Z}function z6($){return!!L0.get(m$($))?.pending.size}function K6($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let z=$.draining?0:($.committedAt??-1/0)+d4-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,z),()=>{return $.timer=void 0,H6($)}),!$.draining)$.timer.unref?.()}function X6($){$.timer?.cancel(),$.timer=void 0}function H6($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([z,X])=>[z,new Map(X)]));return $.running=(async()=>{try{if(await j0($.path,(X)=>{let Y=X;for(let J of B6(Z)){if(J.priorReading)Y=J0(Y,J.priorReading).roster;Y=J0(Y,J.publication).roster}let G=JSON.stringify(Y)!==JSON.stringify(X);return{...G&&{next:Y},result:G}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[X,Y]of Z){let G=$.pending.get(X);for(let[J,B]of Y)if(G?.get(J)===B)G.delete(J);if(!G?.size)$.pending.delete(X)}$.failures=0}catch(z){if(!$.abort.signal.aborted&&$.failures++===0)H1.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()):Y6;K6($,z)}})(),$.running}async function ZZ($,Z=1000){let z=m$($),X=L0.get(z);if(!X)return;X.draining=!0,X6(X);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)H6(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(),X6(X),X.pending.clear(),L0.get(z)===X)L0.delete(z)}}}var v$=1e4;function W6(){return new R}var zZ;function U6($,Z){if(!zZ)throw Error("ClaustrumConsumer is not initialized");return zZ($,Z)}function Q6(){return new F("not-active","Claustrum scoped custody is not active")}class XZ{#$;#Z=new AbortController;#B;#J;#Y;#K;#X;#z;#q;#G;#H=!1;#U=new Set;#V;#Q;#F;#M;#x=new Map;#j;#L;#W;#N;#R=new WeakMap;static{zZ=($,Z)=>{let z=new XZ(Z);return z.#W=$,{consumer:z,hooks:z.#w()}}}constructor($){this.#$=$,this.#B=$.logger??C("claustrum"),this.#J=f0(this.#B,this.#Z.signal),this.#L=G6($.rosterPath,(Z)=>{this.#z=J0(this.#z,Z).roster})}#D($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#O($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}async#P(){if(S())return!0;return await this.#$.isCustodyActive?.()??!0}#T($,Z){let z=q0([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#I(){if(this.#D(),this.#Y)return this.#Y;if(!this.#K){let $={timedOut:!1};this.#K=this.#_($),this.#O(this.#K)}return this.#T(this.#K)}#_($){let Z=this.#$.setTimeoutImpl??setTimeout,z=this.#$.clearTimeoutImpl??clearTimeout,X=(!S()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>_0(this.#$.pluginId))).then((J)=>{if(this.#Z.signal.aborted||$.timedOut){if(J.close(),!$.timedOut)this.#D();throw W6()}if(this.#Y=new y0({client:J,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#B,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&J.insula)this.#Q=T3(J.insula,this.#$.tokenPath);return this.#Y}),Y,G=new Promise((J,B)=>{Y=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#B.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#A()}),B(W6())},this.#A()),Y.unref?.()});return Promise.race([X,G]).finally(()=>{if(Y)z(Y);this.#K=void 0})}#A(){return this.#$.connectTimeoutMs??v$}snapshot(){return this.#z}grantReach(){if(this.#W)return this.#W.grantReach(this.#z?.view);let $=this.#q;return $&&this.#z?.view===$.view?$.reach:void 0}watchState(){if(this.#W)return Object.freeze({vault:this.#W.watchMode()});return Object.freeze({vault:this.#F?.mode??"polling",...this.#$.insula&&{insula:this.#Q?.source.watchMode()??"polling"}})}#C(){this.#F?.close(),this.#F=void 0,this.#M?.(),this.#M=void 0}keptReceiptState(){if(this.#W){let $=this.#N;return $&&this.#W.leaseLive($)?$.custody.keptReceiptState():this.#W.keptReceiptState()}return this.#Y?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return a3(this.#z)}refresh(){if(this.#D(),this.#W)return this.#O(this.#b(this.#W));if(this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#P()){if(this.#z=void 0,this.#q=void 0,this.#C(),this.#Y)this.#Y.close(),this.#O(this.#Y.dispose(this.#J));this.#Y=void 0,this.#Q?.release(),this.#Q=void 0;return}let $=await this.#I(),Z,z=await Z$({path:this.#$.rosterPath,custody:$,onInventory:(Y)=>{Z=Y},isActive:()=>this.#P(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#D();let X=z?.view!==this.#z?.view;if(this.#z=k(this.#$.rosterPath,z),$.retain(z?.rows??[]),Z&&z?.view!==void 0)this.#q=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.#X=void 0}),this.#O(this.#X),this.#S(this.#X),this.#X}#S($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#H)return;if(this.#D(),this.#H=!0,this.#W){this.#W.start();return}let $=async()=>{try{if(await this.#y())await this.refresh();await this.refreshInsulaQuota(),this.#k()}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.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#G=void 0,this.#O($())},Z),this.#G.unref?.()};this.#O($())}async#y(){if(this.#F?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#j===void 0||$-this.#j>=C0)return!0;return!await this.#P()}#k(){let $=this.#Y;if(this.#Z.signal.aborted||!$)return;if(this.#F??=$.watchRoster({view:()=>this.#z?.view,onView:()=>this.#O((async()=>{while(this.#X)await this.#X.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#Q&&!this.#M)this.#M=this.#Q.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#P())return;try{if(!S())await X0(this.#$.tokenPath);await this.#I(),await this.#Q?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#P())return;try{if(!S())await X0(this.#$.tokenPath);return this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#P())return;try{if(!S())await X0(this.#$.tokenPath);let z=k(this.#$.rosterPath,await T(this.#$.rosterPath))?.rows.find((X)=>X.routeId===$);return this.#f(z?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#P())return{miss:"unreachable"};try{if(!S())await X0(this.#$.tokenPath);let X=k(this.#$.rosterPath,await T(this.#$.rosterPath))?.rows.find((J)=>J.routeId===$)?.accountIdentity;if(!X||!this.#Q)return{miss:"unreachable"};let Y=this.#Q.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.#x.get($)!==z.miss)this.#x.set($,z.miss),this.#B.warn("skipped insula provider poll",{reason:z.miss});return}return this.#x.delete($),z.miss?Z():z.reading}#f($){if(!this.#$.insula||!$)return;let Z=this.#Q?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#W)return this.#m(this.#W,$,Z);this.#D(Z);let z=this.#z??await this.#T(this.refresh(),Z);if(!z||!await this.#P())throw this.#Y?.close(),this.#Y=void 0,this.#C(),this.#Q?.release(),this.#Q=void 0,new F("not-active","Claustrum scoped custody is not active");let X=k(this.#$.rosterPath,await T(this.#$.rosterPath));this.#D(Z);let Y=z.rows.find((K)=>K.routeId===$),G=X?.rows.find((K)=>K.routeId===$);if(G&&!G.enabled){if(Y)this.#Y?.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.#Y?.forget(Y.credentialId);throw new F("route-unavailable","Claustrum route is disabled, removed or changed")}let J=await this.#T(this.#I(),Z),B=q0([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()}}#w(){return{discovery:($)=>{let Z=this.#W;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let z=this.#O($.then((X)=>this.#h(Z,X)));this.#S(z)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#z?.view;if(this.#z=k(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(z){this.#$.onError?.(z)}},reset:()=>{this.#z=void 0},roster:()=>this.#z,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()}),onError:($)=>{if(!this.#Z.signal.aborted)this.#$.onError?.($)}}}async#b($){let Z=await $.refresh();return this.#h($,Z)}#h($,Z){if(this.#D(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#z}#E($){if($&&this.#N!==$)return;this.#N?.release(),this.#N=void 0}async#p($,Z){let z=this.#N;if(z&&$.leaseLive(z))return z;this.#E();let X=await $.acquire(Z);if(this.#Z.signal.aborted)X.release(),this.#D();let Y=this.#N;if(Y&&$.leaseLive(Y))return X.release(),Y;return this.#N=X,X}async#m($,Z,z){if(this.#D(z),!this.#z)await this.#T($.refresh(),z);let X=this.#z;if(!await $.readAuthority())throw this.#E(),Q6();if(this.#D(z),!X)throw new F("route-unavailable","Claustrum has no roster for this provider yet");let Y=k(this.#$.rosterPath,await T(this.#$.rosterPath));this.#D(z);let G=X.rows.find((Q)=>Q.routeId===Z),J=Y?.rows.find((Q)=>Q.routeId===Z);if(J&&!J.enabled){if(G)$.forget(G.credentialId);throw new F("route-declined","Claustrum route is disabled")}if(!G||!J||J.state!=="active"||J.credentialId!==G.credentialId||J.accountIdentity!==G.accountIdentity||J.credentialType!==G.credentialType){if(G)$.forget(G.credentialId);throw new F("route-unavailable","Claustrum route is disabled, removed or changed")}let B={credentialId:J.credentialId,credentialType:J.credentialType,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity}},K=q0([this.#Z.signal,...z?[z]:[]]);try{for(let Q=0;;Q++){let H=await this.#p($,K.signal);try{let W=await H.custody.authorize(B,K.signal,Z);return this.#R.set(W,H),W}catch(W){if(Q>0||K.signal.aborted||$.leaseLive(H)||!(W instanceof F)||W.kind!=="closed")throw W;if(this.#E(H),!await $.readAuthority())throw Q6()}}}finally{K.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#z?.rows.find((z)=>z.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#W){if(this.#N&&this.#W.leaseLive(this.#N))this.#N.custody.reportUsage($)}else this.#Y?.reportUsage($)}catch{}}usageReportState(){try{return(this.#W?this.#N?.custody:this.#Y)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,z){if(this.#D(),this.#W){let X=this.#R.get($);if(!X)throw new F("no-receipt","Claustrum dispatch receipt has no active owner");await X.custody.reportFailure($,Z,z);return}if(!this.#Y)throw new F("no-receipt","Claustrum dispatch receipt has no active owner");await this.#Y.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(l3(z.site,Y,J,this.#B))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($){if(this.#D(),await o3(this.#$.rosterPath,$),this.#z=k(this.#$.rosterPath,await T(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z);if(this.#W)this.#W.retainUnion();else this.#Y?.retain(this.#z?.rows??[])}async accept($){if(this.#D(),await r3(this.#$.rosterPath,$),this.#z=k(this.#$.rosterPath,await T(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z)}async reorder($){this.#D();let Z=await t3(this.#$.rosterPath,$);if(this.#z=k(this.#$.rosterPath,await T(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z);return Z}async recordQuota($,Z,z){return this.#D(),e3(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.#D(),$Z(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.#G)(this.#$.clearTimeoutImpl??clearTimeout)(this.#G);if(this.#G=void 0,this.#C(),this.#Y)this.#Y.close(),this.#O(this.#Y.dispose(this.#J));this.#N?.release(),this.#N=void 0,this.#W?.detach(),this.#Q?.release(),this.#Q=void 0,this.#z=void 0,this.#q=void 0,this.#L(),$$(this.#$.rosterPath)}async dispose(){this.close(),this.#V??=Promise.all([b0(this.#U,this.#J),this.#L()]).then(()=>{}),await this.#V}}import{createHash as Q1}from"node:crypto";import{channel as U1}from"node:diagnostics_channel";import{readdir as D1,stat as V1}from"node:fs/promises";import{dirname as F1,join as h0,resolve as D6}from"node:path";var g$=new Map,N1=/^[a-z0-9][a-z0-9._-]{0,63}$/,q1=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,M1=/^[0-9a-f]{16}$/,V6=3;function JZ($,Z=new Set){if($===null)return"null";if(typeof $==="string"||typeof $==="boolean")return JSON.stringify($);if(typeof $==="number")return Number.isFinite($)?JSON.stringify($):void 0;if(typeof $!=="object"||Z.has($))return;let z=new Set(Z).add($),X=[];if(Array.isArray($)){for(let G=0;G<$.length;G++){let J=JZ($[G],z);if(J===void 0)return;X.push(J)}return`[${X.join(",")}]`}let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return;for(let G of Object.keys($).sort()){let J=JZ($[G],z);if(J===void 0)return;X.push(`${JSON.stringify(G)}:${J}`)}return`{${X.join(",")}}`}function _1($,Z){let z=JZ({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??h$,mapAccount:$.mapAccount?String($.mapAccount):null});if(z===void 0)throw new F("invalid-state","Claustrum hub classifierInput must be plain JSON");return Q1("sha256").update(z).digest("hex").slice(0,16)}function F6($,Z){if(typeof $!=="string"||!N1.test($)||q1.test($))throw new F("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function G0($="Claustrum custody lease is closed"){return new F("closed",$)}function YZ(){return new F("not-active","Claustrum scoped custody is not active")}function N6(){return new R}function O1($,Z){return new Promise((z,X)=>{let Y=()=>X(Z.reason);if(Z.addEventListener("abort",Y,{once:!0}),$.then((G)=>{Z.removeEventListener("abort",Y),z(G)},(G)=>{Z.removeEventListener("abort",Y),X(G)}),Z.aborted)Y()})}function q6($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class M6{#$;#Z;#B;#J=new AbortController;#Y=new Map;#K=new WeakMap;#X=0;#z;#q;#G;#H;#U;#V;#Q=0;#F;#M;#x;#j=!1;#L=new Set;#W;#N;#R;constructor($){if(!$.family||!("classify"in $.family))throw new F("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=F6($.hostGeneration,"host generation"),z=$.members.map((Y)=>F6(Y,"member"));if(new Set(z).size!==z.length)throw new F("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??C("claustrum"),this.#B=f0(this.#Z,this.#J.signal),this.#N=h0($.stateDir,"rosters",Z),this.#R=_1($,z);let X=h0(this.#N,this.#R);for(let Y of z)this.#Y.set(Y,{provider:Y,path:h0(X,`${Y}.json`),closed:!1})}#D($){return this.#L.add($),$.then(()=>this.#L.delete($),()=>this.#L.delete($)),$}#O(){if(this.#J.signal.aborted)throw G0("Claustrum discovery hub is closed")}#P($){let Z=this.#Y.get($);if(!Z)throw new F("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#P($).path}member($,Z){this.#O();let z=this.#P($);if(z.hooks)throw new F("wrong-consumer","Claustrum hub member was already built");for(let W of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(W in Z)throw new F("wrong-consumer",`Claustrum hub members cannot take ${W}`);let X={provider:z.provider,start:()=>this.start(),refresh:()=>this.#m(),readAuthority:()=>this.#b(),acquire:(W)=>this.acquire(W),leaseLive:(W)=>this.#A(W),grantReach:(W)=>W!==void 0&&this.#F?.view===W?this.#F.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#g(),publishRoster:(W)=>this.#T(z,W),forget:(W)=>this.#z?.custody?.forget(W),detach:()=>{z.closed=!0,z.releaseRoster?.()}},Y={rosterPath:z.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:G,hooks:J}=U6(X,Y);z.hooks=J;let B=D6(z.path),K=g$.get(B)??new Set,Q=(W)=>{if(z.closed||this.#V!==!0||!this.#z||!this.#_(this.#z)||!J.roster()||this.#l(J,W))return;if(z.seen=JSON.stringify(n3(W)),J.install(W),W.view!==this.#F?.view)z.pending??={failures:0,wait:0};this.#g()};K.add(Q),z.receiveRoster=Q,g$.set(B,K);let H=!0;return z.releaseRoster=()=>{if(!H)return;if(H=!1,K.delete(Q),!K.size)g$.delete(B)},G}#T($,Z){let z=this.#z;if($.closed||!z||!this.#_(z))return;$.seen=JSON.stringify(n3(Z)),$.hooks?.install(Z);for(let X of g$.get(D6($.path))??[]){if(!this.#_(z))return;if(X!==$.receiveRoster)X(Z)}}#I(){let $={id:++this.#X,count:0,ended:!1,controller:new AbortController};return this.#z=$,$}#_($){return!$.ended&&this.#z===$&&!this.#J.signal.aborted}#A($){let Z=this.#K.get($);return!!Z&&!Z.released&&!Z.generation.ended}#C($,Z=G0()){if($.ended)return;if($.ended=!0,$.count=0,this.#z===$)this.#z=void 0;if(this.#G&&this.#K.get(this.#G)?.generation===$)this.#G=void 0;if(this.#H?.generation===$)this.#H.watch.close(),this.#H=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#D($.custody.dispose(this.#B))}#S($){if($.ended)return;if($.count--,$.count<=0)this.#C($)}#y($){let Z=this.#q;if(Z?.generation===$&&Z.promise)return Z.promise;let z={generation:$,timedOut:!1},X=this.#$.connectTimeoutMs??v$,Y,G=(!S()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>_0(this.#$.pluginId))).then((K)=>{if(z.timedOut)throw K.close(),N6();if(!this.#_($)||$.count<=0)throw K.close(),G0("Claustrum connection is no longer wanted");return $.custody=new y0({client:K,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),J=new Promise((K,Q)=>{Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(z.timedOut=!0,!this.#_($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:X}),Q(N6())},X),Y.unref?.()});return z.promise=this.#D(Promise.race([G,J]).finally(()=>{if(Y)(this.#$.clearTimeoutImpl??clearTimeout)(Y)})),z.promise.finally(()=>{if(this.#q===z)this.#q=void 0}).catch(()=>{}),this.#q=z,z.promise}acquire($){try{if(this.#O(),$?.throwIfAborted(),this.#V===!1)throw YZ()}catch(z){return Promise.reject(z)}let Z=this.#z??this.#I();return Z.count++,this.#k(Z,$,!0)}async#k($,Z,z){let X=$.custody;if(!X){let Y=q0([$.controller.signal,...Z?[Z]:[]]);try{X=await O1(this.#y($),Y.signal)}catch(G){if(!$.ended)throw this.#S($),G;return this.#f(Z,z)}finally{Y.dispose()}}if($.ended)return this.#f(Z,z);if(Z?.aborted)throw this.#S($),Z.reason;return this.#w($,X)}#f($,Z){if($?.throwIfAborted(),this.#O(),this.#V===!1)throw YZ();if(!Z)throw G0();let z=this.#z??this.#I();return z.count++,this.#k(z,$,!1)}#w($,Z){let z={generation:$,custody:Z,released:!1},X=()=>{if(z.released||$.ended)throw G0()},Y=Object.freeze({authorize:async(J,B,K)=>{X();let Q=q0([$.controller.signal,...B?[B]:[]]);try{return await Z.authorize(J,Q.signal,K)}finally{Q.dispose()}},reportFailure:async(J,B,K)=>{return X(),Z.reportFailure(J,B,K)},reportUsage:(J)=>{if(!z.released&&!$.ended)Z.reportUsage(J)},usageReportState:()=>{return X(),Z.usageReportState()},forget:(J)=>{X(),Z.forget(J)},keptReceiptState:()=>{return X(),Z.keptReceiptState()}}),G=Object.freeze({custody:Y,generation:$.id,release:()=>{if(z.released)return;z.released=!0,this.#S($)}});return this.#K.set(G,z),G}leaseState(){let $=this.#z;return Object.freeze({generation:$?.id,count:$?.count??0})}async#b(){let $=S()||(await this.#$.isCustodyActive?.()??!0);if(this.#J.signal.aborted)return!1;let Z=this.#V;if(this.#V=$,!$&&Z!==!1)this.#h();return $}#h(){this.#Q++;let $=this.#z;if($)this.#C($,YZ());this.#G=void 0,this.#H?.watch.close(),this.#H=void 0,this.#F=void 0,this.#M=void 0;for(let Z of this.#Y.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),$$(Z.path)}#E(){return[...this.#Y.values()].filter(($)=>$.hooks&&!$.closed)}async#p(){let $=this.#G,Z=$&&this.#K.get($);if($&&Z&&this.#A($))return Z;this.#G=void 0;let z=await this.acquire(this.#J.signal),X=this.#G&&this.#K.get(this.#G);if(this.#G&&X&&this.#A(this.#G))return z.release(),X;this.#G=z;let Y=this.#K.get(z);if(!Y)throw G0();return Y}#m(){try{this.#O()}catch(X){return Promise.reject(X)}let $=this.#U;if($&&!$.generation?.ended)return $.promise;let Z={},z=this.#D(this.#a(Z).finally(()=>{if(this.#U===Z)this.#U=void 0}));Z.promise=z,this.#U=Z;for(let X of this.#E())X.hooks?.discovery(z);return z}async#a($){if(!await this.#b())return;let Z=await this.#p(),z=Z.generation;if($.generation=z,!this.#_(z))return;let X=await this.#o().then(()=>{return},(H)=>H instanceof Error?H:Error(String(H))),Y=new Map(await Promise.all([...this.#Y.values()].map(async(H)=>[H,await T(H.path).then((W)=>W?{file:W}:{},(W)=>W instanceof Error?W:Error(String(W)))])));if(!this.#_(z))return;let G;try{G=await Z.custody.discover(z.controller.signal)}catch(H){if(!this.#_(z))return;for(let W of this.#Y.values())if(W.pending)this.#v(W);throw H}if(!this.#_(z))return;let J=this.#E(),B=await Promise.all(J.map((H)=>H.hooks&&!H.closed?this.#n(H,H.hooks,G,X??Y.get(H),z):void 0));if(!this.#_(z))return;let K=new Map,Q=!0;for(let[H,W]of J.entries()){let V=W.hooks,D=B[H];if(!V||!D)continue;if("error"in D){let{error:_}=D;if(Q=!1,this.#v(W),$6(W.path,_))this.#Z.debug("claustrum hub member commit refused",{member:W.provider});else K.set(W.provider,_);continue}let{roster:U}=D;if(!this.#_(z))return;if(U?.view!==G.view)Q=!1,this.#v(W);else W.pending=void 0;if(!U)continue;if(this.#l(V,U)){Q=!1,this.#v(W);continue}this.#T(W,U)}if(!this.#_(z))return;if(this.#g(),Q)this.#F=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#M=(this.#$.now??Date.now)(),{errors:K}}async#n($,Z,z,X,Y){let G={...z,credentials:z.credentials.filter((J)=>J.member===$.provider),skipped:z.skipped.filter((J)=>J.member===$.provider)};try{if(!X)throw G0("Claustrum hub member has no base view");if(X instanceof Error)throw X;let J;if(!X.file){let K=U1("common-auth.claustrum.phases");if(K.hasSubscribers)K.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{J=await this.#r($)}finally{if(K.hasSubscribers)K.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await Z$({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#_(Y)&&this.#V===!0,signal:Y.controller.signal,projection:()=>({...Z.projection(),...J&&{seed:J}}),listedOver:{view:X.file?.view}})}}catch(J){return{error:J}}}async#o(){for(let $ of[F1(this.#N),this.#N,h0(this.#N,this.#R)])await k0($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,z=[h0(this.#N,Z)];try{for(let Y of await D1(this.#N))if(Y!==this.#R&&M1.test(Y))z.push(h0(this.#N,Y,Z))}catch{}let X;for(let Y of z)try{let G=(await V1(Y)).mtimeMs,J=await T(Y);if(J&&(!X||G>X.modified))X={modified:G,roster:J}}catch{}return X&&s3(X.roster)}#l($,Z){let z=$.projection().reservedRouteIds;return!!z?.size&&Z.rows.some((X)=>z.has(X.routeId))}#v($){let Z=($.pending?.failures??0)+1,z=Math.max(1,this.#$.pollIntervalMs??5000),X=Math.max(1,Math.ceil(C0/z)),Y=Z<=V6?1:Math.min(2**(Z-V6),X);$.pending={failures:Z,wait:Y-1}}#g(){let $=this.#z?.custody;if(!$)return;$.retain(this.#E().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#Q;for(let Z of this.#E()){let z;try{z=await T(Z.path)}catch(B){Z.hooks?.onError(B);continue}if($!==this.#Q||this.#V!==!0)return;let X=Z.hooks;if(!z||!X||Z.closed)continue;let Y=JSON.stringify(z);if(Y===Z.seen)continue;let G=X.roster();if(!G||G.view!==z.view||this.#l(X,z)){Z.pending??={failures:0,wait:0};continue}let J=q6(G);if(Z.seen=Y,this.#T(Z,z),q6(X.roster())!==J)this.#g()}}#e(){let $=!1;for(let z of this.#Y.values()){if(!z.pending)continue;if(z.pending.wait<=0)$=!0;else z.pending.wait--}if(this.#H?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#M===void 0||Z-this.#M>=C0}#$0(){let $=this.#G,Z=$&&this.#K.get($);if(!$||!Z||!this.#A($)||this.#V!==!0)return;let z=Z.generation;if(!this.#_(z)||this.#H?.generation===z)return;let X=Z.custody.watchRoster({view:()=>this.#F?.view,onView:()=>this.#D((async()=>{while(this.#U)await this.#U.promise.catch(()=>{});if(!this.#_(z))return;await this.#i()})()),onRefused:(Y)=>this.#c(Y),onError:(Y)=>this.#d(Y)});this.#H={generation:z,watch:X}}#d($){if(!this.#J.signal.aborted)this.#$.onError?.($)}#c($){if(this.#J.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#E())Z.hooks?.onError($)}#u($){for(let[Z,z]of $?.errors??[])this.#Y.get(Z)?.hooks?.onError(z)}async#i(){let $;try{$=await this.#m()}catch(Z){this.#c(Z);return}this.#u($)}async#s(){try{if(await this.#b()){if(await this.#t(),this.#e())await this.#i();this.#$0()}}catch(Z){this.#d(Z)}if(this.#J.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#x=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#x=void 0,this.#D(this.#s())},$),this.#x.unref?.()}start(){if(this.#j)return;this.#O(),this.#j=!0,this.#D(this.#s())}async refresh(){this.#u(await this.#m())}refusals(){let $=this.#F;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#F?.reach}watchState(){let $=this.#H;return $&&this.#_($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#z?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#J.signal.aborted)return;this.#J.abort(G0("Claustrum discovery hub is closed"));for(let Z of this.#Y.values())Z.releaseRoster?.();if(this.#x)(this.#$.clearTimeoutImpl??clearTimeout)(this.#x);this.#x=void 0;let $=this.#z;if($)this.#C($);this.#G=void 0,this.#H?.watch.close(),this.#H=void 0}async dispose(){this.close(),this.#W??=b0(this.#L,this.#B),await this.#W}}var L1=1e4;async function kz($){let{connectTimeoutMs:Z,...z}=$,X=Z??L1,Y=j1.connect(z),G=!1,J,B=new Promise((K,Q)=>{J=setTimeout(()=>{G=!0,Q(new R)},X),J.unref?.()});try{let K=await Promise.race([Y,B]);return Object.assign(K,{insula:B4($)})}catch(K){throw Y.then((Q)=>Q.close(),()=>{}),K}finally{if(!G&&J)clearTimeout(J)}}var _6=b$("openai");function O6($){return y$($)}function P0($){if(!$||$.corrupt===!0)return!1;return O6($.refresh)}class z$ 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 p$($){if(O6($))throw new z$}var P1=C("quota"),GZ="primary",BZ="secondary",x1="app_EMoamEEZ73f0CkXaXp7hrann",R1="https://auth.openai.com";async function zX($){p$($.refreshToken);let Z=await $.fetchImpl(`${R1}/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:x1}).toString()});if(!Z.ok){let Y=j3(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 S1="https://chatgpt.com/backend-api/wham/usage";async function XX($){let Z=$.logger??P1,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await $.fetchImpl(S1,{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=j3(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:J})}let G=X4(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:j6(Y)}),Y}}import{createHash as T1}from"node:crypto";var A1=globalThis.setTimeout,E1=5;function X$($){let Z=$?.quota?.checkIntervalMinutes??E1;return Math.max(1,Z)*60000}function C1($){return $?.quota?.enabled!==!1}function l$($,Z){if(!$?.resetsAt)return!1;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z<=Z}function WX($,Z,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let G=Z===GZ?$?.primary:Z===BZ?$?.secondary:void 0,J=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(J)&&J>z)return J;return z+X}function I1($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function L6($,Z,z){if(!C1(Z))return z+X$(Z);let X=I1(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+X$(Z);Y.push(B)}if(!Y.length)return z+X$(Z);return Math.min(...Y)+60000}function k1($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function f1($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function h($){return T1("sha256").update($).digest("hex").slice(0,16)}class B0{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!==h($))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($)!==h(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!P6(Z.quota))return;if(this.mainTokenFp=h($),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&&!P6(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($,h(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=h($);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=B0.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(P0(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=h($);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=f1(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=k1($);if(!z)return;let X=Z?h(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:L6(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&&E0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=X$(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 E0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==h(Z))return!1}return E0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,h(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<B0.API_CALL_GAP_MS)await new Promise((Y)=>{let G=A1(Y,B0.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=h($);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 w({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=h($),this.main={quota:Y,refreshAfter:L6(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 w({name:B0.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+X$(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(B0.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(B0.isAuthError($))return;this.mainLastApiError=c0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(B0.isAuthError(z))return;let X=h(Z),Y=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,c0({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,X)}}function P6($){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 b1,randomUUID as y1}from"node:crypto";import{setTimeout as w1}from"node:timers/promises";import{readFile as n1}from"node:fs/promises";var x0=C("refresh"),B$=C("accounts"),h1=1e4,m1=15000,HZ=50;function a($){return $.type==="oauth"&&$.corrupt!==!0}function v1($){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 g1="floors-v1";function RX($){return $.costZeroing?.enabled!==!1}class c$ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var p1=[401,403,429],x6={primary:0,secondary:0},l1=!1,QZ={primary:5,secondary:10};function N($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var d1=new Set(["__proto__","constructor","prototype"]);function c1($){return $.length>0&&!d1.has($)}function u1($){return $ instanceof c$||N($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function d$($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():y1(),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 R6($){if(!N($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let z=Number($.nextRetryAt),X=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function i1($){if(!N($))return;let Z={};for(let Y of["primary","secondary"]){let G=$[Y];if(!N(G))continue;let J=Number(G.usedPercent),B=Number(G.remainingPercent),K=Number(G.checkedAt);if(!Number.isFinite(J)||!Number.isFinite(B)||!Number.isFinite(K))continue;let Q=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[Y]={usedPercent:J,remainingPercent:B,checkedAt:K,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(N(z)){let Y=Number(z.limit),G=Number(z.used),J=Number(z.remaining),B=Number(z.usedPercent),K=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(G)&&Number.isFinite(J)&&Number.isFinite(B)&&Number.isFinite(K)&&typeof z.reached==="boolean")Z.spendControl={limit:Y,used:G,remaining:J,usedPercent:B,remainingPercent:K,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=$.credits;if(N(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&(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 s1($){if(!N($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!v1(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...d$($),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{...d$($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...d$($),type:"oauth",corrupt:!0}}return{...d$($),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:R6($.lastRefreshError),lastQuotaRefreshError:R6($.lastQuotaRefreshError),quota:i1($.quota)}}function a1($){if(!N($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!c1(z)||!N(X))continue;let Y={};if(N(X.inFlight))Y.inFlight={...X.inFlight};if(N(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))Y.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...N(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))Y.cooldownUntil=X.cooldownUntil;if(Object.keys(Y).length>0)Z[z]=Y}return Object.keys(Z).length>0?Z:void 0}var S6=new Set;function b6($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(S6.has(Z))return;S6.add(Z),B$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function y6($){if(!N($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(s1).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let J of Z)if(N(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);b6(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:N($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:N($.refresh)?$.refresh:void 0,quota:N($.quota)?$.quota:void 0,reset:a1($.reset),dump:N($.dump)?$.dump:void 0,costZeroing:N($.costZeroing)?$.costZeroing:void 0,killswitch:N($.killswitch)?$.killswitch:void 0,logging:N($.logging)?$.logging:void 0,cachekeep:N($.cachekeep)?$.cachekeep:void 0,cacheKeep:N($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:z}}function w6($){if(!("claustrum"in $))return $;let{claustrum:Z,...z}=$;return z}async function n($){try{return{exists:!0,value:JSON.parse(await n1($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function d($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function o1($){let Z;try{Z=(await n($)).value}catch{return null}return FZ(Z)}function h6($,Z){if(!N($))return $;let z=N(Z)?Z:{},X=N(z.main)?z.main:void 0,Y=N(z.accounts)?z.accounts:{},G=N($.quota)?$.quota:{},J=N($.refresh)?$.refresh:{},B=X??G,K=X??J,H=J.mainRefreshLeaseId!==void 0?{id:J.mainRefreshLeaseId,until:J.mainRefreshLeaseUntil,tokenHash:J.mainRefreshLeaseTokenHash}:{id:K.refreshLeaseId,until:K.refreshLeaseUntil,tokenHash:K.refreshLeaseTokenHash},V=Array.isArray($.accounts)?$.accounts.map((D)=>{if(!N(D))return D;let U=typeof D.id==="string"&&N(Y[D.id])?Y[D.id]:{};return{...D,...U}}):void 0;return m6({...$,refresh:d({...J,mainLastRefreshError:J.mainLastRefreshError??K.lastRefreshError,mainRefreshLeaseId:H.id,mainRefreshLeaseUntil:H.until,mainRefreshLeaseTokenHash:H.tokenHash}),quota:d({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:V})}async function r1($){let Z=await n($.configPath);if(!Z.exists)return null;let z=await n($.statePath);return y6(h6(Z.value,z.value))}var T6=new Set;async function TX($){try{let{exists:Z,value:z}=await n($.configPath);if(!Z)return null;if(!N(z))throw Error("settings must be an object");let X=N(z.refresh)?z.refresh:{},Y=N(z.quota)?z.quota:{};return{version:1,accounts:[],routing:N(z.routing)?z.routing:void 0,fallbackOn:Array.isArray(z.fallbackOn)?z.fallbackOn.filter((G)=>Number.isInteger(G)):void 0,refresh:d({enabled:X.enabled,refreshBeforeExpiryMinutes:X.refreshBeforeExpiryMinutes}),quota:d({enabled:Y.enabled,checkIntervalMinutes:Y.checkIntervalMinutes,refreshEveryNRequests:Y.refreshEveryNRequests,minimumRemaining:Y.minimumRemaining,failClosedOnUnknownQuota:Y.failClosedOnUnknownQuota}),dump:N(z.dump)?z.dump:void 0,costZeroing:N(z.costZeroing)?z.costZeroing:void 0,killswitch:N(z.killswitch)?z.killswitch:void 0,logging:N(z.logging)?z.logging:void 0,cachekeep:N(z.cachekeep)?z.cachekeep:void 0,cacheKeep:N(z.cacheKeep)?z.cacheKeep:void 0}}catch{if(!T6.has($.configPath))T6.add($.configPath),B$.warn("could not read OpenAI auth settings; using defaults",{path:$.configPath});return null}}function m6($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function t1($){return d({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 v6($){if($.type==="api")return d({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return d({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function u$($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function Y$($,Z,z){if(z in Z)$[z]=Z[z];else delete $[z]}function e1($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function $2($,Z){if(!e1($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var Z2=300000;function A6($,Z){if($===void 0)return 0;return $>Z+Z2?0:$}function z2($,Z,z){let X=Date.now(),Y=A6(Z.lastRefreshedAt,X),G=A6(z.lastRefreshedAt,X),J=Z.expires??0,B=z.expires??0,K=G>Y?z:Y>G?Z:B>J?z:J>B?Z:$2(Z,z);Y$($,K,"access"),Y$($,K,"refresh"),Y$($,K,"expires"),Y$($,K,"lastRefreshedAt"),Y$($,K,"lastRefreshError")}function X2($,Z){if(!N($))return Z;let z=$,X=u$(z.quota),Y=u$(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 z2(J,z,Z),J}function g6($){let Z=$.refresh?d({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?d({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return m6({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(t1)})}async function K$($,Z=!1){let z=Date.now(),X=z+m1,Y=0;while(Date.now()<=X){Y++;let B=await w({name:"save",ttlMs:h1,path:$,renew:Z});if(B)return B;let K=X-Date.now();if(K<=0)break;await w1(Math.min(HZ+u6(HZ),K))}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 ${HZ}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 p6($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,v6(z)]));return{version:1,main:d({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 FZ($){if(!N($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!N(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function Y2($,Z,z,X){if(!N($)||!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((K)=>N(K)&&typeof K.id==="string"&&K.id.trim()===J);if(!B)continue;Y.push(B),G.push(J)}return{preservedRawEntries:Y,preservedIds:G}}function J2($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!N(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function G2($,Z,z){let X=FZ($);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:G}=Y2($,X,Z,z);return b6(G),Y}async function AX($,Z,z={}){let{configPath:X,statePath:Y}=Z,G=await K$(X);try{let J=await K$(Y);try{let B=await n(X),K=await n(Y),Q=(B.exists?y6(h6(B.value,K.value)):null)??B2(),H=new Set(Q.accounts.map((m)=>m.id)),W=FZ(B.value)??new Set,V=$(Q,{rawRosterIds:[...W],loadedRosterIds:[...H]})??Q,D=new Set(z.allowDrop??[]),U=G2(B.value,H,D),_=g6(V),M=new Set((Array.isArray(_.accounts)?_.accounts:[]).map((m)=>N(m)&&typeof m.id==="string"?m.id.trim():"").filter(Boolean)),L=U.filter((m)=>{if(!N(m))return!1;if(typeof m.id!=="string")return!1;return!M.has(m.id.trim())}),x=N(B.value)?B.value:{},f={...w6(x),..._,accounts:[...Array.isArray(_.accounts)?_.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return Q;if(await u(X,f),z.canWrite&&!z.canWrite())return Q;return await u(Y,p6(V)),B$.debug("account config written",{accountCount:f.accounts.length,accountIds:J2(f.accounts)}),V}finally{await J.release()}}finally{await G.release()}}function B2(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function K2($,Z){$.main=$.main??{};let z=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:u$($.main.quota),X=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:u$(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 H2($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function UZ($){if(Array.isArray($))return $.map(UZ);if(!N($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,z])=>[Z,UZ(z)]))}async function W2($,Z,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=Z.statePath,G=await K$(Y);try{let J=(await n(Y)).value,B=N(J)?{...J,version:1}:{version:1};if(z.mainQuota)K2(B,$);if(z.mainRefresh)H2(B,$);if(z.accounts){let K=z.accounts===!0?null:new Set(z.accounts),Q=await o1(Z.configPath);B.accounts={...N(B.accounts)?B.accounts:{}};for(let H of $.accounts){if(K&&!K.has(H.id))continue;if(Q&&!Q.has(H.id))continue;B.accounts[H.id]=X2(B.accounts[H.id],v6(H))}if(K){for(let H of K)if(!$.accounts.some((W)=>W.id===H))delete B.accounts[H]}if(Q){for(let H of Object.keys(B.accounts))if(!Q.has(H))delete B.accounts[H]}}if(X&&!X())return;await u(Y,UZ(B))}finally{await G.release()}}function Q2($){return $?.fallbackOn?.length?$.fallbackOn:p1}function EX($,Z){return Q2(Z).includes($)}function U2($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??x6.primary,secondary:Z.secondary??Z["1w"]??x6.secondary}}function DZ($){return $?.quota?.enabled!==!1}function H$($){return $?.quota?.failClosedOnUnknownQuota??l1}function l6($,Z,z=Date.now()){if(!DZ(Z))return!0;if(!$)return!H$(Z);let X=U2(Z),Y=H$(Z);for(let G of["primary","secondary"]){let J=$[G];if(!J)continue;if(l$(J,z)){if(Y)return!1;continue}if(J.remainingPercent<X[G])return!1}return!0}function i$($){return $?.killswitch?.enabled===!0}function E6($){return{primary:$?.primary??$?.["5h"]??QZ.primary,secondary:$?.secondary??$?.["1w"]??QZ.secondary}}function CX($){return $?.cacheKeep??$?.cachekeep}function C6($){return typeof $==="number"&&Number.isFinite($)?$:0}function d6($,Z){if(!$?.killswitch)return QZ;if($.killswitch.schema===g1){let{accounts:z,defaults:X}=$.killswitch,Y=Z??"main",G=N(z)&&Object.hasOwn(z,Y)&&N(z[Y])?z[Y]:N(X)?X:void 0;return{primary:C6(G?.primary),secondary:C6(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return E6($.killswitch.accounts[Z]);return E6($.killswitch.main)}function c6($,Z,z,X=Date.now()){if(!i$(Z))return!0;if(!$)return!H$(Z);let Y=d6(Z,z),G=H$(Z);for(let J of["primary","secondary"]){let B=$[J];if(!B)continue;if(l$(B,X)){if(G)return!1;continue}if(B.remainingPercent<Y[J])return!1}return!0}function IX($,Z,z,X){if(!i$(X))return 300;let Y=[],G=[{accountId:void 0,quota:$},...Z];for(let{accountId:B,quota:K}of G){if(!K)continue;let Q=d6(X,B),H=[],W=!1;for(let V of["primary","secondary"]){let D=K[V];if(!D||l$(D,z))continue;if(D.remainingPercent>=Q[V])continue;let U=D.resetsAt?Date.parse(D.resetsAt):NaN;if(!Number.isFinite(U)||U<=z){W=!0;break}H.push(U)}if(W||H.length===0)continue;Y.push(Math.max(...H))}if(Y.length===0)return 300;let J=Math.min(...Y);return Math.max(1,Math.ceil((J-z)/1000))}function I6($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function kX($,Z){let{configPath:z,statePath:X}=Z;if(!$)return;try{let G=await n(z);if(G.exists&&N(G.value)&&I6(G.value))return}catch{}let Y=await K$(z);try{let G=await K$(X);try{let J=await n(z);if(J.exists&&N(J.value)){if(I6(J.value))return}if(!$)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let H=j$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(H)B.mainAccountId=H}let K=J.exists&&N(J.value)?J.value:{},Q={...w6(K),...g6(B)};await u(z,Q),await u(X,p6(B))}finally{await G.release()}}finally{await Y.release()}}function D2($){return $?.refresh?.enabled!==!1}function V2($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function u6($){return Math.floor(Math.random()*($+1))}function R0($,Z,z){return!$.access||!$.expires||$.expires-z<=V2(Z)}function F2($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function J$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class i6 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 N2="common-auth-placeholder:v1:openai",s6="main";function fX($){return N($)&&$.type==="oauth"&&($.refresh===N2||$.refresh===_6)}function bX($){return $?.accounts.find((Z)=>Z.id===s6&&Z.enabled!==!1&&a(Z))}function yX($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==s6)}}function I($,Z){let z=$.accounts.findIndex((X)=>X.id===Z.id);if(z!==-1)$.accounts[z]=Z}function G$($){return $ instanceof Error?$.message:String($)}function VZ($,Z,z){if(Z instanceof z$)return;$.lastRefreshError=pZ({error:Z,now:z,refreshToken:$.refresh,previous:$.lastRefreshError})}function WZ($,Z,z){if(Z instanceof z$)return;if($.lastQuotaRefreshError=c0({error:Z,now:z,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)VZ($,Z,z)}function k6($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return Number.isFinite(z)?z>Z:!0}function q2($,Z){if(!$)return!1;return k6($.primary,Z)||k6($.secondary,Z)}function M2($,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 f6($,Z,z){return!M2($.quota,Z,z)}function _2($,Z,z,X){return O3(z)&&l6($.quota,Z,X)&&q2($.quota,X)}function O2($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var j2=60000,L2=60000,P2=600000;function x2($){return`fallback-oauth-refresh-${b1("sha256").update($).digest("base64url").slice(0,16)}`}var R2=1e4,S2=100;class T2{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($)p$($.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+O2(Z),checkedAt:z},$.access,!1,$.accountId)}async load(){return r1(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await W2($,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(()=>{})},j2+u6(L2)),"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||!a(Y))continue;if(J$(Z,Y))continue;if(P0(Y))continue;let G=!1,J=Y;try{if(R0(J,Z,this.now())){let B=J.lastRefreshError;if(B&&U0(B,J.refresh,this.now()))throw G=!0,Error(_$(B,this.now()));try{J=await this.refreshAccount(J,Z),X=!0}catch(K){if(u1(K))continue;G=!0;let Q=Z.accounts.find((H)=>H.id===Y.id&&a(H));if(Q&&!U0(Q.lastRefreshError,Q.refresh,this.now()))VZ(Q,K,this.now()),I(Z,Q),X=!0;throw K}}if(this.seedFallbackQuota(J,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),Z))z.push(J)}catch(B){let K=F2(J,this.now());if(G){if(!K)continue}else if(!K)continue;if(_2(J,Z,B,this.now()))x0.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:J.id,error:G$(B)}),z.push(J);else if(!H$(Z))z.push(J)}}if(X){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((G)=>{B$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:G$(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){B$.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:G$(Z)})}}accountPassesQuotaPolicy($,Z){return l6($.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(!$||!D2($))return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!a(z))continue;if(J$($,z))continue;if(P0(z))continue;if(!R0(z,$,this.now()))continue;if(U0(z.lastRefreshError,z.refresh,this.now()))continue;try{x0.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){x0.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:G$(X)}),VZ(z,X,this.now()),I($,z),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!DZ($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!a(z))continue;if(J$($,z))continue;if(P0(z))continue;let X=z;try{if(R0(X,$,this.now())){if(U0(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,$),Z=!0}if(E0(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,$),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):f6(X,$,this.now())))continue;await this.refreshAccountQuota(X,$),Z=!0}catch(Y){WZ(z,Y,this.now()),I($,z),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),z=[];if(!Z||!DZ(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||!a(G))continue;if(J$(Z,G))continue;if(P0(G))continue;let J=G;try{if(R0(J,Z,this.now())){let B=J.lastRefreshError;if(B&&U0(B,J.refresh,this.now()))throw Error(_$(B,this.now()));J=await this.refreshAccount(J,Z),Y=!0}if(!X&&!f6(J,Z,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,I(Z,J),Y=!0;continue}await this.refreshAccountQuota(J,Z),Y=!0}catch(B){WZ(G,B,this.now()),I(Z,G),Y=!0,z.push({accountId:G.id,message:G$(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 I(Z,J),J}let Y=this.refreshAccountNow($,Z,z).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let G=await Y;return I(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,z,X){let Y=Date.now()+R2;while(Date.now()<Y){await new Promise((Q)=>setTimeout(Q,S2));let G=await this.load(),J=G?.accounts.find((Q)=>Q.id===$.id&&a(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||!R0(J,G,this.now())))return I(Z,J),x0.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let K=J.lastRefreshError;if(K&&U0(K,J.refresh,this.now()))throw I(Z,J),Error(_$(K,this.now()))}return null}assertNotShieldedMainRow($,Z,z){if(z.asPoolMain||!Z)return;if(J$($,Z))throw new i6(Z.id)}async refreshAccountNow($,Z,z){let X=await this.load(),Y=X?.accounts.find((B)=>B.id===$.id&&a(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!R0(Y,X,this.now()))return I(Z,Y),Y;let G=Y??$,J=await w({name:x2(G.id),ttlMs:P2,path:this.paths.configPath,renew:!0});if(!J){x0.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((H)=>H.id===$.id&&a(H)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!R0(Y,X,this.now()))return I(Z,Y),Y;if(!Y)throw new c$($.id);G=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});x0.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 K=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=K.access,G.refresh=K.refresh,G.expires=K.expires,G.lastRefreshedAt=K.expires-K.expiresIn*1000,G.lastRefreshError=void 0,I(Z,G),await this.save(Z),!(await this.load())?.accounts.some((H)=>H.id===$.id))throw new c$($.id);return x0.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,I(Z,z),await this.save(Z)}catch(G){throw WZ($,G,this.now()),I(Z,$),G}}}var a6=["primary","secondary"];function s$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function m0($){return typeof $==="number"&&Number.isFinite($)}function A2($,Z){if(!s$(Z))return;let z=Z.usedPercent;if(!m0(z)||z<0||z>100)return;return{label:$,usedPercent:z,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...m0(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function E2($){let Z=$.spendControl;if(s$(Z)&&typeof Z.reached==="boolean"){let z=(X)=>m0(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 C2($,Z){if(!s$($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...m0($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function mX($,Z,z){if(!s$($)||!m0(Z))return;let X=[],Y=[];for(let Q of a6){let H=A2(Q,$[Q]);if(H)X.push(H);else if(z)Y.push({label:Q})}let G=E2($),J=$.resetCreditsAvailable,B=typeof J==="number"&&Number.isSafeInteger(J)&&J>=0?{resetCredits:{value:J,checkedAt:Z}}:void 0,K=C2($.credits,Z);if(X.length===0&&Y.length===0&&!G&&!B&&!K)return;return{checkedAt:Z,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...G?{budget:G}:{},...B?{counters:B}:{},...K?{credits:K}:{}}}function n6($){if(!H0($))return;let Z=y($),z={};for(let X of a6){let Y=Z.limits.find((J)=>J.label===X&&J.kind==="reading");if(!Y||!m0(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 r6="main";function cX($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function uX($,Z,z){let X=new Map;if(i$(Z))for(let Y of $)X.set(Y.id,c6(n6(Y.quota),Z,Y.id===r6?void 0:Y.id,z));return X}var iX=5,I2=5000;function sX($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function aX($,Z=I2){let z=$.rows.filter((J)=>J.kind==="oauth"&&$.killswitch.get(J.id)!==!1&&y(J.quota).limits.length===0);if(z.length===0)return;if(g({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((J)=>$.killswitch.get(J.id)!==!1))return;let Y=[];if(g({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 a$($){return $.reason==="exhausted"||$.reason==="budget-spent"}function k2($,Z){if(!c($))return!1;let z=$;if(!(Z-z.checkedAt<=l0))return!1;if(z.overageLimitReached===!0)return!1;if(z.unlimited)return!0;return z.hasCredits&&(z.balance===void 0||z.balance>0)}function n$($,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 K=y(B.quota);if(Q0(K,Z.now))return!1;return k2(K.credits,Z.now)}).map((B)=>B.id);return{free:Y,credits:J}}function f2($,Z=$.rows){return g({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class b2{#$=new Set;served($,Z,z){let X=f2($),Y=n$($.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 t6($,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 o6($,Z,z){if(Z.refused.find((Y)=>!a$(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return t6($[0],Z,z)}function nX($){let Z=$.replayable!==!1,z=$.mainId===void 0?r6:$.mainId??"",X=Z?$.placement:"main-first",Y=W3({rows:$.rows,placement:X,formerMainId:z,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),G=N$($.rows.map((W)=>W.id),X,z),J=new Set(Y.admission.refused.filter((W)=>a$(W)&&$.killswitch.get(W.id)!==!1).map((W)=>W.id)),B=G.filter((W)=>J.has(W)),K=n$($.rows,$,Y.admission),Q=Y.order.filter((W)=>K.free.has(W)),H=G.filter((W)=>K.credits.includes(W));if(!Z){let W=G.includes(z),V=W?z:Q[0]??H[0]??Y.order[0]??B[0];if(V!==void 0&&Y.order.includes(V))return{kind:"send",order:[V],lastPath:!1};if(V!==void 0&&H.includes(V))return{kind:"send",order:[V],lastPath:!1};if(V!==void 0&&J.has(V))return{kind:"send",order:[V],lastPath:!0};return{kind:"block",block:W?t6(z,Y.admission,$.killswitch):o6(G,Y.admission,$.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(H.length>0){let W=Y.order.length>0?Y.order:B;return{kind:"send",order:[...H,...W.filter((V)=>!H.includes(V))],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:o6(G,Y.admission,$.killswitch)}}function oX($){let Z=g({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),z=new Map;for(let X of $.rows)z.set(X.id,y(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 e6($,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 F3({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 rX($,Z,z,X){let Y=e6($,Z,{exclude:z,pendingBytes:X}),G=$.rows.filter((H)=>!z.has(H.id)),J=n$(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 K=J.credits[0];if(K===void 0)return B;let Q=y(G.find((H)=>H.id===K)?.quota).checkedAt;return{accountId:K,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function tX($,Z,z){let X=$.killswitch.get(z)===!1,Y={kind:"move",reason:X?"killswitch":"exhausted"},G=e6($,Z,{pin:z}),J=n$($.rows,$,G.admission),B=J.credits.includes(z),K=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&&K)return Y;return{kind:"serve"}}let Q=G.admission.refused.find((W)=>W.id===z),H=X||Q!==void 0&&a$(Q);if(B)return{kind:"serve"};if(K)return H?Y:{kind:"detour"};if(!X&&Q&&a$(Q))return{kind:"last-path"};return{kind:"none"}}function eX($,Z,z,X){let Y=$.killswitch.get(z);return V3({quota:Z.projections.get(z),now:$.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as $8}from"node:os";import{join as Z8}from"node:path";var y2=["error","warn","info","debug","trace"];function w2(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?Z8($8(),"opencode-openai-auth","opencode-openai-auth.log"):Z8($8(),"opencode-openai-auth.log"))}function h2(){let $=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return $&&y2.includes($)?$:void 0}z8({file:w2,level:h2});if(process.once("beforeExit",async()=>{try{await o$()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>o$());
|
|
91
|
+
export{H0 as jd,p0 as kd,A8 as ld,G3 as md,Q8 as nd,CZ as od,N8 as pd,q8 as qd,y as rd,Q0 as sd,bZ as td,C8 as ud,N$ as vd,I8 as wd,Q3 as xd,k8 as yd,d4 as zd,c4 as Ad,a0 as Bd,F as Cd,q0 as Dd,M9 as Ed,_9 as Fd,S as Gd,_0 as Hd,P4 as Id,b9 as Jd,y9 as Kd,w9 as Ld,w3 as Md,v9 as Nd,b4 as Od,g9 as Pd,T as Qd,j0 as Rd,XZ as Sd,kz as Td,y8 as Ud,p8 as Vd,gZ as Wd,pZ as Xd,U0 as Yd,_$ as Zd,iZ as _d,aZ as $d,i8 as ae,dZ as be,cZ as ce,j$ as de,a8 as ee,N0 as fe,t8 as ge,e8 as he,$9 as ie,Z9 as je,E7 as ke,I7 as le,k7 as me,f7 as ne,P0 as oe,z$ as pe,zX as qe,XX as re,WX as se,h as te,B0 as ue,a as ve,g1 as we,RX as xe,QZ as ye,c1 as ze,o1 as Ae,r1 as Be,TX as Ce,AX as De,W2 as Ee,Q2 as Fe,EX as Ge,l6 as He,i$ as Ie,CX as Je,d6 as Ke,c6 as Le,IX as Me,kX as Ne,V2 as Oe,J$ as Pe,s6 as Qe,fX as Re,bX as Se,yX as Te,P2 as Ue,x2 as Ve,T2 as We,mX as Xe,n6 as Ye,r6 as Ze,cX as _e,uX as $e,iX as af,sX as bf,aX as cf,k2 as df,b2 as ef,nX as ff,oX as gf,rX as hf,tX as if,eX as jf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as B}from"node:crypto";import{homedir as G,tmpdir as W}from"node:os";import{dirname as J,join as w,resolve as z}from"node:path";var A="OPENCODE_OPENAI_AUTH_RPC_DIR",K="openai-auth-";function L(k){return B("sha256").update(k).digest("hex").slice(0,16)}function M(){let k=process.env.XDG_STATE_HOME||w(G(),".local","state");return w(k,"cortexkit","openai-auth","rpc")}function Q(k){let q=process.env[A]?.trim();if(q)return z(k,q);return w(M(),`${K}${L(k)}`)}async function $(k){let q=process.env[A]?.trim();if(q)return{dir:z(k,q),secureDir:!1};let x=Q(k);return{dir:x,secureDir:!0,sweepRoot:J(x)}}export{W as
|
|
1
|
+
import{createHash as B}from"node:crypto";import{homedir as G,tmpdir as W}from"node:os";import{dirname as J,join as w,resolve as z}from"node:path";var A="OPENCODE_OPENAI_AUTH_RPC_DIR",K="openai-auth-";function L(k){return B("sha256").update(k).digest("hex").slice(0,16)}function M(){let k=process.env.XDG_STATE_HOME||w(G(),".local","state");return w(k,"cortexkit","openai-auth","rpc")}function Q(k){let q=process.env[A]?.trim();if(q)return z(k,q);return w(M(),`${K}${L(k)}`)}async function $(k){let q=process.env[A]?.trim();if(q)return{dir:z(k,q),secureDir:!1};let x=Q(k);return{dir:x,secureDir:!0,sweepRoot:J(x)}}export{W as fg,K as gg,Q as hg,$ as ig};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as parseJwtClaims, a as RESPONSES_LITE_MODELS, g as extractAccountIdFromClaims, h as TokenResponse, l as ResetTargetIdentity, m as IdTokenClaims, n as CODEX_VERSION, o as RuntimeLayoutOptions, s as PoolLifecycleDeps, t as CODEX_USER_AGENT, u as OpenAiVault, v as AccountPaths } from "./codex-request-
|
|
1
|
+
import { _ as parseJwtClaims, a as RESPONSES_LITE_MODELS, g as extractAccountIdFromClaims, h as TokenResponse, l as ResetTargetIdentity, m as IdTokenClaims, n as CODEX_VERSION, o as RuntimeLayoutOptions, s as PoolLifecycleDeps, t as CODEX_USER_AGENT, u as OpenAiVault, v as AccountPaths } from "./codex-request-DFeGDzpN.js";
|
|
2
2
|
import { S as SidebarState, y as SidebarMachineState } from "./sidebar-state-CrRiE9hw.js";
|
|
3
3
|
import { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin";
|
|
4
4
|
type QuotaWindowName = string;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as w,K as f,L as g,M as h,N as i,O as j,P as k,Q as l,R as m,S as n,T as o,U as p,V as q,W as r,X as s,Y as t,Z as u,_ as v,aa as x,ba as y,ca as z,da as A,ea as B,fa as C,ga as D,ha as E,ia as F,j as c,ja as G,k as d,l as e}from"./index-
|
|
1
|
+
import{$ as w,K as f,L as g,M as h,N as i,O as j,P as k,Q as l,R as m,S as n,T as o,U as p,V as q,W as r,X as s,Y as t,Z as u,_ as v,aa as x,ba as y,ca as z,da as A,ea as B,fa as C,ga as D,ha as E,ia as F,j as c,ja as G,k as d,l as e}from"./index-cy6km6cz.js";import"./index-0kpq9310.js";import"./index-afpxnan1.js";import{be as a,ce as b}from"./index-h2z9jb3g.js";import"./index-3x7q1rj8.js";import"./index-2p3st53v.js";import"./index-bxxjwt4q.js";import"./index-7at0fc03.js";import"./index-dp68014q.js";import"./index-smzgsx6x.js";import"./index-4daebegf.js";export{D as rewriteResponsesLiteBody,B as resolveSidebarSessionId,s as poolResetTarget,a as parseJwtClaims,y as mergePushedQuotaMetadata,l as getMainRefreshLockName,x as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,G as default,t as createResetTargetResolver,j as codexOAuthModelVariantSource,h as codexOAuthModelListed,i as codexOAuthModelLimit,A as buildSidebarState,z as buildSidebarMachineState,u as buildResetRedemptionDeps,p as __resetBootQuotaSeedForTest,v as __menuContextForTest,o as __bootQuotaSeedPromiseForTest,r as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,w as POOL_MIGRATION_ENABLED,F as OpenAIAuthPlugin,C as MID_CONVERSATION_EFFORT_MODELS,m as MAIN_REFRESH_LOCK_TTL_MS,n as MAIN_REFRESH_LEASE_TTL_MS,k as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,E as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,q as AuthPersistError,f as ALLOWED_MODELS};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Af as b,Bf as c}from"../index-2p3st53v.js";import{Ff as a}from"../index-bxxjwt4q.js";import"../index-dp68014q.js";import"../index-smzgsx6x.js";import"../index-4daebegf.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
|