@cortexkit/opencode-openai-auth 1.0.5 → 1.1.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 +9 -8
- package/dist/{pool-lifecycle-C_6YRmsh.d.ts → codex-request-BXDXToyt.d.ts} +158 -27
- package/dist/index-0yh85bwb.js +69 -0
- package/dist/{index-826s1yxa.js → index-4c8yw54k.js} +2 -2
- package/dist/{index-y4gxyxqd.js → index-7c6sxtd6.js} +2 -2
- package/dist/index-7eb3dw37.js +90 -0
- package/dist/index-8re8rprk.js +2 -0
- package/dist/{index-66asrje2.js → index-csky2xpg.js} +1 -1
- package/dist/index-edbdscy7.js +65 -0
- package/dist/{index-pg305s90.js → index-f2fmb596.js} +1 -1
- package/dist/{index-fsxbncpw.js → index-j8v2xwq6.js} +1 -1
- package/dist/{index-fsky1rsh.js → index-k6cydkgt.js} +2 -2
- package/dist/{index-116q849r.js → index-m5qmvr6c.js} +2 -2
- package/dist/index-msx2m78k.js +8 -0
- package/dist/{index-nx2qh047.js → index-zpm95mt5.js} +1 -1
- package/dist/index.d.ts +15 -7
- package/dist/index.js +1 -1
- package/dist/{map-m6f5a_IA.d.ts → map-Buq-GW7l.d.ts} +1 -1
- package/dist/{protocol-DctqemRI.d.ts → model-YRg7Uowo.d.ts} +67 -25
- package/dist/{port-file-ZPlxXB4G.d.ts → port-file-CxEpgSHY.d.ts} +1 -1
- package/dist/protocol-CDV1Pc6h.d.ts +29 -0
- package/dist/rpc/port-file.d.ts +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +3 -3
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{sidebar-state-z_M7Trnd.d.ts → sidebar-state-DjTWUbmf.d.ts} +15 -9
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-bzhkgc29.js → token-rz4t3ay6.js} +1 -1
- package/dist/token-util-tpy2c7h6.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +20 -2
- package/dist/v2/server.d.ts +73 -1
- package/dist/v2/server.js +3 -3
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +13 -8
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +354 -0
- package/src/tui-compiled/raw/shared/134b008900698fe0-backoff.js +92 -0
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +393 -0
- package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
- package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +473 -0
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +566 -0
- package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
- package/src/tui-compiled/raw/shared/4593a4d71edf69fd-tombstone.js +25 -0
- package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +500 -0
- package/src/tui-compiled/raw/shared/6371b24a0573d79e-any-signal.js +42 -0
- package/src/tui-compiled/raw/shared/7c140680fc81be92-interlock.js +29 -0
- package/src/tui-compiled/raw/shared/85512cc5263ba259-provider.js +87 -0
- package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +192 -0
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +806 -0
- package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +0 -1
- package/src/tui-compiled/raw/shared/ca0fccaba1d87af4-errors.js +8 -0
- package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +152 -0
- package/src/tui-compiled/raw/shared/d9d2892a4c371301-host-slot.js +72 -0
- package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +1470 -0
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +24 -0
- package/src/tui-compiled/raw/sidebar-state.js +41 -14
- package/src/tui-compiled/raw/tui/command-dialogs.tsx +3 -34
- package/src/tui-compiled/raw/tui/section-text.js +21 -0
- package/src/tui-compiled/raw/tui/v2-dialog.js +137 -0
- package/src/tui-compiled/raw/tui/v2.tsx +133 -0
- package/src/tui-compiled/raw/tui.tsx +146 -40
- package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +13 -8
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +354 -0
- package/src/tui-compiled/runtime/shared/134b008900698fe0-backoff.js +92 -0
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +393 -0
- package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
- package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +473 -0
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +566 -0
- package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
- package/src/tui-compiled/runtime/shared/4593a4d71edf69fd-tombstone.js +25 -0
- package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +500 -0
- package/src/tui-compiled/runtime/shared/6371b24a0573d79e-any-signal.js +42 -0
- package/src/tui-compiled/runtime/shared/7c140680fc81be92-interlock.js +29 -0
- package/src/tui-compiled/runtime/shared/85512cc5263ba259-provider.js +87 -0
- package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +192 -0
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +806 -0
- package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +0 -1
- package/src/tui-compiled/runtime/shared/ca0fccaba1d87af4-errors.js +8 -0
- package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +152 -0
- package/src/tui-compiled/runtime/shared/d9d2892a4c371301-host-slot.js +72 -0
- package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +1470 -0
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +24 -0
- package/src/tui-compiled/runtime/sidebar-state.js +41 -14
- package/src/tui-compiled/runtime/tui/command-dialogs.js +3 -15
- package/src/tui-compiled/runtime/tui/section-text.js +21 -0
- package/src/tui-compiled/runtime/tui/v2-dialog.js +137 -0
- package/src/tui-compiled/runtime/tui/v2.js +95 -0
- package/src/tui-compiled/runtime/tui.js +255 -163
- package/dist/index-4fnghj9e.js +0 -65
- package/dist/index-a69gr76b.js +0 -2
- package/dist/index-h263aftt.js +0 -157
- package/dist/index-ssj7m2rd.js +0 -8
- package/dist/index-ydz3hbhc.js +0 -2
- package/dist/token-util-4a2xxnpg.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{d as
|
|
1
|
+
import{ne as k,oe as _,pe as R}from"./index-k6cydkgt.js";import{Ge as h,Le as D}from"./index-m5qmvr6c.js";import{Re as w}from"./index-f2fmb596.js";class T extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function F(f){return typeof f==="string"&&f.length>0}var S=new Map;function W(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=S.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},S.set(x,z);return z}var U=100,j=3000;function d(f,x,z){if(f.requireSession===!0&&!F(z))throw new T("push");let J=W(f);if(J.queue.push({id:J.nextId++,type:"open-dialog",payload:x,sessionId:z}),J.queue.length>U)J.queue=J.queue.slice(-U)}function i(f,x=0,z){if(f.requireSession===!0&&!F(z))throw new T("drain");let J=W(f),Y=Date.now();if(J.lastDrainAtAny=Y,z!==void 0)J.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",V=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)J.queue=J.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return J.queue.filter((B)=>B.id>x&&V(B))}function n(f,x){let z=Date.now(),J=W(f),Y=x!==void 0?J.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?J.lastDrainAtAny:0;return Y>0&&z-Y<j}import{randomBytes as t,timingSafeEqual as q}from"node:crypto";import{unlink as v}from"node:fs/promises";import{createServer as u}from"node:http";import{join as I}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class g extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function l(f){return new Promise((x,z)=>{let J=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new g(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){J(!0);return}let Z=[],V=0;f.on("data",(B)=>{if(V+=B.length,V>E){J();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class m extends Error{}async function p(f,x){let z,J=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new m("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,J])}finally{clearTimeout(z)}}function c(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),J=Buffer.from(x);return z.length===J.length&&q(z,J)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=t(32).toString("hex"),J=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,V=new Set,B=u((G,K)=>{G.setTimeout(J,()=>{G.socket.destroy()}),M(G,K)});B.on("connection",(G)=>{V.add(G),G.once("close",()=>V.delete(G))}),B.requestTimeout=Y,B.headersTimeout=Y;async function M(G,K){let H=(X,Q,C={})=>{if(K.headersSent||K.writableEnded||K.destroyed)return;K.writeHead(X,{"content-type":"application/json",...C}),K.end(JSON.stringify(Q))};try{let X=new URL(G.url??"/","http://127.0.0.1").pathname;if(G.method==="GET"&&X==="/health")return H(200,{ok:!0});if(G.method!=="POST"||!X.startsWith("/rpc/"))return H(404,{error:"not found"});if(!c(G.headers.authorization,z))return H(401,{error:"unauthorized"});let Q=X.slice(5),C;try{C=await l(G)}catch($){if(!($ instanceof g))throw $;if($.declaredOversize){let y=G.socket;K.once("finish",()=>{y.end();let A=setTimeout(()=>y.destroy(),2000);if(A.unref(),G.once("end",()=>y.destroy()),y.once("close",()=>clearTimeout(A)),G.complete)y.destroy()})}return H(413,{error:"body too large"},{connection:"close"})}let b;try{b=JSON.parse(C||"{}")}catch{return H(400,{error:"invalid json"})}if(Q==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(b);else{if(!b||typeof b!=="object"||Array.isArray(b))throw Error("invalid params");let L=b;if(f.requireSession===!0&&!F(L.sessionId))return H(400,{error:"session required"});if("lastReceivedId"in L&&(typeof L.lastReceivedId!=="number"||!Number.isSafeInteger(L.lastReceivedId)||L.lastReceivedId<0)||"sessionId"in L&&typeof L.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(L.lastReceivedId??0),sessionId:typeof L.sessionId==="string"?L.sessionId:void 0}}}catch(L){if(L instanceof N)throw L;return H(400,{error:"invalid params"})}let{lastReceivedId:y,sessionId:A}=$;if(f.requireSession===!0&&!F(A))return H(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let O;if(f.drainAsync)try{O=await f.drainAsync(y,A)}catch(L){return x.warn("rpc notification drain failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)}),H(500,{error:"drain failed"})}else O=f.drain?.(y,A);return H(200,{messages:O})}if(Q==="apply"){let $=Promise.resolve(f.apply(b)),y=f.applyDeadlineMs===void 0?await $:await p($,f.applyDeadlineMs);return H(200,y)}return H(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),H(X.status,{error:X.message});if(X instanceof m)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),H(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),H(500,{error:"internal error"})}}let P=await new Promise((G,K)=>{B.on("error",K),B.listen(0,"127.0.0.1",()=>{let H=B.address();if(H&&typeof H==="object")G(H.port);else K(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await R(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(G){x.warn("rpc state sweep failed",{pid:process.pid,error:G instanceof Error?G.message:String(G)})}try{await _(f.dir,{port:P,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:P})}catch(G){throw await new Promise((K)=>B.close(()=>K())),G}return{port:P,token:z,async stop(){await new Promise((H)=>{B.closeAllConnections?.(),B.close(()=>H());for(let X of V)X.destroy()});let G=I(f.dir,`port-${process.pid}.json`),K=await D(G).then((H)=>JSON.parse(H)).catch((H)=>{if(H instanceof h&&H.code!=="ENOENT")throw H;return});if(K?.port===P&&K.token===z)await v(G).catch(()=>{})}}}async function Hf(f,x,z){let J=globalThis,Y=Symbol.for(f),Z=J[Y]??{servers:new Map,pending:new Map};J[Y]=Z;let{servers:V,pending:B}=Z,M=B.get(x)??Promise.resolve(),P,G=M.catch(()=>{}).then(async()=>{let H=V.get(x);if(H){if(await H.stop(),V.get(x)===H)V.delete(x)}P=await z(),V.set(x,P)});B.set(x,G);try{await G}finally{if(B.get(x)===G)B.delete(x)}let K=P;if(!K)throw Error("RPC server failed to start");return{server:K,release:async()=>{if(V.get(x)!==K)return;if(await K.stop(),V.get(x)===K)V.delete(x)}}}var bf=k(w);
|
|
2
|
+
export{d as he,i as ie,n as je,Bf as ke,Hf as le,bf as me};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`;try{G?.({channel:Q,level:V,message:S,data:K})}catch{}if(H===void 0)return;if(U.push(r),U.length>=50){let E=R(!1);if(E instanceof Promise)E.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(V,X)=>_(Q,"error",V,X),warn:(V,X)=>_(Q,"warn",V,X),info:(V,X)=>_(Q,"info",V,X),debug:(V,X)=>_(Q,"debug",V,X),trace:(V,X)=>_(Q,"trace",V,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,U=[],$)clearTimeout($),$=void 0;H=void 0,Z=void 0,I=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var x=BJ();function L(J){x.configure(J);let{configure:H,createLogger:Z,setLogLevel:I,flushLogs:B}=x;return{configure:H,createLogger:Z,setLogLevel:I,flushLogs:B}}function v(J){x.setLogLevel(J)}function u(){return x.flushLogs()}function c(J){return x.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,hJ=d.redactStrings;function mJ(J){L({...J,extraSecretKeys:f})}function cJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function dJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",_J="openai-auth-state.json";function tJ(J){return MJ(J)===AJ?qJ(TJ(J),_J):`${J}.state.json`}import{execFileSync as OJ,spawn as xJ}from"node:child_process";function lJ(J,H=process.platform,Z=OJ,I=xJ){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),U=I("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}return Z(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore",timeout:3000}),!0}catch{return!1}}export{T as
|
|
1
|
+
import{Fe as q,He as O,Je as A,Ke as y,Me as p,Oe as k}from"./index-m5qmvr6c.js";import{appendFileSync as QJ,chmodSync as UJ,existsSync as W,renameSync as g,statSync as ZJ}from"node:fs";import{open as $J}from"node:fs/promises";import{dirname as VJ,resolve as IJ}from"node:path";var i=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,e=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function JJ(J){return J instanceof Error||Object.prototype.toString.call(J)==="[object Error]"}function T(J={}){let H=[e,...J.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function Z(G){let U=G.toLowerCase().replace(/[-_]/g,"");return i.test(G)||U.includes("apikey")||U.endsWith("secret")||U.endsWith("password")||U.endsWith("token")&&!U.endsWith("tokens")||!!J.extraSecretKeys?.(U)}function I(G){let U=G,$=[["name",G.name],["message",G.message],["stack",G.stack]];for(let j of["code","status","cause"])if(U[j]!==void 0)$.push([j,U[j]]);let Y=new Set($.map(([j])=>j));for(let j of Object.entries(G))if(!Y.has(j[0]))$.push(j);return $}function B(G,U,$,Y=0){if(typeof G==="string")return H.reduce((j,C)=>j.replace(C,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if($.has(G))return"[Circular]";$.add(G);try{if(Array.isArray(G))return G.map((N)=>B(N,U,$,Y));let j=JJ(G);if(j&&Y>=8)return"[Truncated]";let C=j?Y+1:Y;return Object.fromEntries((j?I(G):Object.entries(G)).map(([N,z])=>[N,U&&Z(N)?"***REDACTED***":B(z,U,$,C)]))}finally{$.delete(G)}}return{redact:(G)=>B(G,!0,new WeakSet),redactStrings:(G)=>B(G,!1,new WeakSet)}}var F=T(),GJ=F.redact,HJ=F.redactStrings;var D={error:0,warn:1,info:2,debug:3,trace:4},h=5242880,m=3;function b(J){try{UJ(J,384)}catch{}}function jJ(J){try{if(!(W(J)&&ZJ(J).size>=h))return;for(let Z=m-1;Z>=1;Z--)if(W(`${J}.${Z}`)){let I=`${J}.${Z+1}`;g(`${J}.${Z}`,I),b(I)}let H=`${J}.1`;g(J,H),b(H)}catch{}}async function M(J){let{file:H,handle:Z}=J;if(J.file=void 0,J.handle=void 0,H&&Z)await O(H,"log-close",()=>Z.close())}async function w(J,H){await y(VJ(H));try{await A(H,"file",!0)}catch(Z){if(Z.code!=="ENOENT")throw Z;try{await p(H,"")}catch(I){if(I.code!=="EEXIST")throw I;await A(H,"file",!0)}}return J.handle=await O(H,"log-open",()=>$J(H,"a")),J.file=H,J.handle}async function XJ(J,H,Z){H=IJ(H);try{if(J.file!==H)await M(J);let I=J.handle??await w(J,H);if((await O(H,"log-stat",()=>I.stat())).size>=h){await M(J);for(let G=m-1;G>=0;G--){let U=G===0?H:`${H}.${G}`,$=`${H}.${G+1}`;try{await A(U,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await A($,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await k(U,$),await A($,"file")}I=await w(J,H)}await O(H,"log-append",()=>I.appendFile(Z,"utf8"))}catch(I){throw await M(J).catch(()=>{}),I}}function YJ(J){try{return` ${JSON.stringify(J)}`}catch{return" [unserializable]"}}function BJ(J){let H,Z,I,B=T(),G,U=[],$,Y=Promise.resolve(),j,C={};function N(Q){let V=Y.then(Q);return Y=V.catch((X)=>{j=X}),V}function z(Q){if(q&&Q.file!==H)N(()=>M(C)).catch(()=>{});H=Q.file,Z=Q.level,B=T(Q),G=Q.captureSink}function s(Q){if(Q===void 0||Q in D)I=Q}function o(){if(H===void 0)return;return(typeof H==="function"?H():H)||void 0}function t(){if(I)return I;let Q=typeof Z==="function"?Z():Z;if(Q&&Q in D)return Q;return"info"}function R(Q=!0){if($)clearTimeout($),$=void 0;if(!U.length){if(q)return N(async()=>{if(Q)await M(C);if(j)throw j});return}let V;try{V=o()}catch{if(U=[],q&&Q)return N(()=>M(C));return}let X=U.join("");if(U=[],!V){if(q&&Q)return N(()=>M(C));return}if(q)return N(async()=>{try{await XJ(C,V,X)}finally{if(Q)await M(C)}});try{if(jJ(V),W(V))b(V);QJ(V,X,{encoding:"utf8",mode:384})}catch{}}function a(){if(!$)$=setTimeout(()=>{$=void 0;let Q=R(!1);if(Q instanceof Promise)Q.catch(()=>{})},500)}function _(Q,V,X,P){if(H===void 0&&G===void 0)return;try{if(D[V]>D[t()])return;let S=B.redactStrings(X),K;try{K=B.redact(P)}catch{K="[unserializable]"}let r=`[${new Date().toISOString()}] ${V.toUpperCase()} [${Q}] ${S}`+(P===void 0?"":YJ(K))+`
|
|
2
|
+
`;try{G?.({channel:Q,level:V,message:S,data:K})}catch{}if(H===void 0)return;if(U.push(r),U.length>=50){let E=R(!1);if(E instanceof Promise)E.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(V,X)=>_(Q,"error",V,X),warn:(V,X)=>_(Q,"warn",V,X),info:(V,X)=>_(Q,"info",V,X),debug:(V,X)=>_(Q,"debug",V,X),trace:(V,X)=>_(Q,"trace",V,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,U=[],$)clearTimeout($),$=void 0;H=void 0,Z=void 0,I=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var x=BJ();function L(J){x.configure(J);let{configure:H,createLogger:Z,setLogLevel:I,flushLogs:B}=x;return{configure:H,createLogger:Z,setLogLevel:I,flushLogs:B}}function v(J){x.setLogLevel(J)}function u(){return x.flushLogs()}function c(J){return x.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,hJ=d.redactStrings;function mJ(J){L({...J,extraSecretKeys:f})}function cJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function dJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",_J="openai-auth-state.json";function tJ(J){return MJ(J)===AJ?qJ(TJ(J),_J):`${J}.state.json`}import{execFileSync as OJ,spawn as xJ}from"node:child_process";function lJ(J,H=process.platform,Z=OJ,I=xJ){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),U=I("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}return Z(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore",timeout:3000}),!0}catch{return!1}}export{T as te,GJ as ue,v as ve,u as we,c as xe,hJ as ye,mJ as ze,AJ as Ae,tJ as Be,cJ as Ce,dJ as De,lJ as Ee};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import{$d as y,ce as E,fe as x3}from"./index-msx2m78k.js";import{Ce as v$,we as W3,xe as I,ze as M8}from"./index-7c6sxtd6.js";import{Fe as XZ,Ge as E3,Ie as Q$,Ke as g3,Le as oZ,Pe as V$}from"./index-m5qmvr6c.js";var O="all",D3=Object.freeze(["primary"]);function q6(Z){return Z.kind==="retired"?Z.retiredAt:Z.checkedAt}function HZ(Z,$){return JSON.stringify([Z,$])}function a(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function R(Z){return typeof Z==="number"&&Number.isFinite(Z)}function j6(Z){return typeof Z==="string"&&Z.length>0}function C(Z,$,z){return Z[$]===void 0||z(Z[$])}function O8(Z){return R(Z)&&Z>0}function U3(Z){return typeof Z==="string"}function L8(Z){if(!a(Z)||!j6(Z.scope)||!j6(Z.label))return!1;switch(Z.kind){case"reading":return R(Z.checkedAt)&&R(Z.usedPercent)&&C(Z,"resetsAt",U3)&&C(Z,"windowMinutes",O8);case"retired":return R(Z.retiredAt);case"absent":return R(Z.checkedAt);default:return!1}}function S8(Z){if(!a(Z)||!R(Z.checkedAt))return!1;if(Z.kind==="cleared")return!0;return Z.kind==="reading"&&typeof Z.reached==="boolean"&&C(Z,"remainingPercent",R)&&C(Z,"usedPercent",R)&&C(Z,"resetsAt",U3)&&C(Z,"limit",R)&&C(Z,"used",R)&&C(Z,"remaining",R)&&C(Z,"unit",U3)}function M6(Z){return a(Z)&&R(Z.value)&&Number.isInteger(Z.value)&&Z.value>=0&&R(Z.checkedAt)}function F3(Z){return a(Z)&&Object.values(Z).every(M6)}function N3(Z){if(!a(Z))return;let $=Object.entries(Z).filter(([,z])=>M6(z));return $.length===0?void 0:Object.fromEntries($)}function o(Z){if(n(Z))return Z;if(!a(Z))return;let{counters:$,...z}=Z;if(!n(z))return;let X=N3($);return{...z,...X===void 0?{}:{counters:X}}}function n(Z){if(!a(Z)||!Array.isArray(Z.limits))return!1;let $=new Set;for(let z of Z.limits){if(!L8(z))return!1;let X=HZ(z.scope,z.label);if($.has(X))return!1;$.add(X)}return C(Z,"budget",S8)&&C(Z,"counters",F3)}var O6=900000,L6="no quota reading yet",S6="no limits reported";function R6(Z){let $=Math.max(1,Math.floor(Z/60000));if($<60)return`${$}m`;if($<1440){let Y=Math.floor($/60),G=$%60;return G===0?`${Y}h`:`${Y}h${G}m`}let z=Math.floor($/1440),X=Math.floor($%1440/60);return X===0?`${z}d`:`${z}d${X}h`}function R8(Z){if(Z%1440===0)return`${Z/1440}d`;if(Z%60===0)return`${Z/60}h`;return`${Z}m`}function T6(Z){if(Z.scope!==O||Z.windowMinutes===void 0)return Z.label;return R8(Z.windowMinutes)}function j3(Z){return Math.min(100,Math.max(0,Z))}function _6(Z){return`${Math.round(j3(Z))}% left`}function P6(Z,$,z){let X=Z===void 0?Number.NaN:Date.parse(Z);return{...Number.isFinite(X)&&X>z?{resetIn:R6(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>$&&X<=z}}function T8(Z,$){let z=Z.windowMinutes,X=$.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(Z.scope!==$.scope){if(Z.scope===O)return-1;if($.scope===O)return 1;return Z.scope<$.scope?-1:1}return Z.label<$.label?-1:Z.label>$.label?1:0}function E6(Z,$){if(!Z)return{windows:[]};let{now:z}=$,Y=Z.limits.filter((B)=>B.kind==="reading"&&B.remainingPercent!==void 0).sort(T8).map((B)=>{let J=j3(B.remainingPercent??0);return{kind:"window",name:T6(B),figure:_6(B.remainingPercent??0),remainingPercent:J,checkedAt:B.checkedAt,...P6(B.resetsAt,B.checkedAt,z)}}),G=Z.budget;if(G){let B=G.remainingPercent,J=G.reached?"credits spent":B!==void 0?`credits ${_6(B)}`:"credits available";Y.push({kind:"budget",name:"credits",figure:J,...B===void 0?{}:{remainingPercent:j3(B)},checkedAt:G.checkedAt,...P6(G.resetsAt,G.checkedAt,z)})}if(Y.length>0){let B=z-Math.min(...Y.map((J)=>J.checkedAt));if(B>($.staleAfterMs??O6))return{windows:Y,age:`checked ${R6(B)} ago`}}return{windows:Y}}function x6(Z,$){let z=E6(Z,$),X=($.form??"full")==="full",Y=z.windows.map((G)=>{let B=X&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${B}`});return z.age===void 0?Y:[...Y,z.age]}function E8(Z,$){let z=x6(Z,$);if(z.length>0)return z.join(" · ");return Z&&Z.limits.length>0?S6:L6}function x8(Z){if(Z.kind==="retired")return{scope:Z.scope,label:Z.label,kind:"retired",checkedAt:Z.retiredAt};if(Z.kind==="absent")return{scope:Z.scope,label:Z.label,kind:"absent",checkedAt:Z.checkedAt};return{scope:Z.scope,label:Z.label,kind:"reading",checkedAt:Z.checkedAt,usedPercent:Z.usedPercent,remainingPercent:100-Z.usedPercent,...Z.windowMinutes===void 0?{}:{windowMinutes:Z.windowMinutes},...Z.resetsAt===void 0?{}:{resetsAt:Z.resetsAt}}}function C8(Z,$){let z=Z.windowMinutes!==void 0,X=$.windowMinutes!==void 0;if(z!==X)return z?-1:1;if(z&&X&&Z.windowMinutes!==$.windowMinutes)return($.windowMinutes??0)-(Z.windowMinutes??0);if(Z.label!==$.label)return Z.label<$.label?-1:1;return 0}function b8(Z){return{checkedAt:Z.checkedAt,reached:Z.reached,...Z.remainingPercent===void 0?{}:{remainingPercent:Z.remainingPercent},...Z.resetsAt===void 0?{}:{resetsAt:Z.resetsAt}}}function A(Z,$=O){let z=new Map;for(let H of Z?.limits??[]){if(H.scope!==$&&H.scope!==O)continue;let Q=z.get(H.label);if(Q===void 0){z.set(H.label,H);continue}let D=H.scope===O?Q:H,V=H.scope===O?H:Q;z.set(H.label,D.kind==="reading"?D:V)}let X=[...z.values()].map(x8).sort(C8),Y=X.filter((H)=>H.kind==="reading"),G=Y.length>0?Y:X,B=G.length>0?Math.min(...G.map((H)=>H.checkedAt)):void 0,J=Z?.budget?.kind==="reading"?b8(Z.budget):void 0,W=N3(Z?.counters);return{scope:$,limits:X,...B===void 0?{}:{checkedAt:B},...J===void 0?{}:{budget:J},...W===void 0?{}:{counters:W}}}function NZ(Z,$){let z=Z?.budget;if(z?.reached!==!0||typeof z.resetsAt!=="string")return;let X=Date.parse(z.resetsAt);if(!Number.isFinite(X)||X<=$)return;return{resetsAt:z.resetsAt,resetAtMs:X}}function q3(Z){return Z.kind==="reading"&&typeof Z.usedPercent==="number"&&Number.isFinite(Z.usedPercent)&&Z.usedPercent>=100}function fZ(Z,$){if(typeof Z.resetsAt!=="string")return;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)&&z>$?z:void 0}class yZ extends TypeError{constructor(Z){super(Z);this.name="QuotaCodecError"}}function hZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function wZ(Z){return typeof Z==="number"&&Number.isFinite(Z)}function C6(Z){return Z===void 0||typeof Z==="string"&&Z!==""}function b6(Z){return typeof Z==="string"&&Z!==""}function jZ(Z,$){return Z[$]===void 0||wZ(Z[$])}function M3(Z,$){return Z[$]===void 0||typeof Z[$]==="string"}function A8(Z){return hZ(Z)&&C6(Z.scope)&&b6(Z.label)&&wZ(Z.usedPercent)&&M3(Z,"resetsAt")&&(Z.windowMinutes===void 0||wZ(Z.windowMinutes)&&Z.windowMinutes>0)}function I8(Z){return hZ(Z)&&C6(Z.scope)&&b6(Z.label)}function k8(Z){if(!hZ(Z))return!1;if(Z.kind==="cleared")return!0;return Z.kind==="reading"&&typeof Z.reached==="boolean"&&jZ(Z,"remainingPercent")&&jZ(Z,"usedPercent")&&M3(Z,"resetsAt")&&jZ(Z,"limit")&&jZ(Z,"used")&&jZ(Z,"remaining")&&M3(Z,"unit")}function A6(Z){if(!hZ(Z)||!wZ(Z.checkedAt))return!1;let $=Z.readings??[],z=Z.coverage??[];if(!Array.isArray($)||!Array.isArray(z))return!1;let X=new Set;for(let Y of $){if(!A8(Y))return!1;let G=HZ(Y.scope??O,Y.label);if(X.has(G))return!1;X.add(G)}if(!z.every(I8))return!1;return(Z.budget===void 0||k8(Z.budget))&&(Z.counters===void 0||F3(Z.counters))}function f8(Z,$){if(Z.scope!==$.scope)return Z.scope<$.scope?-1:1;if(Z.label!==$.label)return Z.label<$.label?-1:1;return 0}function y8(Z,$,z){if($===void 0)return Z;if(Z!==void 0&&z<Z.checkedAt)return Z;return{...$,checkedAt:z}}function w8(Z,$){let z=new Map(Object.entries(Z??{}));for(let[X,Y]of Object.entries($??{})){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 KZ(Z,$){let z=Z===void 0?void 0:o(Z);if(Z!==void 0&&z===void 0)throw new yZ("stored quota map is malformed");if(!A6($))throw new yZ("quota observation is malformed");let X=z??{limits:[]},Y=$.checkedAt,G=new Map;for(let K of X.limits)G.set(HZ(K.scope,K.label),K);let B=(K)=>{let q=G.get(K);return q===void 0||Y>=q6(q)},J=new Set;for(let K of $.readings??[]){let q=K.scope??O,P=HZ(q,K.label);if(J.add(P),!B(P))continue;G.set(P,{scope:q,label:K.label,kind:"reading",checkedAt:Y,usedPercent:K.usedPercent,...K.resetsAt===void 0?{}:{resetsAt:K.resetsAt},...K.windowMinutes===void 0?{}:{windowMinutes:K.windowMinutes}})}for(let K of $.coverage??[]){let q=K.scope??O,P=HZ(q,K.label);if(J.has(P)||!B(P))continue;let L=G.get(P);G.set(P,L===void 0||L.kind==="absent"?{scope:q,label:K.label,kind:"absent",checkedAt:Y}:{scope:q,label:K.label,kind:"retired",retiredAt:Y})}let{limits:W,budget:H,counters:Q,...D}=X,V=y8(X.budget,$.budget,Y),j=w8(X.counters,$.counters);return{...D,limits:[...G.values()].sort(f8),...V===void 0?{}:{budget:V},...j===void 0?{}:{counters:j}}}var h8=Object.freeze({validate:n,decode:o,merge:KZ});function I6(Z,$,z){let X=$.rateLimitMarks?.get(Z);if(X!==void 0&&z<X)return{id:Z,reason:"rate-limited",until:X};let Y=$.refreshBackoff?.get(Z);if(Y!==void 0&&z<Y)return{id:Z,reason:"refresh-backoff",until:Y};return}function m8(Z,$,z,X){if($.limits.length===0)return{id:Z,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let G of z)if(!$.limits.some((B)=>B.label===G))return{id:Z,stage:1,gate:3,reason:"unknown-window",window:{scope:$.scope,label:G},pullRequested:!0};let Y=$.limits.filter(q3);for(let G of Y)if(fZ(G,X)===void 0)return{id:Z,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of Y){let B=fZ(G,X);if(B!==void 0&&typeof G.resetsAt==="string")return{id:Z,stage:1,gate:5,reason:"exhausted",window:{scope:G.scope,label:G.label},resetsAt:G.resetsAt,resetAtMs:B}}return}function f(Z){let $=Z.scope??O,z=Z.requiredLabels??D3,X=[],Y=[],G=[];for(let V of Z.rows){let j=I6(V.id,Z,Z.now);if(j){X.push(j);continue}if(V.kind==="api-key"){G.push({id:V.id,kind:V.kind});continue}let K=A(V.quota,$),q=m8(V.id,K,z,Z.now);if(q){Y.push(q);continue}G.push({id:V.id,kind:V.kind,projection:K})}let B=new Map(G.flatMap((V)=>{let j=NZ(V.projection,Z.now);return j?[[V.id,j]]:[]})),J=B.size>0&&B.size===G.length,W=[];for(let V of G){let j=B.get(V.id);if(j===void 0)W.push(V);else if(J)W.push({...V,lastPath:!0});else Y.push({id:V.id,stage:2,reason:"budget-spent",...j})}let H=new Map(Z.rows.map((V,j)=>[V.id,j])),Q=(V,j)=>(H.get(V.id)??0)-(H.get(j.id)??0);Y.sort(Q);let D=Y.filter((V)=>("pullRequested"in V)).map((V)=>V.id);for(let V of D)Z.requestPull?.(V);return{admitted:W,refused:Y,excluded:X,pulls:D}}var k6="main";function v8(Z){switch(Z){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 mZ(Z,$,z=k6){if($==="roster"||!Z.includes(z))return[...Z];let X=Z.filter((Y)=>Y!==z);return $==="main-first"?[z,...X]:[...X,z]}function _3(Z){let $=f(Z),z=new Set($.admitted.map((Y)=>Y.id));return{order:mZ(Z.rows.map((Y)=>Y.id),Z.placement??"roster",Z.formerMainId).filter((Y)=>z.has(Y)&&Z.killswitch?.get(Y)!==!1),admission:$}}function g8(Z,$,z){let X=$.at(-1);if(X!==void 0){if(X.status===void 0||!z.includes(X.status))return}let Y=new Set($.map((G)=>G.id));return Z.find((G)=>!Y.has(G))}function P3(Z,$,z){if(!$.has(Z.accountId))return!1;return!(typeof Z.wireIdentity==="string"&&typeof z==="string"&&Z.wireIdentity!==z)}function p8(Z,$,z){let X=new Map;for(let[Y,G]of Z){if(Y===z)continue;if(G.quotaCheckedAt!==$.get(G.accountId))continue;X.set(G.accountId,(X.get(G.accountId)??0)+(G.inputBytes??0))}return X}var S3=900000,y6=0.016666666666666666,O3=0.000001;function vZ(Z,$){for(let z of[Z?.checkedAt,$])if(typeof z==="number"&&Number.isFinite(z))return z;return}function w6(Z){if(Z===401||Z===403)return"permanent";if(Z===void 0||Z===0||!Number.isFinite(Z)||Z>=500&&Z<=599||Z===429)return"transient";return"healthy"}function h6(Z){return Z.limits.filter(($)=>$.kind==="reading").sort(($,z)=>{let X=$.windowMinutes!==void 0,Y=z.windowMinutes!==void 0;if(X!==Y)return X?-1:1;if(X&&Y)return(z.windowMinutes??0)-($.windowMinutes??0);return 0})}function R3(Z){let $=(Z.classifyStatus??w6)(Z.status);if($==="permanent")return{action:"migrate",reason:"permanent"};if(!Z.quota)return{action:"retain",reason:"unknown"};let z=vZ(Z.quota,Z.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||Z.now-z>S3)return{action:"retain",reason:"stale"};if(Z.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of h6(Z.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=NZ(Z.quota,Z.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:$}}function L3(Z,$,z){let X=Math.max(0,Z.remainingPercent-$);if(X<=0)return 0;if(!Z.resetsAt)return X;let Y=Date.parse(Z.resetsAt);if(!Number.isFinite(Y)||Y<=z)return X;let G=Math.max((Y-z)/3600000,y6);return X/G}function f6(Z,$){if(Z<$)return-1;if(Z>$)return 1;return 0}function l8(Z,$){if(!Z.quota)return;let z=vZ(Z.quota,Z.quotaCheckedAt);if(z===void 0||$-z>S3)return;let X=h6(Z.quota).map((B)=>L3({remainingPercent:B.remainingPercent??Number.NaN,...B.resetsAt===void 0?{}:{resetsAt:B.resetsAt}},Z.reservePercent[B.label]??0,$)),Y=Z.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))X.push(L3({remainingPercent:Y.remainingPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt}},0,$));let G=X.length>0?Math.min(...X):0;return G>0?{candidate:Z,quotaCheckedAt:z,weight:G}:void 0}function m6(Z){let $=Z.candidates.filter((Y)=>Y.killswitchPasses!==!1);if(Z.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if($.length===0)return;let z=$.map((Y)=>l8(Y,Z.now)).filter((Y)=>Y!==void 0);if(z.length>0){z.sort((G,B)=>{let J=((Z.pendingBytes.get(G.candidate.accountId)??0)+Z.requestBytes)/Math.max(G.weight,O3),W=((Z.pendingBytes.get(B.candidate.accountId)??0)+Z.requestBytes)/Math.max(B.weight,O3);return J-W||G.candidate.configuredOrder-B.candidate.configuredOrder||f6(G.candidate.accountId,B.candidate.accountId)});let Y=z[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}Z.onEmptyWeightedSet?.();let X=[...$].sort((Y,G)=>{let B=(Y.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-B||Y.configuredOrder-G.configuredOrder||f6(Y.accountId,G.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:vZ(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function T3(Z){let $=f(Z),z=new Map($.admitted.map((K)=>[K.id,K])),X=new Map($.refused.map((K)=>[K.id,K])),Y=new Set($.excluded.map((K)=>K.id)),G=new Set(Z.rows.map((K)=>K.id)),B=Z.pin!==void 0&&P3(Z.pin,G,Z.identities?.get(Z.pin.accountId));if(B&&Z.pin){let K=z.get(Z.pin.accountId);if(K&&Z.killswitch?.get(K.id)!==!1)return{outcome:"dispatch",accountId:K.id,source:"pin",...K.projection?.checkedAt===void 0?{}:{quotaCheckedAt:K.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:$}}let J=Z.pin?X.get(Z.pin.accountId):void 0,W=B&&Z.pin!==void 0&&Z.refusedPinPolicy==="move-on-confirmed-exhaustion"&&(Z.killswitch?.get(Z.pin.accountId)===!1||J?.reason==="exhausted"||J?.reason==="budget-spent"),H=(K)=>{return(typeof Z.rowReservePercent==="function"?Z.rowReservePercent(K):Z.rowReservePercent?.get(K.id))??Z.reservePercent??{}},Q=Z.scope,D=Z.rows.map((K,q)=>({row:K,configuredOrder:q})).filter(({row:K})=>!Y.has(K.id)).map(({row:K,configuredOrder:q})=>{let P=Z.killswitch?.get(K.id),L=Z.resetCreditsApplicable?.get(K.id);return{accountId:K.id,quota:K.kind==="api-key"?void 0:z.get(K.id)?.projection??A(K.quota,Q),reservePercent:H(K),configuredOrder:q,...L===void 0?{}:{resetCreditsApplicable:L},...P===void 0?{}:{killswitchPasses:P}}}),V=[],j=B?{action:"retain"}:Z.pin?{action:"clear"}:{action:"none"};while(D.length>0){let K=m6({candidates:D,pendingBytes:Z.pendingBytes??new Map,requestBytes:Z.requestBytes,now:Z.now,...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}});if(!K)break;let q=X.get(K.accountId);if(q){V.push(q),D=D.filter((L)=>L.accountId!==K.accountId);continue}let P=Z.identities?.get(K.accountId);return{outcome:"dispatch",accountId:K.accountId,source:K.source,...K.quotaCheckedAt===void 0?{}:{quotaCheckedAt:K.quotaCheckedAt},pin:B&&!W?{action:"retain"}:{action:"assign",pin:{accountId:K.accountId,inputBytes:Z.requestBytes,...P===void 0?{}:{wireIdentity:P},...K.quotaCheckedAt===void 0?{}:{quotaCheckedAt:K.quotaCheckedAt}}},refusedSelections:V,admission:$}}return{outcome:"no-admissible-account",pin:j,refusedSelections:V,admission:$}}import{createHash as d8}from"node:crypto";var c8=86400000,u8=300000,i8=3600000,s8=60000,n8=900000,a8=300000;function C3(Z){return Z instanceof Error?Z.message:String(Z)}function o8(Z){let $=Z?.status;if(typeof $==="number")return $===429||$>=500;if(!(Z instanceof Error))return!1;return Z.name==="AbortError"||Z.name==="TimeoutError"||Z.message.includes("fetch failed")||"code"in Z&&(Z.code==="ECONNRESET"||Z.code==="ECONNREFUSED"||Z.code==="ETIMEDOUT"||Z.code==="UND_ERR_CONNECT_TIMEOUT")}function b3(Z){let $=C3(Z),z=Z?.status;if(typeof z==="number")return z===429||z>=500;if(!(Z instanceof Error))return!1;let X=Z.code;return Z.name==="AbortError"||Z.name==="TimeoutError"||$.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function v6(Z){return d8("sha256").update(Z).digest("hex")}function g6(Z){let $=v6(Z.refreshToken),X=(Z.previous?.tokenHash===$?Z.previous.retryCount??0:0)+1,Y,G=Z.error?.retryAfter;if(typeof G==="number"&&G>0)Y=G*1000;else if(o8(Z.error))Y=Math.min(i8,u8*2**Math.min(X-1,6));else Y=c8;return{message:C3(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+Y,retryCount:X,tokenHash:$}}function r(Z,$,z){if(!Z?.nextRetryAt||Z.nextRetryAt<=z)return!1;if(!$)return!0;return Z.tokenHash===v6($)}function gZ(Z,$){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((Z.nextRetryAt??$)-$)/1000))}s after: ${Z.message}`}function qZ(Z){let z=(Z.previous?.retryCount??0)+1,X,Y=Z.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(b3(Z.error))X=Math.min(n8,s8*2**Math.min(z-1,6));else X=a8;return{message:C3(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+X,retryCount:z}}function QZ(Z,$){if(!Z?.nextRetryAt||Z.nextRetryAt<=$)return!1;return!0}function A3(Z){if(!Z)return;let $=Number(Z);if(Number.isFinite($)&&$>0)return Math.ceil($);let z=Date.parse(Z);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{createServer as p6}from"node:http";import{setTimeout as r8}from"node:timers/promises";var cZ="app_EMoamEEZ73f0CkXaXp7hrann",ZZ="https://auth.openai.com",_Z=1455,t8=3000,e8="cortexkit-opencode-openai-auth";function u6(Z){return`${e8}/${Z}`}var i6="main",Z1=`"${i6}" is a reserved account id; choose a different label.`;function s6(Z){let $=new Uint8Array(Z),z=String.fromCharCode(...$);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function $1(){let $=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=s6(await crypto.subtle.digest("SHA-256",new TextEncoder().encode($)));return{verifier:$,challenge:z}}function l6(Z){if(Z.length>16384)return;let $=Z.split(".");if($.length!==3)return;let z=$[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function d6(Z){let $=Z.chatgpt_account_id;if(typeof $==="string"&&$.length>0)return $;let z=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=Z.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 lZ(Z){if(Z.id_token){let $=l6(Z.id_token),z=$&&d6($);if(z)return z}if(Z.access_token){let $=l6(Z.access_token);return $?d6($):void 0}return}function z1(Z){return typeof Z==="string"&&Z.toLowerCase()===i6}function I3(Z){if(z1(Z))throw Error(Z1);return Z}function X1(Z,$,z){let X=new URLSearchParams({response_type:"code",client_id:cZ,redirect_uri:Z,scope:"openid profile email offline_access",code_challenge:$.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:z,originator:"opencode"});return`${ZZ}/oauth/authorize?${X.toString()}`}async function Y1(Z,$,z){let X=await fetch(`${ZZ}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Z,redirect_uri:$,client_id:cZ,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function G1(Z){return Z.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var B1=`<!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>`,pZ=(Z)=>`<!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">${G1(Z)}</div>
|
|
85
|
+
</div>
|
|
86
|
+
</body>
|
|
87
|
+
</html>`,dZ=[],MZ,w=new Map;function c6(Z,$){return new Promise((z,X)=>{let Y=(B)=>{Z.off("listening",G),X(B)},G=()=>{Z.off("error",Y),z()};Z.once("error",Y),Z.once("listening",G),Z.listen(_Z,$)})}function n6(Z){Z.close(()=>{}),Z.closeIdleConnections?.(),setTimeout(()=>{Z.closeAllConnections?.()},25).unref?.()}function t(){return w.size}function $Z(Z){if(w.delete(Z),t()===0)e()}async function J1(){let Z=`http://localhost:${_Z}/auth/callback`;if(dZ.length>0)return{port:_Z,redirectUri:Z};if(MZ)return MZ;MZ=(async()=>{let $=(G,B)=>{let J=new URL(G.url||"/",`http://127.0.0.1:${_Z}`);if(J.pathname==="/auth/callback"){let W=J.searchParams.get("code"),H=J.searchParams.get("state"),Q=J.searchParams.get("error"),D=J.searchParams.get("error_description");if(Q){let j=D||Q;if(H){let K=w.get(H);if(K)K.reject(Error(j)),$Z(H);else if(t()===0)e()}else if(t()===0)e();B.writeHead(200,{"Content-Type":"text/html"}),B.end(pZ(j));return}if(!H){if(t()===0)e();B.writeHead(400,{"Content-Type":"text/html"}),B.end(pZ("Missing state parameter"));return}if(!W){if(t()===0)e();B.writeHead(400,{"Content-Type":"text/html"}),B.end(pZ("Missing authorization code"));return}let V=w.get(H);if(!V){if(t()===0)e();B.writeHead(400,{"Content-Type":"text/html"}),B.end(pZ("Unknown state — authorization may have expired"));return}$Z(H),Y1(W,Z,V.pkce).then((j)=>V.resolve(j)).catch((j)=>V.reject(j)),B.writeHead(200,{"Content-Type":"text/html"}),B.end(B1);return}if(J.pathname==="/cancel"){let W=J.searchParams.get("state"),H=W?[W]:[...w.keys()];B.writeHead(200),B.end("Login cancelled");for(let Q of H){let D=w.get(Q);if(!D)continue;D.reject(Error("Login cancelled")),$Z(Q)}if(t()===0)e();return}B.writeHead(404),B.end("Not found")},z=p6($);await c6(z,"127.0.0.1");let X=[z],Y=p6($);try{await c6(Y,"::1"),X.push(Y)}catch(G){let B=G.code;if(B!=="EADDRNOTAVAIL"&&B!=="EAFNOSUPPORT")throw n6(z),G}return dZ=X,{port:_Z,redirectUri:Z}})();try{return await MZ}finally{MZ=void 0}}function e(){let Z=dZ;dZ=[];for(let $ of Z)n6($)}function W1(Z,$,z=300000,X){return new Promise((Y,G)=>{if(X?.aborted){$Z($),G(Error("Login cancelled"));return}let B=setTimeout(()=>{if(w.get($))$Z($),G(Error("OAuth callback timeout — authorization took too long"))},z),J=()=>{if(clearTimeout(B),w.get($))$Z($),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",J);w.set($,{pkce:Z,state:$,resolve:(W)=>{if(clearTimeout(B),X)X.removeEventListener("abort",J);Y(W)},reject:(W)=>{if(clearTimeout(B),X)X.removeEventListener("abort",J);G(W)}})})}async function H1(Z){let $=await fetch(`${ZZ}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":u6(Z)},body:JSON.stringify({client_id:cZ})});if(!$.ok)throw Error("Failed to initiate device authorization");let z=await $.json();return{deviceData:z,url:`${ZZ}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function K1(Z,$,z){let X=Math.max(parseInt(Z.interval,10)||5,1)*1000,Y=typeof Z.expires_in==="number"?Z.expires_in:parseInt(Z.expires_in||"",10),G=!Number.isNaN(Y)&&Y>0?Y*1000:900000,B=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-B>G)throw Error("Device authorization expired");let J=await fetch(`${ZZ}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":u6($)},body:JSON.stringify({device_auth_id:Z.device_auth_id,user_code:Z.user_code})});if(J.ok){let Q=await J.json(),D=await fetch(`${ZZ}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Q.authorization_code,redirect_uri:`${ZZ}/deviceauth/callback`,client_id:cZ,code_verifier:Q.code_verifier}).toString()});if(!D.ok)throw Error(`Token exchange failed: ${D.status}`);return await D.json()}if(J.status!==403&&J.status!==404)throw Error(`Device authorization failed: ${J.status}`);let W=G-(Date.now()-B);if(W<=0)throw Error("Device authorization expired");let H=Math.min(X+t8,W);try{await r8(H,void 0,{signal:z})}catch(Q){if(Q instanceof Error&&Q.name==="AbortError")throw Error("Device authorization cancelled");throw Q}}}async function t0(Z){let{label:$,headless:z=!1,signal:X,version:Y}=Z;if(I3($),z){let{deviceData:Q,url:D,instructions:V}=await H1(Y),j=(async()=>{let K=await K1(Q,Y,X),q=Date.now(),P=lZ(K);return{id:I3($||P||crypto.randomUUID()),label:$||void 0,type:"oauth",access:K.access_token,refresh:K.refresh_token,expires:q+(K.expires_in??3600)*1000,enabled:!0,addedAt:q,lastUsed:q,lastRefreshedAt:q,accountId:P}})();return{url:D,instructions:V,completion:j}}let{redirectUri:G}=await J1(),B=await $1(),J=s6(crypto.getRandomValues(new Uint8Array(32)).buffer),W=X1(G,B,J),H=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let Q=await W1(B,J,void 0,X),D=Date.now(),V=lZ(Q);return{id:I3($||V||crypto.randomUUID()),label:$||void 0,type:"oauth",access:Q.access_token,refresh:Q.refresh_token,expires:D+(Q.expires_in??3600)*1000,enabled:!0,addedAt:D,lastUsed:D,lastRefreshedAt:D,accountId:V}}finally{$Z(J)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:H}}function uZ(Z){if(Z==null||Z==="")return;let $=typeof Z==="number"?Z:Number(Z);if(Number.isFinite($)){let X=$<100000000000?$*1000:$,Y=new Date(X);return Number.isNaN(Y.getTime())?void 0:Y.toISOString()}let z=new Date(Z);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function k3(Z){let $=Number(Z);return Number.isFinite($)&&$>0?$:void 0}function a6(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function o6(Z,$){let z=Z.get($);if(z===null||z.trim()==="")return;let X=Number(z);if(!Number.isFinite(X)||X<0||X>100)return;let Y=$.slice(0,-13),G=k3(Z.get(`${Y}-window-minutes`)),B=uZ(Z.get(`${Y}-reset-at`)??void 0);if(X===0&&Z.get(`${Y}-window-minutes`)==="0"&&!B)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:B,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var e6=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function Z$(Z,$){let z=Z.get($);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 Z4(Z){if(e6.some((Y)=>Z$(Z,Y)==="invalid"))return{};let $={},z=o6(Z,"x-codex-primary-used-percent");if(z)$.primary=z;let X=o6(Z,"x-codex-secondary-used-percent");if(X)$.secondary=X;return $}function $4(Z){let $=e6.map((z)=>Z$(Z,z));return $.includes("valid")&&!$.includes("invalid")}function r6(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=k3(Z.window_minutes),z=uZ(Z.reset_at);if(Z.used_percent===0&&$===void 0&&!z)return;return{usedPercent:Z.used_percent,remainingPercent:100-Z.used_percent,resetsAt:z,checkedAt:Date.now(),...$!==void 0?{windowMinutes:$}:{}}}function z4(Z){let $={},z=r6(Z.rate_limits?.primary);if(z)$.primary=z;let X=r6(Z.rate_limits?.secondary);if(X)$.secondary=X;return $}function VZ(Z){if(Z==null||Z==="")return;let $=Number(Z);return Number.isFinite($)&&$>=0?$:void 0}function t6(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=k3(Z.limit_window_seconds),z=uZ(Z.reset_at);if(Z.used_percent===0&&$===void 0&&!z)return;return{usedPercent:Z.used_percent,remainingPercent:100-Z.used_percent,resetsAt:z,checkedAt:Date.now(),...$!==void 0?{windowMinutes:$/60}:{}}}function $$(Z){let $={},z=t6(Z.rate_limit?.primary_window);if(z)$.primary=z;let X=t6(Z.rate_limit?.secondary_window);if(X)$.secondary=X;let Y=a6(Z.rate_limit_reset_credits?.available_count);if(Y!==void 0)$.resetCreditsAvailable=Y;let G=a6(Z.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)$.resetCreditsApplicable=G;let B=Z.spend_control?.individual_limit;if(Z.spend_control===null||B===null)$.spendControlCleared=!0;if(B&&typeof Z.spend_control?.reached==="boolean"){let W=VZ(B.limit),H=VZ(B.used),Q=VZ(B.remaining),D=VZ(B.used_percent),V=VZ(B.remaining_percent);if(W!==void 0&&H!==void 0&&Q!==void 0&&D!==void 0&&V!==void 0)$.spendControl={limit:W,used:H,remaining:Q,usedPercent:D,remainingPercent:V,resetsAt:uZ(B.reset_at),unit:B.unit,source:B.source,reached:Z.spend_control.reached}}let J=Z.credits;if(J&&typeof J.has_credits==="boolean"&&typeof J.unlimited==="boolean"&&typeof J.overage_limit_reached==="boolean"){let W=VZ(J.balance);$.credits={hasCredits:J.has_credits,unlimited:J.unlimited,overageLimitReached:J.overage_limit_reached,...W!==void 0?{balance:W}:{}}}return $}import{ClaustrumClient as s1}from"@cortexkit/claustrum-client";import{resolve as z$}from"node:path";import{storeIdentity as Q1}from"@cortexkit/claustrum-client";import{SubcClient as V1}from"@cortexkit/subc-client";function X$(Z){let $=Z.identity??Q1(Z.projectRoot??process.cwd(),Z.storagePath??process.cwd());return{connectionFile:Z.connectionFile,async getUsage(){let z,X=!1,Y,G=new Promise((J,W)=>{Y=setTimeout(()=>W(Error("insula usage timeout")),3000),Y.unref?.()}),B=(async()=>{if(z=Z.connector?await Z.connector({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}):await V1.connect({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}),X)throw z.close(),Error("insula usage timeout");let J=await z.routeOpen({kind:"management_surface",module_id:"insula"},$);return await z.request(J,{method:"usage.get",params:{}})})();try{return await Promise.race([B,G])}finally{X=!0,clearTimeout(Y),z?.close()}}}}var w3=60000,U1=4*w3,f3=new Map,iZ=new Map;function y3(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}class Y${transport;key;#Z=[];#$;constructor(Z,$){this.transport=Z,this.key=$}refresh(Z){if(this.#$)return this.#$;for(let[z,X]of iZ)if(Z-X>=w3)iZ.delete(z);let $=iZ.get(this.key);if($!==void 0&&Z-$<w3)return Promise.resolve();return iZ.set(this.key,Z),this.#$=(async()=>{try{let z=await this.transport.getUsage();if(!y3(z)||!Array.isArray(z.result)||z.error!==void 0)throw Error("unavailable insula usage");this.#Z=z.result.filter((X)=>y3(X)&&typeof X.provider==="string")}catch{this.#Z=[]}})().finally(()=>{this.#$=void 0}),this.#$}current(Z,$,z){for(let X of this.#Z){if(X.provider!==Z||typeof X.account!=="string"||X.account.trim()!==$)continue;if(X.stale!==void 0||X.errorClass!==void 0||!y3(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=U1)continue;return{entry:X,context:{fetchedAt:Y,...typeof X.source==="string"&&{source:X.source}}}}return}}function G$(Z,$){let z=JSON.stringify([z$(Z.connectionFile),z$($)]),X=f3.get(z);if(!X)X={source:new Y$(Z,z),refs:0},f3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)f3.delete(z)}}}import{ClaustrumCredentialError as t4}from"@cortexkit/claustrum-client";function h3(Z){let $=new AbortController,z=[],X=!1,Y=()=>{if(X)return;X=!0;for(let{source:J,listener:W}of z)J.removeEventListener("abort",W);z.length=0},G=(J)=>{if(X||$.signal.aborted)return;$.abort(J),Y()},B=Z.find((J)=>J.aborted);if(B)return $.abort(B.reason),{signal:$.signal,dispose:Y};for(let J of Z){if($.signal.aborted)break;let W=()=>G(J.reason);if(z.push({source:J,listener:W}),J.addEventListener("abort",W,{once:!0}),J.aborted)G(J.reason)}return{signal:$.signal,dispose:Y}}import{ClaustrumCredentialError as k1}from"@cortexkit/claustrum-client";import{createHash as D1,randomBytes as F1,randomUUID as N1}from"node:crypto";import{constants as B$}from"node:fs";import{chmod as j1,mkdir as q1,open as U$,readFile as m3,realpath as M1,rename as _1,stat as D$,unlink as F$}from"node:fs/promises";import{basename as N$,dirname as p,extname as J$,isAbsolute as W$,join as p3,resolve as P1}from"node:path";import{ClaustrumCredentialError as O1,ClaustrumClient as L1,writeEnrollmentTokenFile as S1}from"@cortexkit/claustrum-client";class F extends Error{kind;constructor(Z,$){super($);this.name="ClaustrumConsumerError",this.kind=Z}}var R1=1,nZ=16384,j$=30000,l3=/^[0-9a-f]{64}$/,q$=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),M$=new Set(["pending_queue_full"]);function v3(Z){if(!(Z instanceof O1))return;if(q$.has(Z.code))return{code:Z.code,disposition:"terminal"};if(M$.has(Z.code))return{code:Z.code,disposition:"retry"};return{code:Z.code,disposition:Z.action==="retry"?"retry":"terminal"}}function T1(Z,$){if(!/^[a-z0-9][a-z0-9-]*$/.test(Z)||!/^[a-z0-9][a-z0-9-]*$/.test($))throw new F("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${Z}-${$}`}function E1(Z){return L1.connect(Z)}function _$(Z){let $=J$(Z)||".json",z=N$(Z,J$(Z));return{statePath:p3(p(Z),`${z}-state${$}`),tokenPath:Z}}function x1(Z){let $=Z.override?.trim();if($&&!W$($)&&!Z.cwd)throw new F("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=$?W$($)?$:P1(Z.cwd,$):p3(Z.stateDir,`${Z.host}-enrollment.json`);return _$(z)}function P$(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function sZ(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0}function O$(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=1}function PZ(){return new F("invalid-state","invalid Claustrum enrollment state")}function rZ(Z){if(!P$(Z)||Z.version!==R1||typeof Z.proposedName!=="string"||Z.proposedName.length===0)throw PZ();if(Z.phase==="pending"){if(!l3.test(String(Z.requestSecret??""))||Z.requestId!==void 0&&(typeof Z.requestId!=="string"||Z.requestId.length===0)||!sZ(Z.createdAt)||!sZ(Z.updatedAt))throw PZ();return{version:1,phase:"pending",proposedName:Z.proposedName,requestSecret:Z.requestSecret,...Z.requestId!==void 0&&{requestId:Z.requestId},createdAt:Z.createdAt,updatedAt:Z.updatedAt}}if(Z.phase==="approved"){if(Z.approvedName!==void 0&&(typeof Z.approvedName!=="string"||Z.approvedName.length===0)||!O$(Z.tokenGeneration)||!sZ(Z.updatedAt))throw PZ();return{version:1,phase:"approved",proposedName:Z.proposedName,...Z.approvedName!==void 0&&{approvedName:Z.approvedName},tokenGeneration:Z.tokenGeneration,updatedAt:Z.updatedAt}}if(Z.phase==="denied"||Z.phase==="blocked"){if(Z.errorCode!==void 0&&typeof Z.errorCode!=="string"||!sZ(Z.updatedAt))throw PZ();return{version:1,phase:Z.phase,proposedName:Z.proposedName,...Z.errorCode!==void 0&&{errorCode:Z.errorCode},updatedAt:Z.updatedAt}}throw PZ()}function d3(Z){if(!P$(Z)||!l3.test(String(Z.token??""))||!O$(Z.token_generation))throw new F("invalid-token","invalid Claustrum enrollment token file");return{token:Z.token,token_generation:Z.token_generation}}function C1(Z){if(!Z.isFile())throw new F("unsafe-file","Claustrum enrollment file must be a regular file");if((Z.mode&63)!==0)throw new F("unsafe-file","Claustrum enrollment file must be owner-only");let $=process.geteuid?.();if($!==void 0&&Z.uid!==$)throw new F("unsafe-file","Claustrum enrollment file must be owned by the current user")}function H$(Z){try{return JSON.parse(Z)}catch{throw new F("invalid-state","Claustrum enrollment file is not valid JSON")}}async function l(Z){if(XZ)try{await g3(p(Z));let z=await oZ(Z,!0);if(Buffer.byteLength(z)>nZ)throw new F("unsafe-file","Claustrum enrollment file is too large");return H$(z)}catch(z){if(z.code==="ENOENT")return;throw z}let $;try{$=await U$(Z,B$.O_RDONLY|B$.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new F("unsafe-file","Claustrum enrollment file could not be opened safely")}try{C1(await $.stat());let z=Buffer.alloc(nZ+1),{bytesRead:X}=await $.read(z,0,z.byteLength,0);if(X>nZ)throw new F("unsafe-file","Claustrum enrollment file is too large");return H$(z.subarray(0,X).toString("utf8"))}finally{await $.close()}}function K$(Z,$){let z=[];for(let X of Z.split(`
|
|
88
|
+
`)){if(X.trim()===""||X.startsWith("#"))continue;let Y=X.split(":");if(Y.length!==$||!/^[^\s:,]+$/.test(Y[0]??"")||!/^\d+$/.test(Y[2]??"")||!Number.isSafeInteger(Number(Y[2]))||$===7&&(!/^\d+$/.test(Y[3]??"")||!Number.isSafeInteger(Number(Y[3])))||$===4&&Y[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(Y[3]??""))return;z.push(Y)}return z}async function b1(Z,$,z){try{let[X,Y]=await Promise.all([m3(z.passwdPath??"/etc/passwd","utf8"),m3(z.groupPath??"/etc/group","utf8")]),G=K$(X,7),B=K$(Y,4);if(!G||!B)return!1;let J=G.filter((D)=>Number(D[2])===Z),W=B.filter((D)=>Number(D[2])===$);if(J.length!==1||W.length!==1)return!1;let H=J[0]?.[0],Q=W[0]?.[3]??"";return(Q===""||Q.split(",").every((D)=>D===H))&&!G.some((D)=>Number(D[2])!==Z&&Number(D[3])===$)}catch{return!1}}function L$(Z){if(!Z.passwdPath&&!Z.groupPath)return;return{fs:{readFile:($)=>m3($==="/etc/passwd"?Z.passwdPath??$:$==="/etc/group"?Z.groupPath??$:$)}}}async function S$(Z,$={}){if(!XZ){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await M1(Z)}catch{return}let G;for(;;){let B=await D$(Y).catch(()=>{return});if(B&&(B.mode&18)!==0&&(B.mode&512)===0){if(G===void 0)G=X!==void 0&&await b1(z,X,$);if((B.mode&2)!==0||B.uid!==z||B.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 J=p(Y);if(J===Y)return;Y=J}}try{await Q$(Z,L$($))}catch(z){if(!(z instanceof E3))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 aZ(Z,$={}){if(XZ){await g3(Z,!1,L$($));return}await q1(Z,{recursive:!0,mode:448});let z=await D$(Z),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new F("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((z.mode&63)!==0)await j1(Z,448)}async function zZ(Z,$,z={}){let X=p(Z);await aZ(X,z),await S$(X,z);let Y=`${JSON.stringify($)}
|
|
89
|
+
`;if(Buffer.byteLength(Y)>nZ)throw new F("invalid-state","Claustrum enrollment state is too large");if(XZ)return V$(Z,Y);let G=p3(X,`.${N$(Z)}.${process.pid}.${N1()}.tmp`),B,J=!1;try{B=await U$(G,"wx",384),J=!0,await B.writeFile(Y,"utf8"),await B.chmod(384),await B.sync(),await B.close(),B=void 0,await _1(G,Z),J=!1}finally{if(await B?.close().catch(()=>{}),J)await F$(G).catch(()=>{})}}async function c3(Z,$){let z=await l(Z.tokenPath),X=z===void 0?void 0:d3(z),Y=await l(Z.statePath),G=Y===void 0?void 0:rZ(Y);if(X)return{state:"approved",proposedName:G?.proposedName??$,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:X.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return g(G)}async function A1(Z,$){let z;try{z=await c3(Z,$)}catch(X){if(!(X instanceof F)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await l(Z.statePath);if(Y===void 0)return"unreadable";let G=rZ(Y);return G.phase==="approved"&&G.proposedName===$?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in z&&z.proposedName!==$)return"unreadable";if(z.state==="approved"||z.state==="blocked"&&z.code==="missing_token")return"vault";return"local"}async function YZ(Z){let $=await l(Z);if($===void 0)throw new F("not-enrolled","Claustrum enrollment is not configured");return d3($)}function g(Z){if(Z.phase==="pending")return{state:"pending",proposedName:Z.proposedName,...Z.requestId!==void 0&&{requestId:Z.requestId}};if(Z.phase==="approved")return{state:"approved",proposedName:Z.proposedName,...Z.approvedName!==void 0&&{approvedName:Z.approvedName},tokenGeneration:Z.tokenGeneration};if(Z.phase==="denied")return{state:"denied",proposedName:Z.proposedName};return{state:"blocked",proposedName:Z.proposedName,code:Z.errorCode??"unknown"}}function R$(){return new F("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class T${#Z;#$;#G;#X;#H;#B;#z;constructor(Z){this.#z=Z.ancestorOptions??{},this.#Z=Z.client,this.#$=Z.paths,this.#G=Z.proposedName,this.#X=Z.now??Date.now,this.#H=Z.mintSecret??(()=>F1(32).toString("hex")),this.#B=Z.writeTokenFile??S1}async status(){return c3(this.#$,this.#G)}async resetTerminal(){return E$(this.#$,this.#G)}async#J(Z,$){let z={version:1,phase:"blocked",proposedName:Z.proposedName,errorCode:$,updatedAt:this.#X()};return await zZ(this.#$.statePath,z,this.#z),g(z)}async reconcile(){await aZ(p(this.#$.statePath),this.#z);let Z=await E({name:"ceremony",path:this.#$.statePath,ttlMs:j$,renew:!0});if(!Z)return{state:"busy"};try{let $=await l(this.#$.tokenPath),z=$===void 0?void 0:d3($),X=await l(this.#$.statePath),Y=X===void 0?void 0:rZ(X);if(Y&&Y.proposedName!==this.#G)throw R$();if(z){if(!Y||Y.phase==="pending"){let B={version:1,phase:"approved",proposedName:Y?.proposedName??this.#G,tokenGeneration:z.token_generation,updatedAt:this.#X()};await zZ(this.#$.statePath,B,this.#z),Y=B}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 B={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await zZ(this.#$.statePath,B,this.#z),g(B)}if(Y&&Y.phase!=="pending")return g(Y);if(!Y){let B=this.#X();if(Y={version:1,phase:"pending",proposedName:this.#G,requestSecret:this.#H(),createdAt:B,updatedAt:B},!l3.test(Y.requestSecret))throw new F("invalid-state","invalid minted Claustrum enrollment secret");await zZ(this.#$.statePath,Y,this.#z)}if(!Y.requestId)try{let B=D1("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),J=await this.#Z.enrollPropose({name:Y.proposedName,requestSecretHash:B});Y={...Y,requestId:J.requestId,updatedAt:this.#X()},await zZ(this.#$.statePath,Y,this.#z)}catch(B){let J=v3(B);if(!J)throw B;if(J.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:J.code};return this.#J(Y,J.code)}let G=Y.requestId;if(!G)return g(Y);try{let B=await this.#Z.enrollPoll({requestId:G,requestSecret:Y.requestSecret});if(B.status==="pending")return g(Y);if(B.status==="denied"){let W={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#X()};return await zZ(this.#$.statePath,W,this.#z),g(W)}await aZ(p(this.#$.tokenPath),this.#z),await S$(p(this.#$.tokenPath),this.#z),await this.#B(this.#$.tokenPath,{token:B.token,token_generation:B.tokenGeneration});let J={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:B.name,tokenGeneration:B.tokenGeneration,updatedAt:this.#X()};return await zZ(this.#$.statePath,J,this.#z),g(J)}catch(B){let J=v3(B);if(!J)throw B;if(J.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:G,retryCode:J.code};return this.#J(Y,J.code)}}finally{await Z.release()}}}async function E$(Z,$){await aZ(p(Z.statePath));let z=await E({name:"ceremony",path:Z.statePath,ttlMs:j$,renew:!0});if(!z)return"busy";try{if(await l(Z.tokenPath)!==void 0)return"refused-approved";let X=await l(Z.statePath);if(X===void 0)return"idle";let Y=rZ(X);if(Y.proposedName!==$)throw R$();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await F$(Z.statePath),"reset"}finally{await z.release()}}var OZ="claustrum-tombstone:v1:";function tZ(Z){return`${OZ}${Z}`}function u3(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function eZ(Z){return typeof Z==="string"&&Z.startsWith(OZ)}function x$(Z,$){if(!u3(Z)||Z.type!=="oauth")return!1;return Z.refresh===tZ($)}function C$(Z,$){if(x$(Z,$))return"placeholder";if(u3(Z)&&Z.type==="oauth"&&typeof Z.refresh==="string"&&Z.refresh.length>0&&!eZ(Z.refresh))return"login";if(u3(Z)&&Z.type==="api"&&typeof Z.key==="string"&&Z.key.length>0)return"login";return"empty"}function I1(Z){let $=C$(Z.auth,Z.provider);if(Z.mode==="custody"&&$==="login")throw new F("host-slot-login",`${Z.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if(Z.mode==="local"&&$==="placeholder")throw new F("host-slot-placeholder",`${Z.provider} host slot holds the vault placeholder; sign in to use local accounts`);return $}function b$(Z,$){return $!==void 0&&$.credentialId===Z.credentialId&&$.accountIdentity===Z.accountIdentity&&$.recordVersion!==Z.recordVersion}function f1(Z,$){if($===void 0)return"reauthorize-failed";if($.credentialId!==Z.credentialId)return"credential-changed";if($.accountIdentity!==Z.accountIdentity)return"account-changed";if($.recordVersion===Z.recordVersion)return"version-unchanged";return"rotated"}var A$=I("claustrum");function n3(Z,$,z,X=A$){let Y=b$($,z);return X.debug("scoped 401 re-authorized",{site:Z,credentialId:$.credentialId,servedVersion:$.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:f1($,z)}),Y}var s3=300000;function i3(){return new F("invalid-material","Claustrum returned invalid credential material")}function y1(Z){let $=Z.trim();if($.startsWith("{")){let z;try{z=JSON.parse($)}catch{throw i3()}if(!z||typeof z!=="object")throw i3();let X=z,Y=X.access_token??X.access;$=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test($)||$.startsWith(OZ))throw i3();return $}function w1(Z,$){if(!Z.operations.includes("read"))return;if(!Z.categories.includes($.category))return;if(Z.credentialType==="oauth")return Z.refreshAdapter===$.refreshAdapter?"oauth":void 0;if(Z.credentialType==="api_key"&&$.apiKeys)return Z.refreshAdapter===void 0?"api_key":void 0;return}class Z3{#Z;#$;#G;#X;#H;#B;#z;#J=new WeakMap;#V=new WeakMap;#W=!1;constructor(Z){let $=Z.tokenPath;if(Z.readToken)this.#$=Z.readToken;else if($)this.#$=()=>YZ($);else throw new F("not-enrolled","Claustrum enrollment token path is required");this.#Z=Z.client,this.#X=Z.family,this.#H=Z.parseIdentity,this.#B=Z.requireAssertion??!1,this.#G=Z.now??Date.now,this.#z=Z.logger??A$}#Y(Z){if(this.#W)throw new F("closed","Claustrum scoped custody is closed");Z?.throwIfAborted()}async#K(Z){this.#Y(Z);let $=await this.#$();if(this.#Y(Z),!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new F("invalid-token","Invalid Claustrum enrollment token");return $.token}async#Q(Z,$){this.#Y($);let z,X;try{let Y=Z();z=$?await Promise.race([Y,new Promise((G,B)=>{let J=()=>B($.reason);if($.addEventListener("abort",J,{once:!0}),X=()=>$.removeEventListener("abort",J),$.aborted)J()})]):await Y}catch(Y){if(this.#Y($),Y instanceof k1)throw Y;throw new F("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#Y($),z}async discover(Z){let $=await this.#K(Z),z=await this.#Q(()=>this.#Z.listScoped($),Z),X=[],Y=[],G=new Map;for(let J of z.rows){let W=w1(J,this.#X);if(!W)continue;Y.push({row:J,type:W}),G.set(J.id,(G.get(J.id)??0)+1)}let B=[];for(let{row:J,type:W}of Y){let H;if(!J.id.trim())H="empty credential id";else if((G.get(J.id)??0)>1)H="duplicate credential id";else if(J.accountId!==void 0&&!J.accountId.trim())H="blank account identity";else if(!J.state.trim())H="empty state";if(H){X.push({...J.id.trim()&&{credentialId:J.id},reason:H});continue}B.push(Object.freeze({credentialId:J.id,credentialType:W,...J.accountId!==void 0&&{accountIdentity:J.accountId},state:J.state,...J.email!==void 0&&{email:J.email},...J.orgName!==void 0&&{orgName:J.orgName}}))}for(let J of X)this.#z.warn("skipped malformed vault record",J);return{view:z.view,credentials:Object.freeze(B),skipped:Object.freeze(X)}}async authorize(Z,$){if(!Z.credentialId)throw new F("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:Y}=Z;if(this.#B&&Y===void 0)throw new F("identity-unasserted","Claustrum dispatch requires a known account identity");let G=await this.#K($),B=await this.#Q(()=>this.#Z.getScoped({credentialId:z,enrollmentToken:G,...X==="oauth"&&{minTtlMs:s3}}),$);if(B.credentialId!==void 0&&B.credentialId!==z)throw new F("identity-changed","Claustrum served credential identity changed");let J=B.expiresAtMs;if(!Number.isSafeInteger(B.recordVersion)||B.recordVersion<0||J===null&&X==="oauth"||J!==null&&(!Number.isFinite(J)||J-this.#G()<s3))throw new F("insufficient-validity","Claustrum served credential has insufficient validity");let W=y1(B.material),H=B.accountId?.trim()?B.accountId:void 0;if(this.#B&&(B.credentialId===void 0||H===void 0))throw new F("identity-unasserted","Claustrum served credential did not assert its identity");let Q=H===void 0?this.#H?.(W):void 0,D=H??Q;if(Y!==void 0&&D!==void 0&&D!==Y)throw new F("identity-changed","Claustrum served credential identity changed");let V=D??Y,K=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...V!==void 0&&{accountIdentity:V},accountIdentitySource:H!==void 0?"asserted":Q!==void 0?"parsed":Y!==void 0?"expected":"none",...Y!==void 0&&{expectedAccountIdentity:Y},...B.credentialId!==void 0&&{assertedCredentialId:B.credentialId},...H!==void 0&&{assertedAccountIdentity:H},...B.projectId!==void 0&&{projectId:B.projectId},recordVersion:B.recordVersion,expiresAtMs:J},"accessToken",{value:W,enumerable:!1}));return this.#J.set(K,G),K}async reportFailure(Z,$,z){if($!==401)return;this.#Y();let X=this.#J.get(Z);if(!X)throw new F("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#V.get(Z);if(Y)return Y;let G=this.#Q(()=>this.#Z.reportAuthFailureScoped({credentialId:Z.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:Z.recordVersion,reporterSource:z}));this.#V.set(Z,G);try{await G,this.#z.debug("scoped 401 reported",{credentialId:Z.credentialId,recordVersion:Z.recordVersion,reporterSource:z})}catch(B){throw this.#V.delete(Z),B}}close(){if(this.#W)return;this.#W=!0,this.#Z.close()}}import{createHash as h1}from"node:crypto";function I$(Z,$,z){if(Z.accountIdentity!==void 0&&z!==void 0)return Z.accountIdentity===z;return Z.credentialId===$}function a3(Z,$,z){return Z.some((X)=>I$(X,$,z))}function o3(Z,$,z){let X={credentialId:$,...z!==void 0&&{accountIdentity:z}};return[...Z.filter((Y)=>Y.credentialId!==$||Y.accountIdentity!==z),X]}function r3(Z,$,z){return Z.filter((X)=>!$.some((Y)=>I$(X,Y,z)))}var f$="vault:";function m1(Z){return h1("sha256").update(Z).digest("hex")}function v1(Z){let $=Z.credentialId.split(":");return($.length>=3?$.slice(2).join(":").trim():void 0)||Z.email||Z.credentialId}function g1(Z){return Z.identity!==void 0?`identity:${Z.identity}`:`credential:${Z.credential.credentialId}`}function d(Z){return[Z.credentialId,...Z.aliases??[]]}function y$(Z,$,z={}){let X=z.now??Date.now(),Y=z.routePrefix??f$,G=z.reservedRouteIds??new Set,B=Z?.rows??[],J=[...Z?.declined??[]],W=$.skipped.length===0,H=new Set($.credentials.map((U)=>U.credentialId)),Q=new Set($.skipped.flatMap((U)=>U.credentialId===void 0?[]:[U.credentialId])),D=$.skipped.some((U)=>U.credentialId===void 0),V=(U)=>!H.has(U)&&(Q.has(U)||D),j=new Map;for(let U of B){if(U.accountIdentity===void 0)continue;for(let M of d(U))if(!j.has(M))j.set(M,U.accountIdentity)}let K=new Map;for(let U of $.credentials){let M=U.accountIdentity!==void 0?{credential:U,identity:U.accountIdentity,claimed:!0}:{credential:U,identity:j.get(U.credentialId),claimed:!1},m=g1(M),v=K.get(m)??[];v.push(M),K.set(m,v)}let q=new Set,P=new Set(G),L=[],IZ=(U,M)=>U.credential.credentialId.localeCompare(M.credential.credentialId),FZ=[...K.values()].map((U)=>U.toSorted(IZ)).sort((U,M)=>U[0]&&M[0]?IZ(U[0],M[0]):0);for(let U of FZ){let M=U[0]?.identity,m=U.filter((_)=>_.credential.state==="active"),v=m.length?m:U,H3=v.filter((_)=>_.claimed),kZ=H3.length?H3:v,K3=new Set(U.map((_)=>_.credential.credentialId)),N6=B.find((_)=>!q.has(_)&&d(_).some((WZ)=>K3.has(WZ))&&(_.accountIdentity===void 0||_.accountIdentity===M)),Q3=kZ.find((_)=>_.credential.credentialId===N6?.credentialId)??kZ[0];if(!Q3)continue;let T=Q3.credential,b=N6??(M===void 0?void 0:B.find((_)=>!q.has(_)&&_.accountIdentity===M));if(b)q.add(b);let s=b?.routeId;if(!s||G.has(s)){let _=`${Y}${T.credentialId}${M===void 0?"":`~${m1(M).slice(0,10)}`}`;s=_;for(let WZ=2;P.has(s);WZ++)s=`${_}~${WZ}`}P.add(s);let _8=b?d(b).filter(V):[],V3=[...new Set([...U.map((_)=>_.credential.credentialId),..._8])].filter((_)=>_!==T.credentialId).sort((_,WZ)=>_.localeCompare(WZ)),P8=z.mapAccount?.(T)??{};L.push({previousIndex:b?B.indexOf(b):1/0,row:{routeId:s,credentialId:T.credentialId,credentialType:T.credentialType,...M!==void 0&&{accountIdentity:M},...V3.length&&{aliases:V3},state:T.state,label:P8.label?.trim()||v1(T),...T.email!==void 0&&{email:T.email},...T.orgName!==void 0&&{orgName:T.orgName},enabled:![T.credentialId,...V3].some((_)=>a3(J,_,M)),addedAt:b?.addedAt??X,...b?.quota!==void 0&&{quota:b.quota},...!Q3.claimed&&M!==void 0&&{unclaimed:!0}}})}return B.forEach((U,M)=>{if(q.has(U)||!d(U).some(V))return;if(P.has(U.routeId))return;let[m,...v]=d(U).filter((K3)=>!H.has(K3));if(m===void 0)return;P.add(U.routeId);let{aliases:H3,...kZ}=U;L.push({previousIndex:M,row:{...kZ,credentialId:m,...v.length&&{aliases:v},stale:!0}})}),L.sort((U,M)=>U.previousIndex===M.previousIndex?U.row.credentialId.localeCompare(M.row.credentialId):U.previousIndex-M.previousIndex),{version:1,view:$.view,complete:W,...!W&&{rejected:$.skipped.map((U)=>({...U.credentialId!==void 0&&{credentialId:U.credentialId},reason:U.reason}))},rows:L.map((U)=>U.row),declined:J}}function t3(Z){return(Z?.rows??[]).filter(($)=>$.enabled&&$.state==="active").map(($)=>({id:$.routeId,kind:$.credentialType==="oauth"?"oauth":"api-key",...$.quota!==void 0&&{quota:$.quota}}))}function LZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function UZ(Z){return Z===void 0||typeof Z==="string"}function p1(Z){let $=LZ(Z)?o(Z.quota):void 0;if(!LZ(Z)||typeof Z.routeId!=="string"||typeof Z.credentialId!=="string"||Z.credentialType!=="oauth"&&Z.credentialType!=="api_key"||typeof Z.state!=="string"||typeof Z.label!=="string"||typeof Z.enabled!=="boolean"||typeof Z.addedAt!=="number"||!UZ(Z.accountIdentity)||!UZ(Z.email)||!UZ(Z.orgName)||Z.aliases!==void 0&&(!Array.isArray(Z.aliases)||!Z.aliases.every((z)=>typeof z==="string"))||Z.quota!==void 0&&$===void 0||Z.stale!==void 0&&Z.stale!==!0||Z.unclaimed!==void 0&&Z.unclaimed!==!0)return;return{...Z,...$===void 0?{}:{quota:$}}}var l1=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function k$(Z){if(!Array.isArray(Z))return;let $=[];for(let z of Z){if(!LZ(z)||!UZ(z.credentialId)||typeof z.reason!=="string"||!l1.has(z.reason))return;$.push(z)}return $}function d1(Z){if(!LZ(Z)||Z.version!==1||!UZ(Z.view)||!Array.isArray(Z.rows)||!Array.isArray(Z.declined)||Z.complete!==void 0&&typeof Z.complete!=="boolean"||Z.rejected!==void 0&&!k$(Z.rejected))throw new F("invalid-state","Claustrum roster file is not valid");let $=[];for(let Y of Z.rows){let G=p1(Y);if(!G)throw new F("invalid-state","Claustrum roster file is not valid");$.push(G)}let z=[];for(let Y of Z.declined){if(!LZ(Y)||typeof Y.credentialId!=="string"||!UZ(Y.accountIdentity))throw new F("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=k$(Z.rejected);return{version:1,...typeof Z.view==="string"&&{view:Z.view},complete:Z.complete!==!1,...X&&{rejected:X},rows:$,declined:z}}async function k(Z){let $;try{$=await oZ(Z,XZ)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse($)}catch{throw new F("invalid-state","Claustrum roster file is not valid")}return d1(z)}var c1={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},u1={name:"claustrum-roster",ttlMs:30000};async function DZ(Z,$,z={}){return x3(Z,c1,async(X)=>{let Y=await k(Z),{next:G,result:B}=await $(Y,{assertOwned:()=>X.assertOwned()});if(G)await X.assertOwned(),await y(Z,G,{beforeRename:async()=>{await z.beforePublish?.(),await X.assertOwned()}});return B})}function e3(Z,$){return DZ(Z,(z)=>{let X=z?.rows.find((G)=>G.routeId===$);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");let Y=o3(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 Z6(Z,$){return DZ(Z,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===$);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:r3(z.declined,d(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function i1(Z,$){if(!d(Z).includes($.credentialId))return"refuse";if(Z.unclaimed&&($.accountIdentitySource==="expected"||$.accountIdentitySource==="none"))return"refuse";if(Z.accountIdentity===$.accountIdentity)return"hold";if(Z.accountIdentity===void 0&&$.expectedAccountIdentity===void 0&&$.accountIdentity!==void 0&&($.accountIdentitySource==="asserted"||$.accountIdentitySource==="parsed")&&d(Z).length===1)return"bind";return"refuse"}function $6(Z,$){return DZ(Z,(z)=>{let X=z?.rows.find((J)=>J.routeId===$.routeId),Y=!z||!X?"refuse":i1(X,$);if(!z||!X||Y==="refuse")return{result:!1};let G=KZ(X.quota,$.observation),B=Y==="bind"?{accountIdentity:$.accountIdentity,unclaimed:!0}:{};return{next:{...z,rows:z.rows.map((J)=>J===X?{...J,...B,quota:G}:J)},result:!0}})}function z6(Z,$){return DZ(Z,(z)=>{let X=z?.rows.find((G)=>G.routeId===$.routeId);if(!z||!X||X.accountIdentity===void 0||X.accountIdentity!==$.accountIdentity)return{result:!1};let Y=KZ(X.quota,$.observation);return{next:{...z,rows:z.rows.map((G)=>G===X?{...G,quota:Y}:G)},result:!0}})}async function X6(Z){Z.signal?.throwIfAborted();let $=async()=>await Z.isActive?.()??!0;if(!await $())return;let z=await E({...u1,path:Z.path,renew:!0});if(!z){let X=await k(Z.path);if(Z.signal?.throwIfAborted(),!X?.view)throw new F("roster-busy","Claustrum account discovery is already in progress");return X}try{let X=await Z.custody.discover(Z.signal);return Z.signal?.throwIfAborted(),await DZ(Z.path,async(Y)=>{if(!await $())return{result:void 0};Z.signal?.throwIfAborted(),await z.assertOwned();let G=typeof Z.projection==="function"?Z.projection():Z.projection,B=y$(Y,X,G);return{...JSON.stringify(Y)!==JSON.stringify(B)&&{next:B},result:B}})}finally{await z.release()}}class w${#Z;#$=new AbortController;#G;#X;#H;#B;#z;#J;#V=!1;#W;constructor(Z){this.#Z=Z,this.#G=Z.logger??I("claustrum")}#Y(Z){this.#$.signal.throwIfAborted(),Z?.throwIfAborted()}async#K(){return await this.#Z.isCustodyActive?.()??!0}#Q(Z,$){let z=h3([this.#$.signal,...$?[$]:[]]);return new Promise((X,Y)=>{let G=()=>{z.signal.removeEventListener("abort",B),z.dispose()},B=()=>{G(),Y(z.signal.reason)};if(z.signal.addEventListener("abort",B,{once:!0}),Z.then((J)=>{if(G(),z.signal.aborted)Y(z.signal.reason);else X(J)},(J)=>{G(),Y(J)}),z.signal.aborted)B()})}async#U(){if(this.#Y(),this.#X)return this.#X;if(!this.#H)this.#H=this.#Z.connect().then((Z)=>{if(this.#$.signal.aborted)Z.close(),this.#Y();if(this.#X=new Z3({client:Z,family:this.#Z.family,tokenPath:this.#Z.tokenPath,parseIdentity:this.#Z.parseIdentity,requireAssertion:this.#Z.requireAssertion,now:this.#Z.now,logger:this.#G}),this.#Z.insula&&Z.insula)this.#W=G$(Z.insula,this.#Z.tokenPath);return this.#X}).finally(()=>{this.#H=void 0});return this.#Q(this.#H)}snapshot(){return this.#z}routingRows(){return t3(this.#z)}refresh(){if(this.#Y(),this.#B)return this.#B;return this.#B=(async()=>{if(!await this.#K()){this.#z=void 0,this.#X?.close(),this.#X=void 0,this.#W?.release(),this.#W=void 0;return}let Z=await this.#U(),$=await X6({path:this.#Z.rosterPath,custody:Z,isActive:()=>this.#K(),signal:this.#$.signal,projection:()=>({reservedRouteIds:new Set(this.#Z.reservedRouteIds?.()??[]),routePrefix:this.#Z.routePrefix,mapAccount:this.#Z.mapAccount,now:(this.#Z.now??Date.now)()})});this.#Y();let z=$?.view!==this.#z?.view;if(this.#z=$,$&&z)this.#Z.onRoster?.($);return $})().finally(()=>{this.#B=void 0}),this.#B}start(){if(this.#V)return;this.#Y(),this.#V=!0;let Z=async()=>{try{await this.refresh(),await this.refreshInsulaQuota()}catch(z){if(!this.#$.signal.aborted)this.#Z.onError?.(z)}if(this.#$.signal.aborted)return;let $=this.#Z.pollIntervalMs??5000;if($<=0)return;this.#J=(this.#Z.setTimeoutImpl??setTimeout)(()=>{this.#J=void 0,Z()},$),this.#J.unref?.()};Z()}async refreshInsulaQuota(){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#K())return;try{await YZ(this.#Z.tokenPath),await this.#U(),await this.#W?.source.refresh((this.#Z.now??Date.now)())}catch{}}async cachedInsulaQuota(Z){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#K())return;try{return await YZ(this.#Z.tokenPath),this.#D(Z.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute(Z){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#K())return;try{await YZ(this.#Z.tokenPath);let z=(await k(this.#Z.rosterPath))?.rows.find((X)=>X.routeId===Z);return this.#D(z?.accountIdentity)}catch{return}}#D(Z){if(!this.#Z.insula||!Z)return;let $=this.#W?.source.current(this.#Z.insula.provider,Z,(this.#Z.now??Date.now)());return $?this.#Z.insula.normalize($.entry,$.context):void 0}async authorize(Z,$){this.#Y($);let z=this.#z??await this.#Q(this.refresh(),$);if(!z||!await this.#K())throw new F("not-active","Claustrum scoped custody is not active");let X=await k(this.#Z.rosterPath);this.#Y($);let Y=z.rows.find((W)=>W.routeId===Z),G=X?.rows.find((W)=>W.routeId===Z);if(G&&!G.enabled)throw new F("route-declined","Claustrum route is disabled");if(!Y||!G||G.state!=="active"||G.credentialId!==Y.credentialId||G.accountIdentity!==Y.accountIdentity)throw new F("route-unavailable","Claustrum route is disabled, removed or changed");let B=await this.#Q(this.#U(),$),J=h3([this.#$.signal,...$?[$]:[]]);try{return await B.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},J.signal)}finally{J.dispose()}}async reportFailure(Z,$,z){if(this.#Y(),!this.#X)throw new F("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.reportFailure(Z,$,z)}async send(Z,$,z){let X=z.signal,Y=await this.authorize(Z,X),G=await $(Y,X);if(G.status===401&&!X?.aborted){let B;try{B=await this.authorize(Z,X)}catch{}if(n3(z.site,Y,B,this.#G))await G.body?.cancel().catch(()=>{}),Y=B,G=await $(B,X)}if(G.status===401)await this.reportFailure(Y,401,z.reporterSource??"direct").catch((B)=>this.#Z.onError?.(B)),Promise.resolve().then(()=>this.refresh()).catch((B)=>{if(!this.#$.signal.aborted)this.#Z.onError?.(B)});return G}async decline(Z){this.#Y(),await e3(this.#Z.rosterPath,Z),this.#z=await k(this.#Z.rosterPath)}async accept(Z){this.#Y(),await Z6(this.#Z.rosterPath,Z),this.#z=await k(this.#Z.rosterPath)}async recordQuota(Z,$,z){this.#Y();let X=await $6(this.#Z.rosterPath,{routeId:Z,observation:$,credentialId:z.credentialId,accountIdentitySource:z.accountIdentitySource,...z.accountIdentity!==void 0&&{accountIdentity:z.accountIdentity},...z.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:z.expectedAccountIdentity}});if(X)this.#z=await k(this.#Z.rosterPath);return X}async recordAccountQuota(Z,$,z){this.#Y();let X=await z6(this.#Z.rosterPath,{routeId:Z,accountIdentity:$,observation:z});if(X)this.#z=await k(this.#Z.rosterPath);return X}close(){if(this.#$.signal.aborted)return;if(this.#$.abort(new F("closed","Claustrum consumer is closed")),this.#J)(this.#Z.clearTimeoutImpl??clearTimeout)(this.#J);this.#J=void 0,this.#X?.close(),this.#W?.release(),this.#W=void 0,this.#z=void 0}}async function a4(Z){let $=await s1.connect(Z);return Object.assign($,{insula:X$(Z)})}var h$=tZ("openai");function m$(Z){return eZ(Z)}function GZ(Z){if(!Z||Z.corrupt===!0)return!1;return m$(Z.refresh)}class SZ extends Error{code="tombstone-refresh";constructor(){super("This OpenAI account was moved into the Claustrum vault by an older version of OpenAI auth and holds no local credential. Connect the vault, or sign in to the account again.");this.name="TombstoneRefreshError"}}function $3(Z){if(m$(Z))throw new SZ}var n1=I("quota"),Y6="primary",G6="secondary",a1="app_EMoamEEZ73f0CkXaXp7hrann",o1="https://auth.openai.com";async function U2(Z){$3(Z.refreshToken);let $=await Z.fetchImpl(`${o1}/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:Z.refreshToken,client_id:a1}).toString()});if(!$.ok){let Y=A3($.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${$.status}`),{status:$.status,retryAfter:Y,isRefreshError:!0})}let z=await $.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:$.status,isRefreshError:!0});if(z.refresh_token!==void 0&&typeof z.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:$.status,isRefreshError:!0});let X=typeof z.refresh_token==="string"&&z.refresh_token?z.refresh_token:Z.refreshToken;return{access:z.access_token,refresh:X,expires:Z.now()+z.expires_in*1000,expiresIn:z.expires_in}}var r1="https://chatgpt.com/backend-api/wham/usage";async function D2(Z){let $=Z.logger??n1,z=Z.accountKey??"unknown",X=Date.now();$.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await Z.fetchImpl(r1,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${Z.accessToken}`,"chatgpt-account-id":Z.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Y.ok){let B=A3(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:B})}let G=$$(await Y.json());return $.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:Y.status,elapsedMs:Date.now()-X}),G}catch(Y){throw $.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof Y?.status==="number"?Y.status:"error",elapsedMs:Date.now()-X,error:v$(Y)}),Y}}import{createHash as t1}from"node:crypto";var e1=globalThis.setTimeout,Z9=5;function RZ(Z){let $=Z?.quota?.checkIntervalMinutes??Z9;return Math.max(1,$)*60000}function $9(Z){return Z?.quota?.enabled!==!1}function z3(Z,$){if(!Z?.resetsAt)return!1;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)&&z<=$}function P2(Z,$,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let G=$===Y6?Z?.primary:$===G6?Z?.secondary:void 0,B=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(B)&&B>z)return B;return z+X}function z9(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??15,secondary:$.secondary??$["1w"]??10}}function g$(Z,$,z){if(!$9($))return z+RZ($);let X=z9($),Y=[];for(let G of["primary","secondary"]){let B=Z?.[G];if(!B)continue;if(B.remainingPercent>=X[G])continue;let J=B.resetsAt?Date.parse(B.resetsAt):Number.NaN;if(!Number.isFinite(J)||J<=z)return z+RZ($);Y.push(J)}if(!Y.length)return z+RZ($);return Math.min(...Y)+60000}function X9(Z){if(!Z?.quota?.mainQuota||!Z.quota.mainQuotaCheckedAt)return null;return{quota:Z.quota.mainQuota,checkedAt:Z.quota.mainQuotaCheckedAt,tokenFingerprint:Z.quota.mainQuotaToken}}function Y9(Z){let $=Z?.quota?.refreshEveryNRequests;return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):0}function x(Z){return t1("sha256").update(Z).digest("hex").slice(0,16)}class c{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(Z){this.storage=Z.storage,this.fetchImpl=Z.fetchImpl??fetch,this.configPath=Z.configPath,this.now=Z.now??Date.now,this.fetchQuotaFn=Z.fetchQuotaFn,this.onMainQuotaFetched=Z.onMainQuotaFetched,this.onApiError=Z.onApiError,this.seedMainFromStorage(Z.storage),this.seedMainBackoffFromStorage(Z.storage)}getMain(Z){if(Z&&this.main&&this.mainTokenFp&&this.mainTokenFp!==x(Z))this.main=null,this.mainTokenFp=null;return this.main}getFallback(Z,$){let z=this.fallbacks.get(Z)??null;if(!$||!z)return z;if(this.fallbackTokenFps.get(Z)!==x($))return this.fallbacks.delete(Z),this.fallbackTokenFps.delete(Z),null;return z}getAllFallbacks(){return this.fallbacks}setMain(Z,$,z,X=!1){if(!X&&!p$($.quota))return;if(this.mainTokenFp=x(Z),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=$,B6($.quota))this.clearRateLimited("main")}peekMainForPolicy(Z){if(Z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z)return null;return this.main}peekFallbackForPolicy(Z,$){let z=this.fallbacks.get(Z)??null;if($&&z?.accountId&&z.accountId!==$)return null;return z}setFallback(Z,$,z,X=!1,Y){if(!X&&!p$($.quota))return;let G=this.fallbacks.get(Z)?.accountId;if(Y&&G&&Y!==G)this.clearRateLimited(Z);let B=Y??G;if(this.fallbacks.set(Z,{...$,accountId:B}),z)this.fallbackTokenFps.set(Z,x(z));else this.fallbackTokenFps.delete(Z);if(B6($.quota))this.clearRateLimited(Z)}markRateLimited(Z,$){let z=this.rateLimitedUntilMap.get(Z);if(z!==void 0&&z>$)return;this.rateLimitedUntilMap.set(Z,$)}isRateLimited(Z){let $=this.rateLimitedUntilMap.get(Z);return $!==void 0&&this.now()<$}rateLimitedUntil(Z){return this.rateLimitedUntilMap.get(Z)}clearRateLimited(Z){this.rateLimitedUntilMap.delete(Z)}async refreshMain(Z){let $=x(Z);if(this.mainTokenFp&&this.mainTokenFp!==$)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===$)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=$,this.inflightMain=this._fetchMain(Z),this.inflightMain}async refreshFallback(Z,$){let z=c.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(Z){let $=this.now();for(let z of Z){if(z.enabled===!1)continue;if(GZ(z)||!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&$<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground(Z){let $=x(Z);if(this.inflightMain&&this.inflightMainFp===$)return;if(this.isBackedOff())return;this.refreshMain(Z).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(Z){let $=Y9(this.storage);if($<=0)return!1;return Z>0&&Z%$===0}needsRefresh(Z){return this.isMainStale()||this.shouldRefreshOnRequestCount(Z)}updateStorage(Z){this.storage=Z,this.seedMainFromStorage(Z),this.seedMainBackoffFromStorage(Z)}seedMainFromStorage(Z,$){let z=X9(Z);if(!z)return;let X=$?x($):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:g$(z.quota,Z,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,Z?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=Z.mainAccountId}}seedMainBackoffFromStorage(Z){let $=Z?.quota?.mainLastQuotaApiError;this.mainLastApiError=$&&QZ($,this.now())?$:void 0}seedFallbacksFromAccounts(Z){let $=RZ(this.storage);for(let z of Z){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+$,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return QZ(this.mainLastApiError,this.now())}isFallbackBackedOff(Z,$){if($){if(this.fallbackErrorTokenFps.get(Z)!==x($))return!1}return QZ(this.fallbackApiErrors.get(Z),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(Z,$){return JSON.stringify([Z,x($)])}static quotaLockName(Z){return`opencode-fallback-quota-refresh-${Z.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(Z){let $=async()=>{let X=this.now()-this.lastApiCallAt;if(X<c.API_CALL_GAP_MS)await new Promise((Y)=>{let G=e1(Y,c.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),Z()},z=this.apiGate.then($,$);return this.apiGate=z.catch(()=>{}),z}async _fetchMain(Z){let $=x(Z);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 E({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(Z),G=this.now();if(this.mainTokenFp=x(Z),this.main={quota:Y,refreshAfter:g$(Y,this.storage,G),checkedAt:G},B6(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===$)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 E({name:c.quotaLockName(Z),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($),Y=this.now();return this.setFallback(Z,{quota:X,refreshAfter:Y+RZ(this.storage),checkedAt:Y},$,!0),this.fallbackApiErrors.delete(Z),this.fallbackErrorTokenFps.delete(Z),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError(Z,$,z),z}finally{this.inflightFallbacks.delete(c.fallbackInflightKey(Z,$))}})}async _fetchQuota(Z){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:Z,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError(Z){return Z?.status===401}_handleMainFetchError(Z){if(c.isAuthError(Z))return;this.mainLastApiError=qZ({error:Z,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(Z,$,z){if(c.isAuthError(z))return;let X=x($),Y=this.fallbackErrorTokenFps.get(Z)===X?this.fallbackApiErrors.get(Z):void 0;this.fallbackApiErrors.set(Z,qZ({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set(Z,X)}}function p$(Z){return Boolean(Z.primary||Z.secondary)}function B6(Z){let{primary:$,secondary:z}=Z;if(!$&&!z)return!1;if($&&$.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{createHash as G9,randomUUID as B9}from"node:crypto";import{setTimeout as J9}from"node:timers/promises";import{readFile as _9}from"node:fs/promises";var BZ=I("refresh"),Y3=I("accounts"),W9=1e4,H9=15000,J6=50;function h(Z){return Z.type==="oauth"&&Z.corrupt!==!0}function K9(Z){let $=Z?.trim();if(!$)return!1;try{let z=new URL($);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}var Q9="floors-v1";function w2(Z){return Z.costZeroing?.enabled!==!1}class G3 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(Z){super(`Fallback account ${Z} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var V9=[401,403,429],l$={primary:0,secondary:0},U9=!1,H6={primary:5,secondary:10};function N(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var D9=new Set(["__proto__","constructor","prototype"]);function F9(Z){return Z.length>0&&!D9.has(Z)}function N9(Z){return Z instanceof G3||N(Z)&&Z.name==="AccountRemovedDuringRefreshError"&&Z.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function X3(Z){return{id:typeof Z.id==="string"&&Z.id.trim()?Z.id.trim():B9(),label:typeof Z.label==="string"?Z.label:void 0,enabled:typeof Z.enabled==="boolean"?Z.enabled:void 0,addedAt:typeof Z.addedAt==="number"?Z.addedAt:void 0,lastUsed:typeof Z.lastUsed==="number"?Z.lastUsed:void 0,accountId:typeof Z.accountId==="string"?Z.accountId:void 0}}function d$(Z){if(!N(Z))return;if(typeof Z.message!=="string")return;let $=Number(Z.checkedAt);if(!Number.isFinite($))return;let z=Number(Z.nextRetryAt),X=Number(Z.retryCount);return{message:Z.message,checkedAt:$,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof Z.tokenHash==="string"?Z.tokenHash:void 0}}function j9(Z){if(!N(Z))return;let $={};for(let Y of["primary","secondary"]){let G=Z[Y];if(!N(G))continue;let B=Number(G.usedPercent),J=Number(G.remainingPercent),W=Number(G.checkedAt);if(!Number.isFinite(B)||!Number.isFinite(J)||!Number.isFinite(W))continue;let H=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;$[Y]={usedPercent:B,remainingPercent:J,checkedAt:W,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(H)&&H>0?{windowMinutes:H}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof Z[Y]==="number"?Z[Y]:Number.NaN;if(Number.isFinite(G)&&G>=0)$[Y]=G}let z=Z.spendControl;if(N(z)){let Y=Number(z.limit),G=Number(z.used),B=Number(z.remaining),J=Number(z.usedPercent),W=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(G)&&Number.isFinite(B)&&Number.isFinite(J)&&Number.isFinite(W)&&typeof z.reached==="boolean")$.spendControl={limit:Y,used:G,remaining:B,usedPercent:J,remainingPercent:W,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=Z.credits;if(N(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&typeof X.overageLimitReached==="boolean"){let Y=Number(X.balance);$.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,overageLimitReached:X.overageLimitReached,...Number.isFinite(Y)?{balance:Y}:{}}}return Object.keys($).length?$:void 0}function q9(Z){if(!N(Z))return null;if(Z.type==="api"){let $=typeof Z.baseURL==="string"?Z.baseURL.trim():"",z=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!K9($))return null;let X=Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...X3(Z),type:"api",apiKey:z||void 0,baseURL:$,authHeader:X}}if(Z.type!=="oauth")return null;if(Z.corrupt===!0){if(typeof Z.id!=="string"||!Z.id.trim())return null;return{...X3(Z),type:"oauth",corrupt:!0}}if(typeof Z.refresh!=="string"||!Z.refresh.trim()){if(!Object.hasOwn(Z,"refresh")||typeof Z.id!=="string"||!Z.id.trim())return null;return{...X3(Z),type:"oauth",corrupt:!0}}return{...X3(Z),type:"oauth",access:typeof Z.access==="string"?Z.access:void 0,refresh:Z.refresh,expires:typeof Z.expires==="number"?Z.expires:void 0,lastRefreshedAt:typeof Z.lastRefreshedAt==="number"?Z.lastRefreshedAt:void 0,lastRefreshError:d$(Z.lastRefreshError),lastQuotaRefreshError:d$(Z.lastQuotaRefreshError),quota:j9(Z.quota)}}function M9(Z){if(!N(Z))return;let $=Object.create(null);for(let[z,X]of Object.entries(Z)){if(!F9(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]=Y}return Object.keys($).length>0?$:void 0}var c$=new Set;function r$(Z){if(Z.length===0)return;let $=JSON.stringify([...Z].sort());if(c$.has($))return;c$.add($),Y3.warn("account load-dropped, preserved on disk",{droppedIds:Z})}function t$(Z){if(!N(Z)||!Array.isArray(Z.accounts))return null;let $=Z.accounts,z=$.map(q9).filter((X)=>X!=null);if(z.length<$.length){let X=new Set;for(let B of $)if(N(B)&&typeof B.id==="string"&&B.id.trim())X.add(B.id.trim());let Y=new Set(z.map((B)=>B.id)),G=[];for(let B of X)if(!Y.has(B))G.push(B);r$(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:N(Z.routing)?Z.routing:void 0,fallbackOn:Array.isArray(Z.fallbackOn)?Z.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:N(Z.refresh)?Z.refresh:void 0,quota:N(Z.quota)?Z.quota:void 0,reset:M9(Z.reset),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,mainAccountId:typeof Z.mainAccountId==="string"?Z.mainAccountId:void 0,accounts:z}}function e$(Z){if(!("claustrum"in Z))return Z;let{claustrum:$,...z}=Z;return z}async function u(Z){try{return{exists:!0,value:JSON.parse(await _9(Z,"utf8"))}}catch($){if($.code==="ENOENT")return{exists:!1,value:null};throw $}}function i(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}async function P9(Z){let $;try{$=(await u(Z)).value}catch{return null}return U6($)}function Z8(Z,$){if(!N(Z))return Z;let z=N($)?$:{},X=N(z.main)?z.main:void 0,Y=N(z.accounts)?z.accounts:{},G=N(Z.quota)?Z.quota:{},B=N(Z.refresh)?Z.refresh:{},J=X??G,W=X??B,Q=B.mainRefreshLeaseId!==void 0?{id:B.mainRefreshLeaseId,until:B.mainRefreshLeaseUntil,tokenHash:B.mainRefreshLeaseTokenHash}:{id:W.refreshLeaseId,until:W.refreshLeaseUntil,tokenHash:W.refreshLeaseTokenHash},V=Array.isArray(Z.accounts)?Z.accounts.map((j)=>{if(!N(j))return j;let K=typeof j.id==="string"&&N(Y[j.id])?Y[j.id]:{};return{...j,...K}}):void 0;return $8({...Z,refresh:i({...B,mainLastRefreshError:B.mainLastRefreshError??W.lastRefreshError,mainRefreshLeaseId:Q.id,mainRefreshLeaseUntil:Q.until,mainRefreshLeaseTokenHash:Q.tokenHash}),quota:i({...G,mainQuota:J.quota,mainQuotaCheckedAt:J.quotaCheckedAt,mainQuotaToken:J.quotaToken,mainLastQuotaApiError:J.lastQuotaApiError}),accounts:V})}async function O9(Z){let $=await u(Z.configPath);if(!$.exists)return null;let z=await u(Z.statePath);return t$(Z8($.value,z.value))}function $8(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}function L9(Z){return i({id:Z.id,label:Z.label,type:Z.type,corrupt:Z.type==="oauth"&&Z.corrupt===!0?!0:void 0,enabled:Z.enabled,addedAt:Z.addedAt,accountId:Z.accountId,baseURL:Z.type==="api"?Z.baseURL:void 0,authHeader:Z.type==="api"?Z.authHeader:void 0})}function z8(Z){if(Z.type==="api")return i({apiKey:Z.apiKey,lastUsed:Z.lastUsed});if(Z.corrupt)return{};return i({access:Z.access,refresh:Z.refresh,expires:Z.expires,lastUsed:Z.lastUsed,lastRefreshedAt:Z.lastRefreshedAt,lastRefreshError:Z.lastRefreshError,lastQuotaRefreshError:Z.lastQuotaRefreshError,quota:Z.quota})}function B3(Z){return Math.max(Z?.primary?.checkedAt??0,Z?.secondary?.checkedAt??0)}function TZ(Z,$,z){if(z in $)Z[z]=$[z];else delete Z[z]}function S9(Z,$){return Z.access===$.access&&Z.refresh===$.refresh&&Z.expires===$.expires&&Z.lastRefreshedAt===$.lastRefreshedAt}function R9(Z,$){if(!S9(Z,$))return $;if(!("lastRefreshError"in $))return Z;if(!("lastRefreshError"in Z))return $;return($.lastRefreshError?.checkedAt??0)>(Z.lastRefreshError?.checkedAt??0)?$:Z}var T9=300000;function u$(Z,$){if(Z===void 0)return 0;return Z>$+T9?0:Z}function E9(Z,$,z){let X=Date.now(),Y=u$($.lastRefreshedAt,X),G=u$(z.lastRefreshedAt,X),B=$.expires??0,J=z.expires??0,W=G>Y?z:Y>G?$:J>B?z:B>J?$:R9($,z);TZ(Z,W,"access"),TZ(Z,W,"refresh"),TZ(Z,W,"expires"),TZ(Z,W,"lastRefreshedAt"),TZ(Z,W,"lastRefreshError")}function x9(Z,$){if(!N(Z))return $;let z=Z,X=B3(z.quota),Y=B3($.quota),G=X>Y,B=G?{...z,...$,quota:z.quota,lastQuotaRefreshError:z.lastQuotaRefreshError}:{...z,...$};if(!G&&!("lastQuotaRefreshError"in $))delete B.lastQuotaRefreshError;if(!("lastRefreshError"in $))delete B.lastRefreshError;if(typeof z.lastUsed==="number"&&(typeof $.lastUsed!=="number"||z.lastUsed>$.lastUsed))B.lastUsed=z.lastUsed;return E9(B,z,$),B}function X8(Z){let $=Z.refresh?i({enabled:Z.refresh.enabled,refreshBeforeExpiryMinutes:Z.refresh.refreshBeforeExpiryMinutes}):void 0,z=Z.quota?i({enabled:Z.quota.enabled,checkIntervalMinutes:Z.quota.checkIntervalMinutes,refreshEveryNRequests:Z.quota.refreshEveryNRequests,minimumRemaining:Z.quota.minimumRemaining,failClosedOnUnknownQuota:Z.quota.failClosedOnUnknownQuota}):void 0;return $8({version:1,main:Z.main,routing:Z.routing,fallbackOn:Z.fallbackOn,refresh:$,quota:z,reset:Z.reset,dump:Z.dump,costZeroing:Z.costZeroing,killswitch:Z.killswitch,logging:Z.logging,cachekeep:Z.cachekeep,cacheKeep:Z.cacheKeep,mainAccountId:Z.mainAccountId,accounts:Z.accounts.map(L9)})}async function CZ(Z,$=!1){let z=Date.now(),X=z+H9,Y=0;while(Date.now()<=X){Y++;let J=await E({name:"save",ttlMs:W9,path:Z,renew:$});if(J)return J;let W=X-Date.now();if(W<=0)break;await J9(Math.min(J6+W8(J6),W))}let G=Date.now()-z,B=Math.round(G/Math.max(1,Y));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${Z} (${Y} attempts, ~${B}ms apart; retry interval is ${J6}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 Y8(Z){let $=Object.fromEntries(Z.accounts.map((z)=>[z.id,z8(z)]));return{version:1,main:i({quota:Z.quota?.mainQuota,quotaCheckedAt:Z.quota?.mainQuotaCheckedAt,quotaToken:Z.quota?.mainQuotaToken,lastQuotaApiError:Z.quota?.mainLastQuotaApiError,lastRefreshError:Z.refresh?.mainLastRefreshError,refreshLeaseId:Z.refresh?.mainRefreshLeaseId,refreshLeaseUntil:Z.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:Z.refresh?.mainRefreshLeaseTokenHash}),accounts:$}}function U6(Z){if(!N(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let z of Z.accounts){if(!N(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;$.add(X)}return $}function C9(Z,$,z,X){if(!N(Z)||!Array.isArray(Z.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],G=[];for(let B of $){if(z.has(B))continue;if(X.has(B))continue;let J=Z.accounts.find((W)=>N(W)&&typeof W.id==="string"&&W.id.trim()===B);if(!J)continue;Y.push(J),G.push(B)}return{preservedRawEntries:Y,preservedIds:G}}function b9(Z){if(!Array.isArray(Z))return[];let $=[];for(let z of Z){if(!N(z))continue;if(typeof z.id!=="string")continue;$.push(z.id)}return $}function A9(Z,$,z){let X=U6(Z);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:G}=C9(Z,X,$,z);return r$(G),Y}async function m2(Z,$,z={}){let{configPath:X,statePath:Y}=$,G=await CZ(X);try{let B=await CZ(Y);try{let J=await u(X),W=await u(Y),H=(J.exists?t$(Z8(J.value,W.value)):null)??I9(),Q=new Set(H.accounts.map((U)=>U.id)),D=U6(J.value)??new Set,V=Z(H,{rawRosterIds:[...D],loadedRosterIds:[...Q]})??H,j=new Set(z.allowDrop??[]),K=A9(J.value,Q,j),q=X8(V),P=new Set((Array.isArray(q.accounts)?q.accounts:[]).map((U)=>N(U)&&typeof U.id==="string"?U.id.trim():"").filter(Boolean)),L=K.filter((U)=>{if(!N(U))return!1;if(typeof U.id!=="string")return!1;return!P.has(U.id.trim())}),IZ=N(J.value)?J.value:{},FZ={...e$(IZ),...q,accounts:[...Array.isArray(q.accounts)?q.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return H;if(await y(X,FZ),z.canWrite&&!z.canWrite())return H;return await y(Y,Y8(V)),Y3.debug("account config written",{accountCount:FZ.accounts.length,accountIds:b9(FZ.accounts)}),V}finally{await B.release()}}finally{await G.release()}}function I9(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function k9(Z,$){Z.main=Z.main??{};let z=typeof Z.main.quotaCheckedAt==="number"?Z.main.quotaCheckedAt:B3(Z.main.quota),X=typeof $.quota?.mainQuotaCheckedAt==="number"?$.quota.mainQuotaCheckedAt:B3($.quota?.mainQuota);if(z>X)return;Z.main.quota=$.quota?.mainQuota,Z.main.quotaCheckedAt=$.quota?.mainQuotaCheckedAt,Z.main.quotaToken=$.quota?.mainQuotaToken,Z.main.lastQuotaApiError=$.quota?.mainLastQuotaApiError}function f9(Z,$){Z.main=Z.main??{},Z.main.lastRefreshError=$.refresh?.mainLastRefreshError,Z.main.refreshLeaseId=$.refresh?.mainRefreshLeaseId,Z.main.refreshLeaseUntil=$.refresh?.mainRefreshLeaseUntil,Z.main.refreshLeaseTokenHash=$.refresh?.mainRefreshLeaseTokenHash}function K6(Z){if(Array.isArray(Z))return Z.map(K6);if(!N(Z))return Z;return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0).map(([$,z])=>[$,K6(z)]))}async function y9(Z,$,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=$.statePath,G=await CZ(Y);try{let B=(await u(Y)).value,J=N(B)?{...B,version:1}:{version:1};if(z.mainQuota)k9(J,Z);if(z.mainRefresh)f9(J,Z);if(z.accounts){let W=z.accounts===!0?null:new Set(z.accounts),H=await P9($.configPath);J.accounts={...N(J.accounts)?J.accounts:{}};for(let Q of Z.accounts){if(W&&!W.has(Q.id))continue;if(H&&!H.has(Q.id))continue;J.accounts[Q.id]=x9(J.accounts[Q.id],z8(Q))}if(W){for(let Q of W)if(!Z.accounts.some((D)=>D.id===Q))delete J.accounts[Q]}if(H){for(let Q of Object.keys(J.accounts))if(!H.has(Q))delete J.accounts[Q]}}if(X&&!X())return;await y(Y,K6(J))}finally{await G.release()}}function w9(Z){return Z?.fallbackOn?.length?Z.fallbackOn:V9}function v2(Z,$){return w9($).includes(Z)}function h9(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??l$.primary,secondary:$.secondary??$["1w"]??l$.secondary}}function Q6(Z){return Z?.quota?.enabled!==!1}function bZ(Z){return Z?.quota?.failClosedOnUnknownQuota??U9}function G8(Z,$,z=Date.now()){if(!Q6($))return!0;if(!Z)return!bZ($);let X=h9($),Y=bZ($);for(let G of["primary","secondary"]){let B=Z[G];if(!B)continue;if(z3(B,z)){if(Y)return!1;continue}if(B.remainingPercent<X[G])return!1}return!0}function J3(Z){return Z?.killswitch?.enabled===!0}function i$(Z){return{primary:Z?.primary??Z?.["5h"]??H6.primary,secondary:Z?.secondary??Z?.["1w"]??H6.secondary}}function g2(Z){return Z?.cacheKeep??Z?.cachekeep}function s$(Z){return typeof Z==="number"&&Number.isFinite(Z)?Z:0}function B8(Z,$){if(!Z?.killswitch)return H6;if(Z.killswitch.schema===Q9){let{accounts:z,defaults:X}=Z.killswitch,Y=$??"main",G=N(z)&&Object.hasOwn(z,Y)&&N(z[Y])?z[Y]:N(X)?X:void 0;return{primary:s$(G?.primary),secondary:s$(G?.secondary)}}if($&&Z.killswitch.accounts?.[$])return i$(Z.killswitch.accounts[$]);return i$(Z.killswitch.main)}function J8(Z,$,z,X=Date.now()){if(!J3($))return!0;if(!Z)return!bZ($);let Y=B8($,z),G=bZ($);for(let B of["primary","secondary"]){let J=Z[B];if(!J)continue;if(z3(J,X)){if(G)return!1;continue}if(J.remainingPercent<Y[B])return!1}return!0}function p2(Z,$,z,X){if(!J3(X))return 300;let Y=[],G=[{accountId:void 0,quota:Z},...$];for(let{accountId:J,quota:W}of G){if(!W)continue;let H=B8(X,J),Q=[],D=!1;for(let V of["primary","secondary"]){let j=W[V];if(!j||z3(j,z))continue;if(j.remainingPercent>=H[V])continue;let K=j.resetsAt?Date.parse(j.resetsAt):NaN;if(!Number.isFinite(K)||K<=z){D=!0;break}Q.push(K)}if(D||Q.length===0)continue;Y.push(Math.max(...Q))}if(Y.length===0)return 300;let B=Math.min(...Y);return Math.max(1,Math.ceil((B-z)/1000))}function n$(Z){return typeof Z.version==="number"&&Array.isArray(Z.accounts)}async function l2(Z,$){let{configPath:z,statePath:X}=$;if(!Z)return;try{let G=await u(z);if(G.exists&&N(G.value)&&n$(G.value))return}catch{}let Y=await CZ(z);try{let G=await CZ(X);try{let B=await u(z);if(B.exists&&N(B.value)){if(n$(B.value))return}if(!Z)return;let J={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(Z.access){let Q=lZ({id_token:"",access_token:Z.access,refresh_token:Z.refresh});if(Q)J.mainAccountId=Q}let W=B.exists&&N(B.value)?B.value:{},H={...e$(W),...X8(J)};await y(z,H),await y(X,Y8(J))}finally{await G.release()}}finally{await Y.release()}}function m9(Z){return Z?.refresh?.enabled!==!1}function v9(Z){return(Z?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function W8(Z){return Math.floor(Math.random()*(Z+1))}function JZ(Z,$,z){return!Z.access||!Z.expires||Z.expires-z<=v9($)}function g9(Z,$){return Boolean(Z.access&&typeof Z.expires==="number"&&Z.expires>$)}function EZ(Z,$){return Boolean(Z?.mainAccountId&&$.accountId&&$.accountId===Z.mainAccountId)}class H8 extends Error{constructor(Z){super(`Refusing to refresh account ${Z}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}var p9="common-auth-placeholder:v1:openai",K8="main";function d2(Z){return N(Z)&&Z.type==="oauth"&&(Z.refresh===p9||Z.refresh===h$)}function c2(Z){return Z?.accounts.find(($)=>$.id===K8&&$.enabled!==!1&&h($))}function u2(Z){if(!Z)return Z;return{...Z,accounts:Z.accounts.filter(($)=>$.id!==K8)}}function S(Z,$){let z=Z.accounts.findIndex((X)=>X.id===$.id);if(z!==-1)Z.accounts[z]=$}function xZ(Z){return Z instanceof Error?Z.message:String(Z)}function V6(Z,$,z){if($ instanceof SZ)return;Z.lastRefreshError=g6({error:$,now:z,refreshToken:Z.refresh,previous:Z.lastRefreshError})}function W6(Z,$,z){if($ instanceof SZ)return;if(Z.lastQuotaRefreshError=qZ({error:$,now:z,previous:Z.lastQuotaRefreshError}),$?.isRefreshError===!0)V6(Z,$,z)}function a$(Z,$){if(!Z)return!1;if(!Z.resetsAt)return!0;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)?z>$:!0}function l9(Z,$){if(!Z)return!1;return a$(Z.primary,$)||a$(Z.secondary,$)}function d9(Z,$,z){if(!Z)return!1;let X=$?.quota?.checkIntervalMinutes??5,Y=Math.max(1,X)*60000,G=Math.max(Z.primary?.checkedAt??0,Z.secondary?.checkedAt??0);return z-G<Y}function o$(Z,$,z){return!d9(Z.quota,$,z)}function c9(Z,$,z,X){return b3(z)&&G8(Z.quota,$,X)&&l9(Z.quota,X)}function u9(Z){let $=Z?.quota?.checkIntervalMinutes??5;return Math.max(1,$)*60000}var i9=60000,s9=60000,n9=600000;function a9(Z){return`fallback-oauth-refresh-${G9("sha256").update(Z).digest("base64url").slice(0,16)}`}var o9=1e4,r9=100;class t9{now;fetchImpl;paths;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor(Z){this.options=Z,this.now=Z.now??Date.now,this.fetchImpl=Z.fetchImpl??fetch,this.paths=Z.paths,this.quotaManager=Z.quotaManager??null,this.onFallbackStorageChanged=Z.onFallbackStorageChanged}assertNotTombstoned(Z){if(Z)$3(Z.refresh)}seedFallbackQuota(Z,$){if(!this.quotaManager)return;if(!Z.quota)return;let z=Math.max(Z.quota.primary?.checkedAt??0,Z.quota.secondary?.checkedAt??0);if(z<=0)return;let X=this.quotaManager.getFallback(Z.id,Z.access);if(X&&X.checkedAt>=z)return;this.quotaManager.setFallback(Z.id,{quota:Z.quota,refreshAfter:z+u9($),checkedAt:z},Z.access,!1,Z.accountId)}async load(){return O9(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save(Z,$){await y9(Z,this.paths,{accounts:$??!0},this.options.canWrite)}startBackgroundRefresh(){let Z=async()=>{if(await this.options.backgroundRefreshPaused?.())return;if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if(Z().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{Z().catch(()=>{})},i9+W8(s9)),"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(Z){let $=Z!==void 0?Z:await this.load();if(!$)return[];let z=[],X=!1;for(let Y of $.accounts){if(Y.enabled===!1||!h(Y))continue;if(EZ($,Y))continue;if(GZ(Y))continue;let G=!1,B=Y;try{if(JZ(B,$,this.now())){let J=B.lastRefreshError;if(J&&r(J,B.refresh,this.now()))throw G=!0,Error(gZ(J,this.now()));try{B=await this.refreshAccount(B,$),X=!0}catch(W){if(N9(W))continue;G=!0;let H=$.accounts.find((Q)=>Q.id===Y.id&&h(Q));if(H&&!r(H.lastRefreshError,H.refresh,this.now()))V6(H,W,this.now()),S($,H),X=!0;throw W}}if(this.seedFallbackQuota(B,$),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(B),$))z.push(B)}catch(J){let W=g9(B,this.now());if(G){if(!W)continue}else if(!W)continue;if(c9(B,$,J,this.now()))BZ.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:B.id,error:xZ(J)}),z.push(B);else if(!bZ($))z.push(B)}}if(X){let Y=structuredClone($);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((G)=>{Y3.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:xZ(G)})})}return z}async markUsed(Z){try{let $=await this.load();if(!$)return;let z=$.accounts.find((X)=>X.id===Z.id);if(!z)return;z.lastUsed=this.now(),await this.save($,[z.id])}catch($){Y3.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:Z.id,error:xZ($)})}}accountPassesQuotaPolicy(Z,$){return G8(Z.quota,$,this.now())}quotaPolicyAccount(Z){if(!this.quotaManager)return Z;let $=this.quotaManager.getFallback(Z.id,Z.access)?.quota;return $?{...Z,quota:$}:Z}async refreshDueAccounts(){let Z=await this.load();if(!Z||!m9(Z))return;let $=!1;for(let z of Z.accounts){if(z.enabled===!1||!h(z))continue;if(EZ(Z,z))continue;if(GZ(z))continue;if(!JZ(z,Z,this.now()))continue;if(r(z.lastRefreshError,z.refresh,this.now()))continue;try{BZ.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){BZ.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:xZ(X)}),V6(z,X,this.now()),S(Z,z),$=!0}}if($)await this.save(Z)}async refreshQuotaForDueAccounts(){let Z=await this.load();if(!Z||!Q6(Z))return;if(!this.options.fetchQuotaFn)return;let $=!1;for(let z of Z.accounts){if(z.enabled===!1||!h(z))continue;if(EZ(Z,z))continue;if(GZ(z))continue;let X=z;try{if(JZ(X,Z,this.now())){if(r(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,Z),$=!0}if(QZ(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,Z),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):o$(X,Z,this.now())))continue;await this.refreshAccountQuota(X,Z),$=!0}catch(Y){W6(z,Y,this.now()),S(Z,z),$=!0}}if($)await this.save(Z),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(Z={}){let $=await this.load(),z=[];if(!$||!Q6($))return{storage:$,errors:z};if(!this.options.fetchQuotaFn)return{storage:$,errors:z};let X=Z.force??!1,Y=!1;for(let G of $.accounts){if(G.enabled===!1||!h(G))continue;if(EZ($,G))continue;if(GZ(G))continue;let B=G;try{if(JZ(B,$,this.now())){let J=B.lastRefreshError;if(J&&r(J,B.refresh,this.now()))throw Error(gZ(J,this.now()));B=await this.refreshAccount(B,$),Y=!0}if(!X&&!o$(B,$,this.now())){if(B.lastQuotaRefreshError)B.lastQuotaRefreshError=void 0,S($,B),Y=!0;continue}await this.refreshAccountQuota(B,$),Y=!0}catch(J){W6(G,J,this.now()),S($,G),Y=!0,z.push({accountId:G.id,message:xZ(J)})}}if(Y)await this.save($);return{storage:$,errors:z}}async refreshAccount(Z,$,z={}){let X=this.refreshPromises.get(Z.id);if(X){let B=await X;return S($,B),B}let Y=this.refreshAccountNow(Z,$,z).finally(()=>{this.refreshPromises.delete(Z.id)});this.refreshPromises.set(Z.id,Y);let G=await Y;return S($,G),G}async waitForConcurrentFallbackRefresh(Z,$,z,X){let Y=Date.now()+o9;while(Date.now()<Y){await new Promise((H)=>setTimeout(H,r9));let G=await this.load(),B=G?.accounts.find((H)=>H.id===Z.id&&h(H));if(!B)continue;if(this.assertNotTombstoned(B),(B.access!==z.access||B.refresh!==z.refresh||(B.expires??0)>(z.expires??0)+60000)&&(X.force||!JZ(B,G,this.now())))return S($,B),BZ.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:B.id,expiresInMs:B.expires?B.expires-this.now():void 0}),B;let W=B.lastRefreshError;if(W&&r(W,B.refresh,this.now()))throw S($,B),Error(gZ(W,this.now()))}return null}assertNotShieldedMainRow(Z,$,z){if(z.asPoolMain||!$)return;if(EZ(Z,$))throw new H8($.id)}async refreshAccountNow(Z,$,z){let X=await this.load(),Y=X?.accounts.find((J)=>J.id===Z.id&&h(J));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!JZ(Y,X,this.now()))return S($,Y),Y;let G=Y??Z,B=await E({name:a9(G.id),ttlMs:n9,path:this.paths.configPath,renew:!0});if(!B){BZ.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let J=await this.waitForConcurrentFallbackRefresh(Z,$,G,z);if(J)return J;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),Y=X?.accounts.find((Q)=>Q.id===Z.id&&h(Q)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!JZ(Y,X,this.now()))return S($,Y),Y;if(!Y)throw new G3(Z.id);G=Y;let J=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});BZ.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 W=await J({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=W.access,G.refresh=W.refresh,G.expires=W.expires,G.lastRefreshedAt=W.expires-W.expiresIn*1000,G.lastRefreshError=void 0,S($,G),await this.save($),!(await this.load())?.accounts.some((Q)=>Q.id===Z.id))throw new G3(Z.id);return BZ.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await B.release()}}async refreshAccountQuota(Z,$){let z=Z;if(this.assertNotTombstoned(z),!z.access)throw Error(`Fallback account ${Z.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 ${Z.id} has no access token`);let G=await Y(z.access);z.quota=G,z.lastQuotaRefreshError=void 0,S($,z),await this.save($)}catch(G){throw W6(Z,G,this.now()),S($,Z),G}}}var Q8=["primary","secondary"];function D6(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function AZ(Z){return typeof Z==="number"&&Number.isFinite(Z)}function e9(Z,$){if(!D6($))return;let z=$.usedPercent;if(!AZ(z)||z<0||z>100)return;return{label:Z,usedPercent:z,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...AZ($.windowMinutes)&&$.windowMinutes>0?{windowMinutes:$.windowMinutes}:{}}}function Z0(Z){let $=Z.spendControl;if(D6($)&&typeof $.reached==="boolean"){let z=(X)=>AZ($[X])?{[X]:$[X]}:{};return{kind:"reading",reached:$.reached,...z("remainingPercent"),...z("usedPercent"),...z("limit"),...z("used"),...z("remaining"),...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...typeof $.unit==="string"?{unit:$.unit}:{}}}if(Z.spendControlCleared===!0)return{kind:"cleared"};return}function n2(Z,$,z){if(!D6(Z)||!AZ($))return;let X=[],Y=[];for(let W of Q8){let H=e9(W,Z[W]);if(H)X.push(H);else if(z)Y.push({label:W})}let G=Z0(Z),B=Z.resetCreditsAvailable,J=typeof B==="number"&&Number.isSafeInteger(B)&&B>=0?{resetCredits:{value:B,checkedAt:$}}:void 0;if(X.length===0&&Y.length===0&&!G&&!J)return;return{checkedAt:$,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...G?{budget:G}:{},...J?{counters:J}:{}}}function V8(Z){if(!n(Z))return;let $=A(Z),z={};for(let X of Q8){let Y=$.limits.find((B)=>B.label===X&&B.kind==="reading");if(!Y||!AZ(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 D8="main";function Z7(Z){return Z.find(($)=>$.id.startsWith("vault:")&&$.credentialId==="chatgpt:openai")?.id??null}function $7(Z,$,z){let X=new Map;if(J3($))for(let Y of Z)X.set(Y.id,J8(V8(Y.quota),$,Y.id===D8?void 0:Y.id,z));return X}var z7=5,$0=5000;function X7(Z){if(Z==="ordered")return"roster";return Z==="fallback-first"?"fallback-first":"main-first"}function Y7(Z,$=$0){let z=Z.rows.filter((B)=>B.kind==="oauth"&&Z.killswitch.get(B.id)!==!1&&A(B.quota).limits.length===0);if(z.length===0)return;if(f({rows:Z.rows,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:()=>{}}).admitted.some((B)=>Z.killswitch.get(B.id)!==!1))return;let Y=[];if(f({rows:z,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:(B)=>{let J=Z.requestPull(B);if(J)Y.push(J.catch(()=>{}))}}),Y.length===0)return;let G;return Promise.race([Promise.all(Y),new Promise((B)=>{G=setTimeout(B,$)})]).then(()=>{}).finally(()=>clearTimeout(G))}function F6(Z){return Z.reason==="exhausted"||Z.reason==="budget-spent"}function F8(Z,$,z){if(Z===void 0)return{reason:"no-credential"};if(z.get(Z)===!1)return{reason:"killswitch"};let X=$.excluded.find((G)=>G.id===Z);if(X?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:X.until};if(X)return{reason:"no-credential"};let Y=$.refused.find((G)=>G.id===Z);if(Y&&"resetAtMs"in Y)return{reason:"quota-exhausted",resetAtMs:Y.resetAtMs};if(Y)return{reason:"quota-unknown"};return{reason:"no-credential"}}function U8(Z,$,z){if($.refused.find((Y)=>!F6(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return F8(Z[0],$,z)}function G7(Z){let $=Z.replayable!==!1,z=Z.mainId===void 0?D8:Z.mainId??"",X=$?Z.placement:"main-first",Y=_3({rows:Z.rows,placement:X,formerMainId:z,killswitch:Z.killswitch,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,now:Z.now,requestPull:Z.requestPull}),G=mZ(Z.rows.map((W)=>W.id),X,z),B=new Set(Y.admission.refused.filter((W)=>F6(W)&&Z.killswitch.get(W.id)!==!1).map((W)=>W.id)),J=G.filter((W)=>B.has(W));if(!$){let W=G.includes(z),H=W?z:Y.order[0]??J[0];if(H!==void 0&&Y.order.includes(H))return{kind:"send",order:[H],lastPath:!1};if(H!==void 0&&B.has(H))return{kind:"send",order:[H],lastPath:!0};return{kind:"block",block:W?F8(z,Y.admission,Z.killswitch):U8(G,Y.admission,Z.killswitch)}}if(Y.order.length>0)return{kind:"send",order:Y.order,lastPath:!1};if(J.length>0)return{kind:"send",order:J,lastPath:!0};return{kind:"block",block:U8(G,Y.admission,Z.killswitch)}}function B7(Z){let $=f({rows:Z.rows,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,now:Z.now,requestPull:Z.requestPull}),z=new Map;for(let X of Z.rows)z.set(X.id,A(X.quota));for(let X of $.admitted)if(X.projection)z.set(X.id,X.projection);return{projections:z,excluded:new Set($.excluded.map((X)=>X.id))}}function N8(Z,$,z){let X=z.exclude,Y=X?Z.rows.filter((B)=>!X.has(B.id)):Z.rows,G=new Map;for(let B of Y){let J=$.resetCredits(B.id);if(J!==void 0)G.set(B.id,J)}return T3({rows:Y,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:Z.requestPull,killswitch:Z.killswitch,requestBytes:$.requestBytes,...z.pendingBytes?{pendingBytes:z.pendingBytes}:{},rowReservePercent:(B)=>$.reservePercent(B.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...z.pin===void 0?{}:{pin:{accountId:z.pin}},...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}})}function J7(Z,$,z,X){let Y=N8(Z,$,{exclude:z,pendingBytes:X});if(Y.outcome!=="dispatch"||Y.source==="pin")return;return{accountId:Y.accountId,source:Y.source,...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}}function W7(Z,$,z){let X=Z.killswitch.get(z)===!1,Y=N8(Z,$,{pin:z});if(Y.outcome==="dispatch"){if(Y.pin.action==="assign")return{kind:"move",reason:X?"killswitch":"exhausted"};return Y.accountId===z?{kind:"serve"}:{kind:"detour"}}let G=Y.admission.refused.find((B)=>B.id===z);if(!X&&G&&F6(G))return{kind:"last-path"};return{kind:"none"}}function H7(Z,$,z,X){let Y=Z.killswitch.get(z);return R3({quota:$.projections.get(z),now:Z.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as j8}from"node:os";import{join as q8}from"node:path";var z0=["error","warn","info","debug","trace"];function X0(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?q8(j8(),"opencode-openai-auth","opencode-openai-auth.log"):q8(j8(),"opencode-openai-auth.log"))}function Y0(){let Z=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return Z&&z0.includes(Z)?Z:void 0}M8({file:X0,level:Y0});if(process.once("beforeExit",async()=>{try{await W3()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>W3());
|
|
90
|
+
export{n as mc,KZ as nc,h8 as oc,T6 as pc,x6 as qc,E8 as rc,A as sc,k6 as tc,v8 as uc,mZ as vc,g8 as wc,P3 as xc,p8 as yc,c8 as zc,o8 as Ac,v6 as Bc,g6 as Cc,r as Dc,gZ as Ec,u6 as Fc,s6 as Gc,$1 as Hc,l6 as Ic,d6 as Jc,lZ as Kc,X1 as Lc,$Z as Mc,J1 as Nc,W1 as Oc,H1 as Pc,K1 as Qc,t0 as Rc,Z4 as Sc,$4 as Tc,z4 as Uc,h3 as Vc,F as Wc,T1 as Xc,E1 as Yc,x1 as Zc,c3 as _c,A1 as $c,T$ as ad,I1 as bd,k as cd,w$ as dd,a4 as ed,GZ as fd,SZ as gd,U2 as hd,D2 as id,P2 as jd,x as kd,c as ld,h as md,Q9 as nd,w2 as od,H6 as pd,F9 as qd,P9 as rd,O9 as sd,m2 as td,y9 as ud,w9 as vd,v2 as wd,G8 as xd,J3 as yd,g2 as zd,B8 as Ad,J8 as Bd,p2 as Cd,l2 as Dd,v9 as Ed,EZ as Fd,K8 as Gd,d2 as Hd,c2 as Id,u2 as Jd,n9 as Kd,a9 as Ld,t9 as Md,n2 as Nd,V8 as Od,D8 as Pd,Z7 as Qd,$7 as Rd,z7 as Sd,X7 as Td,Y7 as Ud,G7 as Vd,B7 as Wd,J7 as Xd,W7 as Yd,H7 as Zd};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Qd as NZ,Td as WZ,pc as BZ,rc as QZ,sc as UZ,vc as DZ}from"./index-7eb3dw37.js";import{$d as ZZ,de as $Z,ee as JZ,fe as y,ge as x}from"./index-msx2m78k.js";import{xe as PZ}from"./index-7c6sxtd6.js";import{Fe as b,Ge as t,Ke as A,Le as e}from"./index-m5qmvr6c.js";import{createHash as hZ}from"node:crypto";import{constants as mZ,copyFileSync as pZ,mkdirSync as gZ,statSync as dZ}from"node:fs";import{readFile as lZ}from"node:fs/promises";import{homedir as uZ,tmpdir as cZ}from"node:os";import{dirname as rZ,join as h}from"node:path";import{chmod as AZ,mkdir as yZ}from"node:fs/promises";import{dirname as n}from"node:path";function k(Z){let{path:$,defaultValue:V,normalize:J}=Z,X=Promise.resolve(),Y=(G)=>{if(G==="")return V;try{return J(JSON.parse(G))}catch{return V}},j=async()=>{try{if(b)await A(n($),Z.secureDir??!0);return await e($,b)}catch(G){if(G.code==="ENOENT")return"";throw G}},z=async()=>{try{return Y(await j())}catch(G){if(G instanceof t)throw G;return V}},Q=(G,D)=>{let N=X.then(G).then((P)=>D?.onResult?.(P));return X=N.catch(()=>{}),N},B={...x.sidebar,name:Z.lockName??x.sidebar.name,timeoutMs:Z.timeoutMs??x.sidebar.timeoutMs},K=async(G,D,N)=>{await ZZ($,D,{serialize:JSON.stringify,beforeRename:async()=>{await N?.beforeCommit?.(),await G.assertOwned()}}),await N?.afterRename?.();try{return await G.assertOwned(),!0}catch(P){if(P instanceof JZ)return!1;throw P}},U=async(G,D,N)=>{Z.logger?.warn("sidebar lock lost after rename; repairing write",{path:$});try{let P=await y($,B,async(W)=>{let H=G(await z(),D);if(H===void 0)return"skipped";return await K(W,H,N)?"written":"lost-again"});if(P==="lost-again")Z.logger?.warn("sidebar repair lost its lock after rename",{path:$});return{status:"lost-after-rename",repair:P}}catch(P){if(!(P instanceof $Z))throw P;return Z.logger?.warn("sidebar repair lock unavailable; repair skipped",{path:$}),{status:"lost-after-rename",repair:"lock-unavailable"}}},L=async(G,D)=>{let N=D,P=n($),W=Z.secureDir??!0;if(b)await A(P,W);else if(await yZ(P,{recursive:!0,mode:448}),W)await AZ(P,448).catch((F)=>{Z.logger?.warn("sidebar directory permission remediation failed",{error:F instanceof Error?F.message:String(F)})});let H=await y($,B,async(F)=>{let o=async(C)=>({value:C,held:await K(F,C,N)});for(let C=0;C<3;C+=1){let i=await j(),s=G(Y(i));if(s===void 0)return;if(C===0)await N?.beforeRecheck?.();if(await j()!==i)continue;return await o(s)}let a=G(await z());return a===void 0?void 0:await o(a)});if(H===void 0)return{status:"skipped"};if(H.held)return{status:"written"};let r=D?.repair??Z.repair;if(!r)return Z.logger?.warn("sidebar lock lost after rename; write not repaired",{path:$}),{status:"lost-after-rename",repair:"none"};return await U(r,H.value,N)};return{read:z,write:(G,D)=>Q(()=>L(()=>G,D),D),update:(G,D)=>Q(()=>L(G,D),D)}}var g=["primary","secondary"],kZ={primary:300,secondary:10080};function wZ(Z,$){return BZ({scope:"all",label:$,windowMinutes:Z})}function C0(Z){if(!Z)return[];let $=[];for(let V of g){let J=Z[V];if(!J)continue;let X=J.windowMinutes,Y=X!==void 0&&Number.isFinite(X)&&X>0?X:kZ[V];$.push({key:V,label:wZ(X,V),window:J,windowMs:Y*60000})}return $}var M=PZ("sidebar"),oZ="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE";function HZ(){let Z=process.env.XDG_STATE_HOME||h(uZ(),".local","state");return h(Z,"cortexkit","openai-auth","sidebar-state.json")}var OZ=h(cZ(),"opencode-openai-auth","sidebar-state.json");function v0(Z){OZ=Z,m.clear()}var aZ=/^[a-f0-9]{64}$/,d=604800000,TZ=256,_Z=3600000;function _(Z){return hZ("sha256").update(Z).digest("hex")}function iZ(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function RZ(Z){let $=iZ(Z);return $!==void 0?{resetCredits:$}:{}}function sZ(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.activeId!=="string"||typeof X.route!=="string"||typeof X.updatedAt!=="number"||!Number.isFinite(X.updatedAt))continue;$[V]={activeId:X.activeId,route:X.route,updatedAt:X.updatedAt}}return Object.keys($).length>0?$:void 0}function nZ(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(!aZ.test(V)||J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.accountId!=="string"||X.accountId.length===0||typeof X.assignedAt!=="number"||!Number.isFinite(X.assignedAt)||X.assignedAt<0||typeof X.lastSeenAt!=="number"||!Number.isFinite(X.lastSeenAt)||X.lastSeenAt<0||typeof X.inputBytes!=="number"||!Number.isFinite(X.inputBytes)||X.inputBytes<0)continue;let Y=X.quotaCheckedAt;if(Y!==void 0&&(typeof Y!=="number"||!Number.isFinite(Y)||Y<0))continue;let j=X.wireAccountId;$[V]={accountId:X.accountId,assignedAt:X.assignedAt,lastSeenAt:X.lastSeenAt,inputBytes:X.inputBytes,...Y===void 0?{}:{quotaCheckedAt:Y},...typeof j==="string"?{wireAccountId:j}:{}}}return Object.keys($).length>0?$:void 0}function O(){let Z=process.env[oZ];if(Z)return Z;let $=HZ();if(!m.has($))m.add($),tZ($,OZ);return $}var m=new Set;function tZ(Z,$){try{gZ(rZ(Z),{recursive:!0,mode:448}),pZ($,Z,mZ.COPYFILE_EXCL)}catch{}}var E={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function f(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return E;let $=Z,V=$.main,J;if(V!==null&&typeof V==="object"&&!Array.isArray(V)){let G=V;J={quota:"quota"in G?G.quota:null,killed:typeof G.killed==="boolean"?G.killed:!1,...typeof G.mainAccountId==="string"?{mainAccountId:G.mainAccountId}:{},...typeof G.quotaBackedOff==="boolean"?{quotaBackedOff:G.quotaBackedOff}:{},...typeof G.quotaBackoffUntil==="number"?{quotaBackoffUntil:G.quotaBackoffUntil}:{},...typeof G.refreshBackedOff==="boolean"?{refreshBackedOff:G.refreshBackedOff}:{},...typeof G.refreshBackoffUntil==="number"?{refreshBackoffUntil:G.refreshBackoffUntil}:{},...RZ(G.resetCredits)}}else J={quota:null,killed:!1};let X=XZ($.fallbacks),Y=Array.isArray($.vaultAccounts)?XZ($.vaultAccounts):void 0,j=typeof $.activeId==="string"?$.activeId:void 0,z=typeof $.route==="string"?$.route:E.route,Q=typeof $.lastUpdated==="number"?$.lastUpdated:0,B=typeof $.planType==="string"?$.planType:void 0,K=typeof $.credits==="number"?$.credits:void 0,U=sZ($.activeRouting),L=nZ($.stickyAssignments);return{main:J,fallbacks:X,activeId:j,route:z,lastUpdated:Q,...U!==void 0?{activeRouting:U}:{},...L!==void 0?{stickyAssignments:L}:{},...B!==void 0?{planType:B}:{},...K!==void 0?{credits:K}:{},...$.accountPool===!0?{accountPool:!0}:{},...Y!==void 0?{vaultAccounts:Y}:{}}}function XZ(Z){if(!Array.isArray(Z))return[];return Z.filter(($)=>$!==null&&typeof $==="object"&&!Array.isArray($)&&typeof $.id==="string").map(($)=>({id:$.id,...typeof $.credentialId==="string"?{credentialId:$.credentialId}:{},label:typeof $.label==="string"?$.label:void 0,...typeof $.accountId==="string"?{accountId:$.accountId}:{},quota:"quota"in $?$.quota:null,killed:typeof $.killed==="boolean"?$.killed:!1,enabled:typeof $.enabled==="boolean"?$.enabled:!0,...typeof $.routable==="boolean"?{routable:$.routable}:{},...["needs sign-in","turned off in vault","unavailable"].includes($.vaultState)?{vaultState:$.vaultState}:{},...RZ($.resetCredits)}))}function l(Z){return[...Z.fallbacks,...Z.vaultAccounts??[]]}async function eZ(Z=O()){try{let $=await lZ(Z,"utf8");return f(JSON.parse($))}catch{return E}}var Z0=3600000,VZ=128;function CZ(Z,$,V=Date.now()){if(!(Z.updatedAt>=V-Z0&&Z.updatedAt<=V))return!1;if($===void 0)return!0;return Z.activeId==="main"||$.some((X)=>X.enabled!==!1&&X.routable!==!1&&X.killed!==!0&&X.id===Z.activeId)}function $0(Z,$=Date.now()){let V=Z?.spendControl;if(V?.reached!==!0||typeof V.resetsAt!=="string")return;let J=Date.parse(V.resetsAt);if(!Number.isFinite(J)||J<=$)return;return{resetsAt:V.resetsAt,resetAtMs:J}}function J0(Z,$=Date.now()){let V;for(let X of g){let Y=Z?.[X];if(typeof Y?.resetsAt!=="string"||!Number.isFinite(Y.usedPercent)||Y.usedPercent<100)continue;let j=Date.parse(Y.resetsAt);if(!Number.isFinite(j)||j<=$)continue;if(!V||j<V.resetAtMs)V={resetsAt:Y.resetsAt,resetAtMs:j}}let J=$0(Z,$);if(J&&(!V||J.resetAtMs<V.resetAtMs))V=J;return V}function q(Z,$=Date.now()){return J0(Z,$)!==void 0}function X0(Z,$,V=Date.now()){if(!$||Z.route!=="sticky-balanced")return;let J=Z.stickyAssignments?.[_($)];if(!J||J.lastSeenAt<V-d)return;if(J.accountId==="main"&&Z.vaultAccounts===void 0)return Z.main?.killed||q(Z.main?.quota,V)?void 0:"main";let X=l(Z).find((Y)=>Y.id===J.accountId);if(!X||X.enabled===!1||X.routable===!1||X.killed===!0||q(X.quota,V))return;return X.id}function S0(Z,$,V=Date.now()){if(!$){if(Z.vaultAccounts===void 0)return{activeId:Z.activeId??"main",route:Z.route};let K=Z.vaultAccounts.find((U)=>U.id===Z.activeId&&U.enabled&&U.routable!==!1&&!U.killed);if(K&&!q(K.quota,V))return{activeId:K.id,route:Z.route}}let J=$?Z.activeRouting?.[$]:void 0,X=l(Z),Y=J?.activeId==="main"?Z.main.quota:X.find((K)=>K.id===J?.activeId)?.quota;if(J&&(Z.vaultAccounts===void 0||J.activeId.startsWith("vault:"))&&CZ(J,X,V)&&!q(Y,V))return{activeId:J.activeId,route:J.route};let j=X0(Z,$,V);if(j)return{activeId:j,route:Z.route};let z=Z.vaultAccounts!==void 0,Q=(z?FZ(Z):Z.fallbacks).filter((K)=>K.enabled&&K.routable!==!1&&!K.killed),B=Q.find((K)=>!q(K.quota,V))??Q[0];return{activeId:z?B?.id??"vault":Z.route==="fallback-first"&&B?B.id:"main",route:Z.route}}function FZ(Z){let $=Z.vaultAccounts??[],V=new Map($.map((J)=>[J.id,J]));return DZ($.map((J)=>J.id),Z.route==="sticky-balanced"?"roster":WZ(Z.route),NZ($)??"").flatMap((J)=>{let X=V.get(J);return X?[X]:[]})}function MZ(Z,$,V=Date.now(),J){if(!Z)return;let X=Object.entries(Z).filter(([j,z])=>j!==J&&CZ(z,$,V)),Y=X.length<=VZ?X:X.sort((j,z)=>z[1].updatedAt-j[1].updatedAt).slice(0,VZ);return Y.length>0?Object.fromEntries(Y):void 0}function I(Z,$,V=Date.now(),J){if(!Z)return;let X=0,Y=0,j=0,z=[];for(let[B,K]of Object.entries(Z)){if(B===J){j+=1;continue}if(K.lastSeenAt<V-d){Y+=1;continue}if($!==void 0&&!$.has(K.accountId)){X+=1;continue}z.push([B,K])}let Q=X+Y+j;if(Q>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:Q,reasons:{"account-not-in-roster":X,expired:Y,"explicit-removal":j}});return z.length>0?Object.fromEntries(z):void 0}function qZ(Z,$){let V=Object.keys(Z).length-TZ;if(V<=0)return Z;let J=new Set(Object.entries(Z).filter(([X])=>X!==$).sort(([X,Y],[j,z])=>Y.lastSeenAt-z.lastSeenAt||X.localeCompare(j)).slice(0,V).map(([X])=>X));return Object.fromEntries(Object.entries(Z).filter(([X])=>!J.has(X)))}function EZ(Z,$){if(Z===$)return!0;if(!Z||!$)return!1;let V=Object.entries(Z);if(V.length!==Object.keys($).length)return!1;return V.every(([J,X])=>Object.is($[J],X))}function IZ(Z,$,V,J){return Z!==void 0&&$.has(Z.accountId)&&!V.has(Z.accountId)&&Z.lastSeenAt>=J-d}function bZ(Z,$,V,J){return $>Z.inputBytes||V-Z.lastSeenAt>=_Z||Z.wireAccountId===void 0&&J!==void 0}function xZ(Z,$){return typeof Z.wireAccountId==="string"&&typeof $==="string"&&Z.wireAccountId!==$}function V0(Z){let $=new Map(Z),V={get size(){return $.size},has:(J)=>$.has(J),get:(J)=>$.get(J),entries:()=>$.entries(),keys:()=>$.keys(),values:()=>$.values(),forEach:(J,X)=>{$.forEach((Y,j)=>{J.call(X,Y,j,V)})},[Symbol.iterator]:()=>$[Symbol.iterator]()};return Object.freeze(V)}function Y0(Z,$,V){let J=new Map;for(let[X,Y]of Object.entries(Z??{})){if(X===V)continue;if(Y.quotaCheckedAt!==$[Y.accountId])continue;J.set(Y.accountId,(J.get(Y.accountId)??0)+Y.inputBytes)}return V0(J)}function u(Z){if(Z===void 0)return;return new Set(["main",...Z.filter(($)=>$.enabled!==!1&&$.killed!==!0).map(($)=>$.id)])}var p=Promise.resolve();function T(Z){let $=p.then(Z);return p=$.catch(()=>{}),$}var YZ=new Map;function c(Z){let $=YZ.get(Z);if(!$)$=k({path:Z,defaultValue:E,normalize:f,secureDir:Z===HZ(),logger:M}),YZ.set(Z,$);return $}var w=new Set;async function vZ(Z,$){try{await $}catch(V){let J={pid:process.pid,error:V instanceof Error?V.message:String(V)};if(w.has(Z))M.debug("sidebar write failed again",J);else w.add(Z),M.warn("sidebar write failed",J);throw V}if(w.delete(Z))M.info("sidebar write recovered",{pid:process.pid})}function f0(Z,$=O()){return T(()=>vZ($,c($).write(f(Z))))}function z0(Z){return c(Z).read()}function R(Z,$,V){let J=Symbol("sidebar authority changed");return vZ(Z,c(Z).update((X)=>{if(V?.canWrite&&!V.canWrite())return;let Y=$(X);if(Y===void 0)return;if(Y.vaultAccounts!==void 0)Y.activeId=Y.activeId?.startsWith("vault:")?Y.activeId:void 0,Y.activeRouting=Object.fromEntries(Object.entries(Y.activeRouting??{}).filter(([,j])=>j.activeId.startsWith("vault:"))),Y.stickyAssignments=Object.fromEntries(Object.entries(Y.stickyAssignments??{}).filter(([,j])=>j.accountId.startsWith("vault:")&&!Y.vaultAccounts?.some((z)=>z.id===j.accountId&&z.killed)));return f(Y)},{beforeRecheck:async(...X)=>{if(await V?.beforeRecheck?.(...X),V?.canWrite&&!V.canWrite())throw J}}).catch((X)=>{if(X!==J)throw X}))}function v(Z){let $;for(let V of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt])if(typeof V==="number"&&Number.isFinite(V))$=$===void 0?V:Math.max($,V);return $}function zZ(Z,$){let V=v(Z),J=v($);if(J!==void 0&&(V===void 0||J>V))return $;return Z}function jZ(Z,$){return Z!==void 0&&$!==void 0&&Z===$}function S(Z,$){let V=Z?.checkedAt;if(typeof V==="number"&&Number.isFinite(V))return V;if(typeof $==="number"&&Number.isFinite($))return $;return}function GZ(Z,$,V,J,X){if(Z&&$){let Y=S(Z,J),j=S($,X);if(j!==void 0&&(Y===void 0||j>Y))return $;return Z}return V?$:Z}function KZ(Z,$){if(Z.spendControl!==void 0)return Z.spendControl;if(Z.spendControlCleared===!0)return;return $.spendControl}function LZ(Z,$){if(!Z)return $;if(!$)return Z;let V=v(Z),J=v($),X=J!==void 0&&(V===void 0||J>V),Y=GZ(Z.primary,$.primary,X,Z.checkedAt,$.checkedAt),j=GZ(Z.secondary,$.secondary,X,Z.checkedAt,$.checkedAt),z=X?KZ($,Z):KZ(Z,$),Q=z===void 0&&(Z.spendControlCleared===!0||$.spendControlCleared===!0),B;for(let G of[S(Y),S(j)])if(G!==void 0)B=B===void 0?G:Math.max(B,G);let{spendControl:K,spendControlCleared:U,...L}=Z;return{...L,primary:Y,secondary:j,...z!==void 0?{spendControl:z}:{},...Q?{spendControlCleared:!0}:{},checkedAt:B??Z.checkedAt}}function A0(Z,$=O(),V){return T(async()=>{await R($,(J)=>{let X=new Map(J.fallbacks.map((K)=>[K.id,K])),Y=Z.vaultAccounts!==void 0,j=jZ(Z.main.mainAccountId,J.main.mainAccountId),z=j?LZ(Z.main.quota,J.main.quota):zZ(Z.main.quota,J.main.quota),Q=Date.now(),B=I(J.stickyAssignments,Y?void 0:u(l(Z)),Q);return{...J,...Z,main:Y?Z.main:{...Z.main,quota:z,mainAccountId:j?Z.main.mainAccountId:z===J.main.quota&&z!==Z.main.quota?J.main.mainAccountId:Z.main.mainAccountId},fallbacks:Y?Z.fallbacks:Z.fallbacks.map((K)=>{let U=X.get(K.id),L=jZ(K.accountId,U?.accountId),G=L?LZ(K.quota,U?.quota??null):zZ(K.quota,U?.quota??null);return{...K,quota:G,accountId:L?K.accountId:G===U?.quota&&G!==K.quota?U?.accountId:K.accountId}}),activeId:J.activeId,activeRouting:J.activeRouting,stickyAssignments:B,lastUpdated:Math.max(Q,J.lastUpdated+1),accountPool:Z.accountPool===!0?!0:void 0,vaultAccounts:Z.vaultAccounts}},V)})}function y0(Z,$,V=O(),J){return T(async()=>{await R(V,(X)=>{let Y=MZ({...X.activeRouting,[Z.sessionId]:{activeId:Z.activeId,route:Z.route,updatedAt:Z.updatedAt}},$,Date.now()),j=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:u($),Date.now());return{...X,activeId:Z.activeId,route:Z.route,activeRouting:Y,stickyAssignments:j,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function k0(Z,$=O(),V){return T(async()=>{await R($,(J)=>({...J,activeId:Z.activeId,route:Z.route,lastUpdated:Math.max(Date.now(),J.lastUpdated+1)}),V)})}function w0(Z,$,V=O(),J){return T(async()=>{await R(V,(X)=>{let Y=Date.now(),j=MZ(X.activeRouting,$,Y,Z),z=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:u($),Y,_(Z));return{...X,activeRouting:j,stickyAssignments:z,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function SZ(Z,$){return IZ(Z,new Set($.validPinnedAccountIds),new Set($.excludeAccountIds),$.now)&&!xZ(Z,$.wireAccountIdByAccount?.[Z.accountId])&&!bZ(Z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[Z.accountId])}function fZ(Z,$){let V=_($.sessionId),J=new Set($.validPinnedAccountIds),X=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),j=!EZ(Z.stickyAssignments,Y),z=Y?.[V],Q=z!==void 0&&xZ(z,$.wireAccountIdByAccount?.[z.accountId]);if(IZ(z,J,X,$.now)&&!Q){let U=bZ(z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[z.accountId]),L=U?{...z,inputBytes:Math.max(z.inputBytes,$.requestBytes),...z.wireAccountId===void 0&&$.wireAccountIdByAccount?.[z.accountId]!==void 0?{wireAccountId:$.wireAccountIdByAccount?.[z.accountId]}:{},...$.now-z.lastSeenAt>=_Z?{lastSeenAt:$.now}:{}}:z;if(!j&&!U)return{assignment:L,next:void 0};return{assignment:L,next:{...Z,stickyAssignments:{...Y,[V]:L},lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let B=$.choose(Y0(Y,$.quotaCheckedAtByAccount,Q?V:void 0));if(!B){if(!j)return{assignment:void 0,next:void 0};return{assignment:void 0,next:{...Z,stickyAssignments:Y,lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let K={accountId:B.accountId,assignedAt:$.now,lastSeenAt:$.now,inputBytes:$.requestBytes,...B.quotaCheckedAt===void 0?{}:{quotaCheckedAt:B.quotaCheckedAt},...$.wireAccountIdByAccount?.[B.accountId]===void 0?{}:{wireAccountId:$.wireAccountIdByAccount?.[B.accountId]}};return{assignment:K,next:{...Z,stickyAssignments:qZ({...Y,[V]:K},V),lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}async function h0(Z,$=O(),V){let J=_(Z.sessionId),X=(await z0($)).stickyAssignments?.[J];if(SZ(X,Z))return X;let Y;return await T(async()=>{await R($,(j)=>{let z=fZ(j,Z);return Y=z.assignment,z.next},V)}),Y}function m0(Z,$){let V=Z.stickyAssignments?.[_($.sessionId)];if(SZ(V,$))return{assignment:V,next:void 0};return fZ(Z,$)}function p0(Z,$=O()){let V=_(Z.sessionId),J=new Set(Z.validPinnedAccountIds);return T(async()=>{await R($,(X)=>{let Y=Date.now(),j=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:J,Y),z=j?.[V];if(z&&z.assignedAt>Z.assignment.assignedAt){if(EZ(X.stickyAssignments,j))return;return{...X,stickyAssignments:j,lastUpdated:Math.max(Y,X.lastUpdated+1)}}let B=z!==void 0&&z.accountId===Z.assignment.accountId&&z.assignedAt===Z.assignment.assignedAt?{...Z.assignment,inputBytes:Math.max(z.inputBytes,Z.assignment.inputBytes),lastSeenAt:Math.max(z.lastSeenAt,Z.assignment.lastSeenAt)}:Z.assignment;return{...X,stickyAssignments:qZ({...j,[V]:B},V),lastUpdated:Math.max(Y,X.lastUpdated+1)}})})}async function g0(Z,$=O()){let V=_(Z),J=!1;return await T(async()=>{await R($,(X)=>{let Y=X.stickyAssignments;if(Y?.[V]===void 0){J=!1;return}J=!0;let{[V]:j,...z}=Y;return{...X,...Object.keys(z).length>0?{stickyAssignments:z}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}})}),J}function d0(){return p}var j0=500;function G0(Z,$,V){return new Promise((J,X)=>{let Y=setTimeout(()=>J(V()),$);Y.unref?.(),Z.then((j)=>{clearTimeout(Y),J(j)},(j)=>{clearTimeout(Y),X(j)})})}function l0(Z,$={}){let V=$.readBudgetMs??j0,J,X,Y=()=>{try{let z=dZ(Z);return`${z.ino}:${z.size}:${z.mtimeMs}`}catch{return}},j=(z)=>{if(X&&X.key===z)return X.promise;let Q=Date.now(),B=eZ(Z).then((L)=>{if(!J||J.readAt<=Q)J={state:L,readAt:Q,key:z};return{state:L,readAt:Q}}),K={key:z,promise:B};X=K;let U=()=>{if(X===K)X=void 0};return B.then(U,U),B};return{get(){let z=Y();if(J&&J.key===z)return Promise.resolve({state:J.state,readAt:J.readAt});return G0(j(z),V,()=>J?{state:J.state,readAt:J.readAt}:{state:E,readAt:0})},read(){return j(Y())},refreshInBackground(){let z=Y();if(J?.key===z)return;j(z)}}}function u0(Z,$,V){let J={assignment:V};Z.delete($),Z.set($,J);while(Z.size>TZ){let X=Z.keys().next().value;if(X===void 0)break;Z.delete(X)}return J}function c0(Z,$){if($.size===0)return Z.state;let V={...Z.state.stickyAssignments},J=!1;for(let[X,Y]of $){if(Y.persistedAt!==void 0&&Z.readAt>Y.persistedAt){$.delete(X);continue}V[X]=Y.assignment,J=!0}if(!J)return Z.state;return{...Z.state,stickyAssignments:V}}function r0(Z){let $=Z.retryDelayMs??500,V=Z.maxRetryDelayMs??30000,J=new Map,X=new Map,Y=new Set,j=0,z=$,Q,B=!1,K=()=>{if(Q||B||X.size===0)return;Q=setTimeout(()=>{Q=void 0;let L=[...X];X.clear(),z=Math.min(z*2,V);for(let[G,D]of L){let N=J.get(G);if(N!==void 0)U(G,D.label,D.write,N)}},z),Q.unref?.()},U=(L,G,D,N)=>{let P;try{P=D()}catch(W){P=Promise.reject(W)}P.then(()=>{if(J.get(L)!==N)return;if(J.delete(L),Y.delete(L))Z.logger.info("sidebar bookkeeping write recovered",{pid:process.pid,write:G});if(Y.size===0)z=$;Z.onWritten?.()},(W)=>{if(J.get(L)!==N)return;let H={pid:process.pid,write:G,error:W instanceof Error?W.message:String(W)};if(B){J.delete(L),Z.logger.debug("sidebar bookkeeping write dropped",H);return}if(Y.has(L))Z.logger.debug("sidebar bookkeeping write failed again",H);else Y.add(L),Z.logger.warn("sidebar bookkeeping write failed; retrying in the background",H);X.set(L,{label:G,write:D}),K()})};return{enqueue(L,G,D){j+=1,J.set(L,j),X.delete(L),U(L,G,D,j)},cancel(L){J.delete(L),X.delete(L),Y.delete(L)},stop(){if(B=!0,Q)clearTimeout(Q);Q=void 0,X.clear()}}}function o0(Z){let $=Z.activeId;if(Z.vaultAccounts!==void 0){let V=FZ(Z).filter((X)=>X.enabled&&X.routable!==!1),J=V.find((X)=>X.id===$)??V[0];return J?{id:J.id,name:J.label??J.id,quota:J.quota,killed:J.killed}:{id:"vault",name:"vault",quota:null,killed:!1}}if($&&$!=="main"){let V=Z.fallbacks.find((J)=>J.enabled&&J.id===$);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,killed:V.killed}}return{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed}}function K0(Z,$=Date.now()){if(!Z)return;return UZ({limits:g.flatMap((V)=>{let J=Z[V];return J?[{kind:"reading",scope:"all",label:V,usedPercent:J.usedPercent,checkedAt:J.checkedAt??Z.checkedAt??$,windowMinutes:J.windowMinutes,resetsAt:J.resetsAt}]:[]}),...Z.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:Z.checkedAt??$}}:{}})}function a0(Z,$=Date.now()){let V=Z?.primary?.usedPercent??null,J=Z?.secondary?.usedPercent??null,X=K0(Z,$);return{primaryUsedPercent:V,secondaryUsedPercent:J,text:!X||X.limits.length===0&&!X.budget?null:QZ(X,{now:$,form:"compact"})}}var L0=300000,B0=0.01,Q0=1;function i0(Z,$,V){if(!Z.resetsAt)return null;let J=new Date(Z.resetsAt).getTime();if(!Number.isFinite(J))return null;let X=J-$,Y=V-X;if(Y<L0)return null;if(Y<$*B0)return null;if(Y>=$)return null;let j=Z.usedPercent,z=Math.min(Math.max(Y/$*100,0),100),Q=j-z,B=Math.abs(Q)<Q0?"on-pace":Q>0?"deficit":"reserve",K=null;if(j>0){let U=Y*100/j,L=X+U;if(L<J)K=new Date(L).toISOString()}return{pacePercent:z,deltaPercent:Q,state:B,runsOutAt:K}}
|
|
2
|
+
export{wZ as zb,C0 as Ab,v0 as Bb,d as Cb,TZ as Db,_ as Eb,O as Fb,E as Gb,f as Hb,eZ as Ib,Z0 as Jb,VZ as Kb,CZ as Lb,$0 as Mb,J0 as Nb,q as Ob,X0 as Pb,S0 as Qb,MZ as Rb,I as Sb,f0 as Tb,A0 as Ub,y0 as Vb,k0 as Wb,w0 as Xb,fZ as Yb,h0 as Zb,m0 as _b,p0 as $b,g0 as ac,d0 as bc,j0 as cc,G0 as dc,l0 as ec,u0 as fc,c0 as gc,r0 as hc,o0 as ic,K0 as jc,a0 as kc,i0 as lc};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as n}from"node:module";var k=Object.defineProperty;var q=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var l=(b)=>b;function m(b,a){this[b]=l.bind(null,a)}var r=(b,a)=>{for(var c in a)k(b,c,{get:a[c],enumerable:!0,configurable:!0,set:m.bind(a,c)})};var t=n(import.meta.url),o=Symbol.dispose||Symbol.for("Symbol.dispose"),p=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),u=(b,a,c)=>{if(a!=null){if(typeof a!=="object"&&typeof a!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var e;if(c)e=a[p];if(e===void 0)e=a[o];if(typeof e!=="function")throw TypeError("Object not disposable");b.push([c,e,a])}else if(c)b.push([c]);return a},v=(b,a,c)=>{var e=typeof SuppressedError==="function"?SuppressedError:function(d,i,f,g){return g=Error(f),g.name="SuppressedError",g.error=d,g.suppressed=i,g},j=(d)=>a=c?new e(d,a,"An error was suppressed during disposal"):(c=!0,d),h=(d)=>{while(d=b.pop())try{var i=d[1]&&d[1].call(d[2]);if(d[0])return Promise.resolve(i).then(h,(f)=>(j(f),h()))}catch(f){j(f)}if(c)throw a};return h()};
|
|
2
|
-
export{q as
|
|
2
|
+
export{q as Ue,r as Ve,t as We,u as Xe,v as Ye};
|