@cortexkit/opencode-openai-auth 1.2.0 → 1.3.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.
Files changed (49) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-CjXETpTA.d.ts → codex-request-B9D0e97Q.d.ts} +145 -28
  3. package/dist/{index-ehjj89rx.js → index-1mbgsxsr.js} +1 -1
  4. package/dist/{index-htvcmtcx.js → index-2pgkrebq.js} +1 -1
  5. package/dist/{index-rwbrhkse.js → index-4v2fs42x.js} +1 -1
  6. package/dist/index-8x1aj7q3.js +2 -0
  7. package/dist/{index-6n4pnfkg.js → index-ex6nx3mq.js} +1 -1
  8. package/dist/{index-qxbchh2d.js → index-gn2b097f.js} +1 -1
  9. package/dist/{index-qp5hdpw8.js → index-m3ctrabv.js} +1 -1
  10. package/dist/{index-03em8hv1.js → index-psjyexj3.js} +15 -15
  11. package/dist/{index-ffg0sgg5.js → index-tddr876f.js} +1 -1
  12. package/dist/index-tn8x5tz8.js +90 -0
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +1 -1
  15. package/dist/{model-CQcw10oW.d.ts → model-BdITTmeb.d.ts} +1 -1
  16. package/dist/{port-file-BDJnzgHH.d.ts → port-file-DbHIVC9a.d.ts} +1 -1
  17. package/dist/{protocol-C-kagE6O.d.ts → protocol-MysYPAho.d.ts} +1 -1
  18. package/dist/rpc/port-file.d.ts +1 -1
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.d.ts +1 -1
  21. package/dist/rpc/protocol.js +1 -1
  22. package/dist/rpc/rpc-client.d.ts +3 -3
  23. package/dist/rpc/rpc-client.js +1 -1
  24. package/dist/{sidebar-state-BfQ4mpZO.d.ts → sidebar-state-CVSok7zv.d.ts} +20 -4
  25. package/dist/sidebar-state.d.ts +1 -1
  26. package/dist/sidebar-state.js +1 -1
  27. package/dist/tui-preferences.js +1 -1
  28. package/dist/tui.d.ts +2 -2
  29. package/dist/v2/server.d.ts +2 -2
  30. package/dist/v2/server.js +1 -1
  31. package/package.json +4 -4
  32. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +69 -1
  33. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +225 -16
  34. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +130 -5
  35. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +10 -2
  36. package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +106 -0
  37. package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +286 -21
  38. package/src/tui-compiled/raw/shared/dc9290c2a7552ba6-watch.js +253 -0
  39. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +4 -1
  40. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +69 -1
  41. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +225 -16
  42. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +130 -5
  43. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +10 -2
  44. package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +106 -0
  45. package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +286 -21
  46. package/src/tui-compiled/runtime/shared/dc9290c2a7552ba6-watch.js +253 -0
  47. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +4 -1
  48. package/dist/index-f21addzm.js +0 -90
  49. package/dist/index-r2s51ac1.js +0 -2
@@ -1,4 +1,4 @@
1
- import{Pe as O,Qe as U,Te as b,Ue as m,Ve as L,Ze as y}from"./index-r2s51ac1.js";import{createHash as Zz,randomUUID as v}from"node:crypto";import{chmod as t,mkdir as r,open as e,readdir as j,rename as zz,rmdir as Gz,stat as Jz,unlink as S}from"node:fs/promises";import{join as R,resolve as D}from"node:path";function l(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function F(z){if(!l(z))return!1;try{return process.kill(z,0),!0}catch(J){return J.code==="EPERM"}}function Cz(z){return(J)=>Kz(J,z)}function Kz(z,J){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(J)&&/^[0-9a-f]{16}$/.test(z.slice(J.length))}function Nz(z){let J=/^port-(\d+)\.json$/.exec(z);return J?Number(J[1]):void 0}function p(z,J){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:V,port:Q,token:K}=z;return l(V)&&Nz(J)===V&&typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=65535&&typeof K==="string"&&K.length>0}async function h(z,J){J?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await S(z).catch(()=>{})}async function Az(z,J,V={}){let Q=async()=>{let K=R(z,`port-${J.pid}.json`);if(O)return await m(z,V.secureDir??!1),await V.beforeWrite?.(),await y(K,JSON.stringify({...J,startedAt:Date.now()}),{stagePath:`${K}.${(V.stageName??v)()}.tmp`}),K;if(await r(z,{recursive:!0,mode:V.secureDir?448:void 0}),V.secureDir)await t(z,448);await V.beforeWrite?.();let W={...J,startedAt:Date.now()},Y=`${K}.${(V.stageName??v)()}.tmp`,N,G=!1;try{N=await e(Y,"wx",384),G=!0,await N.writeFile(JSON.stringify(W),"utf8"),await N.chmod(384),await N.close(),N=void 0,await zz(Y,K),G=!1}finally{if(await N?.close().catch(()=>{}),G)await S(Y).catch(()=>{})}return K};try{return await Q()}catch(K){if(K.code==="ENOENT")return await Q();throw K}}async function Oz(z,J,V,Q){let K;try{K=await j(z,{withFileTypes:!0})}catch(Y){if(Y.code==="ENOENT")return;throw Y}let W=D(J);for(let Y of K){if(!Y.isDirectory()||!V(Y.name))continue;let N=R(z,Y.name),G;try{G=await j(N)}catch(X){if(X.code==="ENOENT")continue;throw X}for(let X of G){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;let $=R(N,X),Z;try{Z=await L($)}catch(H){if(H instanceof U&&H.code!=="ENOENT")throw H;continue}if(Z===void 0)continue;let q;try{q=JSON.parse(Z)}catch{await h($,Q);continue}if(!p(q,X)){await h($,Q);continue}if(!F(q.pid))await S($).catch(()=>{})}if(D(N)!==W)await Gz(N).catch(()=>{})}}async function c(z,J){if(!F(J.pid))return null;let V=R(D(z),`port-${J.pid}.json`);try{if(O)await b(V,"file");let Q=await Jz(V);return`${V}:${Q.dev}:${Q.ino}:${Q.mtimeMs}:${Q.size}`}catch(Q){if(Q instanceof U&&Q.code!=="ENOENT")throw Q;return null}}async function a(z,J,V={}){let Q;try{if(O)await b(z,"directory");Q=await j(z)}catch(G){if(G instanceof U&&G.code!=="ENOENT")throw G;return null}let K=[];for(let G of Q){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;try{let X=JSON.parse(await L(R(z,G)));if(p(X,G))if(F(X.pid))K.push(X);else await S(R(z,G)).catch(()=>{})}catch(X){if(X instanceof U&&X.code!=="ENOENT")throw X}}if(K.length===0)return null;let W=J!==void 0&&J>=1?K.filter((G)=>G.pid===J):[];if(V.exactPid===!0&&W.length===0)return null;let Y=W.length>0?W:K,N=(G)=>typeof G.startedAt==="number"&&Number.isFinite(G.startedAt)?G.startedAt:-1/0;return Y.sort((G,X)=>N(X)-N(G))[0]??null}import{open as Qz}from"node:fs/promises";import{connect as Vz}from"node:net";import{join as Wz,resolve as o}from"node:path";var i=2000,A=new Map,T=new Map;async function Xz(z,J){let V=Wz(o(z),`port-${J.pid}.json`);if(O){let K=JSON.parse(await L(V));if(K.pid!==J.pid||K.port!==J.port||K.token!==J.token)return null;return null}let Q;try{Q=await Qz(V,"r");let K=await Q.stat(),W=JSON.parse(await Q.readFile("utf8"));if(W.pid!==J.pid||W.port!==J.port||W.token!==J.token)return null;return`${V}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch{return null}finally{await Q?.close().catch(()=>{})}}async function s(z,J,V,Q){let K=A.get(z);if(!O&&K&&await c(J,K.entry)===K.identity)return K;A.delete(z);let W=T.get(z);if(W)return W;let Y=(async()=>{let N=await(Q.discover??a)(J,V,Q);if(!N)return null;let G=await Xz(J,N);if(!G)return{entry:N,identity:""};let X={entry:N,identity:G};return A.set(z,X),X})();T.set(z,Y);try{return await Y}finally{if(T.get(z)===Y)T.delete(z)}}async function d(z,J,V,Q=i){return new Promise((K)=>{let W,Y=!1,N=!1,G=($,Z=!1)=>{if(Y)return;Y=!0,clearTimeout(X),W?.destroy(),K({value:$,stale:Z})},X=setTimeout(()=>G(null),Q);try{let $=JSON.stringify(V);W=Vz({host:"127.0.0.1",port:z.port}),W.on("connect",()=>{N=!0,W?.write(`POST /rpc/${J} HTTP/1.0\r
1
+ import{Pe as O,Qe as U,Te as b,Ue as m,Ve as L,Ze as y}from"./index-8x1aj7q3.js";import{createHash as Zz,randomUUID as v}from"node:crypto";import{chmod as t,mkdir as r,open as e,readdir as j,rename as zz,rmdir as Gz,stat as Jz,unlink as S}from"node:fs/promises";import{join as R,resolve as D}from"node:path";function l(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function F(z){if(!l(z))return!1;try{return process.kill(z,0),!0}catch(J){return J.code==="EPERM"}}function Cz(z){return(J)=>Kz(J,z)}function Kz(z,J){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(J)&&/^[0-9a-f]{16}$/.test(z.slice(J.length))}function Nz(z){let J=/^port-(\d+)\.json$/.exec(z);return J?Number(J[1]):void 0}function p(z,J){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:V,port:Q,token:K}=z;return l(V)&&Nz(J)===V&&typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=65535&&typeof K==="string"&&K.length>0}async function h(z,J){J?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await S(z).catch(()=>{})}async function Az(z,J,V={}){let Q=async()=>{let K=R(z,`port-${J.pid}.json`);if(O)return await m(z,V.secureDir??!1),await V.beforeWrite?.(),await y(K,JSON.stringify({...J,startedAt:Date.now()}),{stagePath:`${K}.${(V.stageName??v)()}.tmp`}),K;if(await r(z,{recursive:!0,mode:V.secureDir?448:void 0}),V.secureDir)await t(z,448);await V.beforeWrite?.();let W={...J,startedAt:Date.now()},Y=`${K}.${(V.stageName??v)()}.tmp`,N,G=!1;try{N=await e(Y,"wx",384),G=!0,await N.writeFile(JSON.stringify(W),"utf8"),await N.chmod(384),await N.close(),N=void 0,await zz(Y,K),G=!1}finally{if(await N?.close().catch(()=>{}),G)await S(Y).catch(()=>{})}return K};try{return await Q()}catch(K){if(K.code==="ENOENT")return await Q();throw K}}async function Oz(z,J,V,Q){let K;try{K=await j(z,{withFileTypes:!0})}catch(Y){if(Y.code==="ENOENT")return;throw Y}let W=D(J);for(let Y of K){if(!Y.isDirectory()||!V(Y.name))continue;let N=R(z,Y.name),G;try{G=await j(N)}catch(X){if(X.code==="ENOENT")continue;throw X}for(let X of G){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;let $=R(N,X),Z;try{Z=await L($)}catch(H){if(H instanceof U&&H.code!=="ENOENT")throw H;continue}if(Z===void 0)continue;let q;try{q=JSON.parse(Z)}catch{await h($,Q);continue}if(!p(q,X)){await h($,Q);continue}if(!F(q.pid))await S($).catch(()=>{})}if(D(N)!==W)await Gz(N).catch(()=>{})}}async function c(z,J){if(!F(J.pid))return null;let V=R(D(z),`port-${J.pid}.json`);try{if(O)await b(V,"file");let Q=await Jz(V);return`${V}:${Q.dev}:${Q.ino}:${Q.mtimeMs}:${Q.size}`}catch(Q){if(Q instanceof U&&Q.code!=="ENOENT")throw Q;return null}}async function a(z,J,V={}){let Q;try{if(O)await b(z,"directory");Q=await j(z)}catch(G){if(G instanceof U&&G.code!=="ENOENT")throw G;return null}let K=[];for(let G of Q){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;try{let X=JSON.parse(await L(R(z,G)));if(p(X,G))if(F(X.pid))K.push(X);else await S(R(z,G)).catch(()=>{})}catch(X){if(X instanceof U&&X.code!=="ENOENT")throw X}}if(K.length===0)return null;let W=J!==void 0&&J>=1?K.filter((G)=>G.pid===J):[];if(V.exactPid===!0&&W.length===0)return null;let Y=W.length>0?W:K,N=(G)=>typeof G.startedAt==="number"&&Number.isFinite(G.startedAt)?G.startedAt:-1/0;return Y.sort((G,X)=>N(X)-N(G))[0]??null}import{open as Qz}from"node:fs/promises";import{connect as Vz}from"node:net";import{join as Wz,resolve as o}from"node:path";var i=2000,A=new Map,T=new Map;async function Xz(z,J){let V=Wz(o(z),`port-${J.pid}.json`);if(O){let K=JSON.parse(await L(V));if(K.pid!==J.pid||K.port!==J.port||K.token!==J.token)return null;return null}let Q;try{Q=await Qz(V,"r");let K=await Q.stat(),W=JSON.parse(await Q.readFile("utf8"));if(W.pid!==J.pid||W.port!==J.port||W.token!==J.token)return null;return`${V}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch{return null}finally{await Q?.close().catch(()=>{})}}async function s(z,J,V,Q){let K=A.get(z);if(!O&&K&&await c(J,K.entry)===K.identity)return K;A.delete(z);let W=T.get(z);if(W)return W;let Y=(async()=>{let N=await(Q.discover??a)(J,V,Q);if(!N)return null;let G=await Xz(J,N);if(!G)return{entry:N,identity:""};let X={entry:N,identity:G};return A.set(z,X),X})();T.set(z,Y);try{return await Y}finally{if(T.get(z)===Y)T.delete(z)}}async function d(z,J,V,Q=i){return new Promise((K)=>{let W,Y=!1,N=!1,G=($,Z=!1)=>{if(Y)return;Y=!0,clearTimeout(X),W?.destroy(),K({value:$,stale:Z})},X=setTimeout(()=>G(null),Q);try{let $=JSON.stringify(V);W=Vz({host:"127.0.0.1",port:z.port}),W.on("connect",()=>{N=!0,W?.write(`POST /rpc/${J} HTTP/1.0\r
2
2
  Host: 127.0.0.1:${z.port}\r
3
3
  Connection: close\r
4
4
  Content-Type: application/json\r
@@ -0,0 +1,90 @@
1
+ import{je as y,me as T,pe as h3}from"./index-gn2b097f.js";import{Ge as N3,He as b,Je as w$,Me as z$}from"./index-1mbgsxsr.js";import{Pe as JZ,Qe as w3,Se as T6,Ue as t3,Ve as Y3,Ze as E6}from"./index-8x1aj7q3.js";var P="all",P3=Object.freeze(["primary"]);function I4(Z){return Z.kind==="retired"?Z.retiredAt:Z.checkedAt}function QZ(Z,$){return JSON.stringify([Z,$])}function r(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function R(Z){return typeof Z==="number"&&Number.isFinite(Z)}function A4(Z){return typeof Z==="string"&&Z.length>0}function C(Z,$,z){return Z[$]===void 0||z(Z[$])}function v$(Z){return R(Z)&&Z>0}function _3(Z){return typeof Z==="string"}function g$(Z){if(!r(Z)||!A4(Z.scope)||!A4(Z.label))return!1;switch(Z.kind){case"reading":return R(Z.checkedAt)&&R(Z.usedPercent)&&C(Z,"resetsAt",_3)&&C(Z,"windowMinutes",v$);case"retired":return R(Z.retiredAt);case"absent":return R(Z.checkedAt);default:return!1}}function p$(Z){if(!r(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",_3)&&C(Z,"limit",R)&&C(Z,"used",R)&&C(Z,"remaining",R)&&C(Z,"unit",_3)}function b4(Z){return r(Z)&&R(Z.value)&&Number.isInteger(Z.value)&&Z.value>=0&&R(Z.checkedAt)}function L3(Z){return r(Z)&&Object.values(Z).every(b4)}function S3(Z){if(!r(Z))return;let $=Object.entries(Z).filter(([,z])=>b4(z));return $.length===0?void 0:Object.fromEntries($)}function t(Z){if(o(Z))return Z;if(!r(Z))return;let{counters:$,...z}=Z;if(!o(z))return;let X=S3($);return{...z,...X===void 0?{}:{counters:X}}}function o(Z){if(!r(Z)||!Array.isArray(Z.limits))return!1;let $=new Set;for(let z of Z.limits){if(!g$(z))return!1;let X=QZ(z.scope,z.label);if($.has(X))return!1;$.add(X)}return C(Z,"budget",p$)&&C(Z,"counters",L3)}var w4=900000,h4="no quota reading yet",m4="no limits reported";function v4(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 g4(Z){if(Z%1440===0)return`${Z/1440}d`;if(Z%60===0)return`${Z/60}h`;return`${Z}m`}function p4(Z){if(Z.scope!==P||Z.windowMinutes===void 0)return Z.label;return g4(Z.windowMinutes)}function R3(Z){return Math.min(100,Math.max(0,Z))}function hZ(Z){return Math.round(R3(Z))}function f4(Z){return`${hZ(Z)}% left`}function k4(Z,$,z){let X=Z===void 0?Number.NaN:Date.parse(Z);return{...Number.isFinite(X)&&X>z?{resetIn:v4(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>$&&X<=z}}function l$(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===P)return-1;if($.scope===P)return 1;return Z.scope<$.scope?-1:1}return Z.label<$.label?-1:Z.label>$.label?1:0}function l4(Z,$){let{windows:z,age:X}=x3(Z,$),Y=z.map(({part:G})=>G);return X===void 0?{windows:Y}:{windows:Y,age:X}}function x3(Z,$){if(!Z)return{windows:[]};let{now:z}=$,Y=Z.limits.filter((J)=>J.kind==="reading"&&J.remainingPercent!==void 0).sort(l$).map((J)=>{let B=R3(J.remainingPercent??0);return{scope:J.scope,...J.windowMinutes===void 0?{}:{windowMinutes:J.windowMinutes},part:{kind:"window",name:p4(J),figure:f4(J.remainingPercent??0),remainingPercent:B,checkedAt:J.checkedAt,...k4(J.resetsAt,J.checkedAt,z)}}}),G=Z.budget;if(G){let J=G.remainingPercent,B=G.reached?"credits spent":J!==void 0?`credits ${f4(J)}`:"credits available";Y.push({scope:P,spent:G.reached,part:{kind:"budget",name:"credits",figure:B,...J===void 0?{}:{remainingPercent:R3(J)},checkedAt:G.checkedAt,...k4(G.resetsAt,G.checkedAt,z)}})}if(Y.length>0){let J=z-Math.min(...Y.map(({part:B})=>B.checkedAt));if(J>($.staleAfterMs??w4))return{windows:Y,age:`checked ${v4(J)} ago`}}return{windows:Y}}function d$(Z,$){return x3(Z,$).age!==void 0}function y4(Z){let $=Z.slice(Z.indexOf(":")+1);return $.charAt(0).toUpperCase()+$.slice(1)}function d4(Z){let $=[...new Set(Z.map(y4))],z=new Map($.map((Y)=>[Y,2])),X=(Y)=>Y.slice(0,z.get(Y));for(;;){let Y=new Map;for(let J of $)Y.set(X(J),[...Y.get(X(J))??[],J]);let G=!1;for(let J of Y.values()){if(J.length<2)continue;for(let B of J){let H=z.get(B)??2;if(H<B.length)z.set(B,H+1),G=!0}}if(!G)break}return new Map(Z.map((Y)=>[Y,X(y4(Y))]))}var u$=2;function c$(Z){let $=Z.map((X)=>X.label.trim()||X.scope),z=d4($);return $.map((X)=>z.get(X)??X)}function i$(Z,$){if(!Z||Z.length===0)return;let z=$.filter(({part:B})=>B.kind==="window");if(z.some(({scope:B})=>B===P))return;let X=Z.flatMap((B,H)=>{let W=z.filter(({scope:U})=>U===B.scope).reduce((U,Q)=>U===void 0||(Q.part.remainingPercent??0)<(U.part.remainingPercent??0)?Q:U,void 0);return W?[{group:B,listed:H,window:W}]:[]});if(X.length===0)return;let Y=c$(Z),G=(B)=>B.window.part.remainingPercent??0,J=[...X].sort((B,H)=>G(B)-G(H)||B.listed-H.listed).slice(0,u$).sort((B,H)=>B.listed-H.listed);return J.map((B,H)=>{let{windowMinutes:K}=B.window,W=[Y[B.listed]??B.group.scope,...K===void 0?[]:[g4(K)],`${hZ(G(B))}%`].join(" ");return H===J.length-1?`${W} left`:W})}function s$(Z,$){let{windows:z}=x3(Z,$),X=i$(Z?.groups,z);if(X)return X;let Y=z.filter(({part:Q,scope:F})=>Q.kind==="window"&&F===P),G=z.filter(({part:Q,scope:F})=>Q.kind==="window"&&F!==P),J=d4(G.map(({scope:Q})=>Q)),B=z.find(({part:Q})=>Q.kind==="budget"),H=B?.spent?0:B?.part.remainingPercent,W=[...G.map(({scope:Q,part:F})=>({label:J.get(Q)??Q,remaining:F.remainingPercent??0})),...H===void 0?[]:[{label:"cr",remaining:H}]].reduce((Q,F)=>Q===void 0||F.remaining<Q.remaining?F:Q,void 0),U=Y.map(({part:Q})=>`${Q.name} ${hZ(Q.remainingPercent??0)}%`);if(W)U.push(`${W.label} ${hZ(W.remaining)}%`);if(U.length===0)return z.map(({part:Q})=>Q.figure);return U.map((Q,F)=>F===U.length-1?`${Q} left`:Q)}function u4(Z,$){if($.form==="narrow")return s$(Z,$);let z=l4(Z,$),X=($.form??"full")==="full",Y=z.windows.map((G)=>{let J=X&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${J}`});return z.age===void 0?Y:[...Y,z.age]}function n$(Z,$){let z=u4(Z,$);if(z.length>0)return z.join(" · ");return Z&&Z.limits.length>0?m4:h4}function a$(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 o$(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 r$(Z){return{checkedAt:Z.checkedAt,reached:Z.reached,...Z.remainingPercent===void 0?{}:{remainingPercent:Z.remainingPercent},...Z.resetsAt===void 0?{}:{resetsAt:Z.resetsAt}}}function I(Z,$=P){let z=new Map;for(let K of Z?.limits??[]){if(K.scope!==$&&K.scope!==P)continue;let W=z.get(K.label);if(W===void 0){z.set(K.label,K);continue}let U=K.scope===P?W:K,Q=K.scope===P?K:W;z.set(K.label,U.kind==="reading"?U:Q)}let X=[...z.values()].map(a$).sort(o$),Y=X.filter((K)=>K.kind==="reading"),G=Y.length>0?Y:X,J=G.length>0?Math.min(...G.map((K)=>K.checkedAt)):void 0,B=Z?.budget?.kind==="reading"?r$(Z.budget):void 0,H=S3(Z?.counters);return{scope:$,limits:X,...J===void 0?{}:{checkedAt:J},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H}}}function qZ(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 T3(Z){return Z.kind==="reading"&&typeof Z.usedPercent==="number"&&Number.isFinite(Z.usedPercent)&&Z.usedPercent>=100}function mZ(Z,$){if(typeof Z.resetsAt!=="string")return;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)&&z>$?z:void 0}class vZ extends TypeError{constructor(Z){super(Z);this.name="QuotaCodecError"}}function pZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function gZ(Z){return typeof Z==="number"&&Number.isFinite(Z)}function c4(Z){return Z===void 0||typeof Z==="string"&&Z!==""}function i4(Z){return typeof Z==="string"&&Z!==""}function OZ(Z,$){return Z[$]===void 0||gZ(Z[$])}function E3(Z,$){return Z[$]===void 0||typeof Z[$]==="string"}function t$(Z){return pZ(Z)&&c4(Z.scope)&&i4(Z.label)&&gZ(Z.usedPercent)&&E3(Z,"resetsAt")&&(Z.windowMinutes===void 0||gZ(Z.windowMinutes)&&Z.windowMinutes>0)}function e$(Z){return pZ(Z)&&c4(Z.scope)&&i4(Z.label)}function Z1(Z){if(!pZ(Z))return!1;if(Z.kind==="cleared")return!0;return Z.kind==="reading"&&typeof Z.reached==="boolean"&&OZ(Z,"remainingPercent")&&OZ(Z,"usedPercent")&&E3(Z,"resetsAt")&&OZ(Z,"limit")&&OZ(Z,"used")&&OZ(Z,"remaining")&&E3(Z,"unit")}function s4(Z){if(!pZ(Z)||!gZ(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(!t$(Y))return!1;let G=QZ(Y.scope??P,Y.label);if(X.has(G))return!1;X.add(G)}if(!z.every(e$))return!1;return(Z.budget===void 0||Z1(Z.budget))&&(Z.counters===void 0||L3(Z.counters))}function $1(Z,$){if(Z.scope!==$.scope)return Z.scope<$.scope?-1:1;if(Z.label!==$.label)return Z.label<$.label?-1:1;return 0}function z1(Z,$,z){if($===void 0)return Z;if(Z!==void 0&&z<Z.checkedAt)return Z;return{...$,checkedAt:z}}function X1(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 VZ(Z,$){let z=Z===void 0?void 0:t(Z);if(Z!==void 0&&z===void 0)throw new vZ("stored quota map is malformed");if(!s4($))throw new vZ("quota observation is malformed");let X=z??{limits:[]},Y=$.checkedAt,G=new Map;for(let V of X.limits)G.set(QZ(V.scope,V.label),V);let J=(V)=>{let q=G.get(V);return q===void 0||Y>=I4(q)},B=new Set;for(let V of $.readings??[]){let q=V.scope??P,_=QZ(q,V.label);if(B.add(_),!J(_))continue;G.set(_,{scope:q,label:V.label,kind:"reading",checkedAt:Y,usedPercent:V.usedPercent,...V.resetsAt===void 0?{}:{resetsAt:V.resetsAt},...V.windowMinutes===void 0?{}:{windowMinutes:V.windowMinutes}})}for(let V of $.coverage??[]){let q=V.scope??P,_=QZ(q,V.label);if(B.has(_)||!J(_))continue;let L=G.get(_);G.set(_,L===void 0||L.kind==="absent"?{scope:q,label:V.label,kind:"absent",checkedAt:Y}:{scope:q,label:V.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:K,counters:W,...U}=X,Q=z1(X.budget,$.budget,Y),F=X1(X.counters,$.counters);return{...U,limits:[...G.values()].sort($1),...Q===void 0?{}:{budget:Q},...F===void 0?{}:{counters:F}}}var Y1=Object.freeze({validate:o,decode:t,merge:VZ});function n4(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 G1(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((J)=>J.label===G))return{id:Z,stage:1,gate:3,reason:"unknown-window",window:{scope:$.scope,label:G},pullRequested:!0};let Y=$.limits.filter(T3);for(let G of Y)if(mZ(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 J=mZ(G,X);if(J!==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:J}}return}function k(Z){let $=Z.scope??P,z=Z.requiredLabels??P3,X=[],Y=[],G=[];for(let Q of Z.rows){let F=n4(Q.id,Z,Z.now);if(F){X.push(F);continue}if(Q.kind==="api-key"){G.push({id:Q.id,kind:Q.kind});continue}let V=I(Q.quota,$),q=G1(Q.id,V,z,Z.now);if(q){Y.push(q);continue}G.push({id:Q.id,kind:Q.kind,projection:V})}let J=new Map(G.flatMap((Q)=>{let F=qZ(Q.projection,Z.now);return F?[[Q.id,F]]:[]})),B=J.size>0&&J.size===G.length,H=[];for(let Q of G){let F=J.get(Q.id);if(F===void 0)H.push(Q);else if(B)H.push({...Q,lastPath:!0});else Y.push({id:Q.id,stage:2,reason:"budget-spent",...F})}let K=new Map(Z.rows.map((Q,F)=>[Q.id,F])),W=(Q,F)=>(K.get(Q.id)??0)-(K.get(F.id)??0);Y.sort(W);let U=Y.filter((Q)=>("pullRequested"in Q)).map((Q)=>Q.id);for(let Q of U)Z.requestPull?.(Q);return{admitted:H,refused:Y,excluded:X,pulls:U}}var a4="main";function J1(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 lZ(Z,$,z=a4){if($==="roster"||!Z.includes(z))return[...Z];let X=Z.filter((Y)=>Y!==z);return $==="main-first"?[z,...X]:[...X,z]}function C3(Z){let $=k(Z),z=new Set($.admitted.map((Y)=>Y.id));return{order:lZ(Z.rows.map((Y)=>Y.id),Z.placement??"roster",Z.formerMainId).filter((Y)=>z.has(Y)&&Z.killswitch?.get(Y)!==!1),admission:$}}function B1(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 A3(Z,$,z){if(!$.has(Z.accountId))return!1;return!(typeof Z.wireIdentity==="string"&&typeof z==="string"&&Z.wireIdentity!==z)}function H1(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 f3=900000,r4=0.016666666666666666,I3=0.000001;function dZ(Z,$){for(let z of[Z?.checkedAt,$])if(typeof z==="number"&&Number.isFinite(z))return z;return}function t4(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 e4(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 k3(Z){let $=(Z.classifyStatus??t4)(Z.status);if($==="permanent")return{action:"migrate",reason:"permanent"};if(!Z.quota)return{action:"retain",reason:"unknown"};let z=dZ(Z.quota,Z.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||Z.now-z>f3)return{action:"retain",reason:"stale"};if(Z.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of e4(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=qZ(Z.quota,Z.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:$}}function b3(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,r4);return X/G}function o4(Z,$){if(Z<$)return-1;if(Z>$)return 1;return 0}function K1(Z,$){if(!Z.quota)return;let z=dZ(Z.quota,Z.quotaCheckedAt);if(z===void 0||$-z>f3)return;let X=e4(Z.quota).map((J)=>b3({remainingPercent:J.remainingPercent??Number.NaN,...J.resetsAt===void 0?{}:{resetsAt:J.resetsAt}},Z.reservePercent[J.label]??0,$)),Y=Z.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))X.push(b3({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 Z6(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)=>K1(Y,Z.now)).filter((Y)=>Y!==void 0);if(z.length>0){z.sort((G,J)=>{let B=((Z.pendingBytes.get(G.candidate.accountId)??0)+Z.requestBytes)/Math.max(G.weight,I3),H=((Z.pendingBytes.get(J.candidate.accountId)??0)+Z.requestBytes)/Math.max(J.weight,I3);return B-H||G.candidate.configuredOrder-J.candidate.configuredOrder||o4(G.candidate.accountId,J.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 J=(Y.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-J||Y.configuredOrder-G.configuredOrder||o4(Y.accountId,G.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:dZ(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function y3(Z){let $=k(Z),z=new Map($.admitted.map((V)=>[V.id,V])),X=new Map($.refused.map((V)=>[V.id,V])),Y=new Set($.excluded.map((V)=>V.id)),G=new Set(Z.rows.map((V)=>V.id)),J=Z.pin!==void 0&&A3(Z.pin,G,Z.identities?.get(Z.pin.accountId));if(J&&Z.pin){let V=z.get(Z.pin.accountId);if(V&&Z.killswitch?.get(V.id)!==!1)return{outcome:"dispatch",accountId:V.id,source:"pin",...V.projection?.checkedAt===void 0?{}:{quotaCheckedAt:V.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:$}}let B=Z.pin?X.get(Z.pin.accountId):void 0,H=J&&Z.pin!==void 0&&Z.refusedPinPolicy==="move-on-confirmed-exhaustion"&&(Z.killswitch?.get(Z.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),K=(V)=>{return(typeof Z.rowReservePercent==="function"?Z.rowReservePercent(V):Z.rowReservePercent?.get(V.id))??Z.reservePercent??{}},W=Z.scope,U=Z.rows.map((V,q)=>({row:V,configuredOrder:q})).filter(({row:V})=>!Y.has(V.id)).map(({row:V,configuredOrder:q})=>{let _=Z.killswitch?.get(V.id),L=Z.resetCreditsApplicable?.get(V.id);return{accountId:V.id,quota:V.kind==="api-key"?void 0:z.get(V.id)?.projection??I(V.quota,W),reservePercent:K(V),configuredOrder:q,...L===void 0?{}:{resetCreditsApplicable:L},..._===void 0?{}:{killswitchPasses:_}}}),Q=[],F=J?{action:"retain"}:Z.pin?{action:"clear"}:{action:"none"};while(U.length>0){let V=Z6({candidates:U,pendingBytes:Z.pendingBytes??new Map,requestBytes:Z.requestBytes,now:Z.now,...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}});if(!V)break;let q=X.get(V.accountId);if(q){Q.push(q),U=U.filter((L)=>L.accountId!==V.accountId);continue}let _=Z.identities?.get(V.accountId);return{outcome:"dispatch",accountId:V.accountId,source:V.source,...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt},pin:J&&!H?{action:"retain"}:{action:"assign",pin:{accountId:V.accountId,inputBytes:Z.requestBytes,..._===void 0?{}:{wireIdentity:_},...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt}}},refusedSelections:Q,admission:$}}return{outcome:"no-admissible-account",pin:F,refusedSelections:Q,admission:$}}import{createHash as W1}from"node:crypto";var Q1=86400000,V1=300000,U1=3600000,D1=60000,F1=900000,N1=300000;function m3(Z){return Z instanceof Error?Z.message:String(Z)}function j1(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 v3(Z){let $=m3(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 $6(Z){return W1("sha256").update(Z).digest("hex")}function z6(Z){let $=$6(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(j1(Z.error))Y=Math.min(U1,V1*2**Math.min(X-1,6));else Y=Q1;return{message:m3(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+Y,retryCount:X,tokenHash:$}}function e(Z,$,z){if(!Z?.nextRetryAt||Z.nextRetryAt<=z)return!1;if(!$)return!0;return Z.tokenHash===$6($)}function uZ(Z,$){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((Z.nextRetryAt??$)-$)/1000))}s after: ${Z.message}`}function MZ(Z){let z=(Z.previous?.retryCount??0)+1,X,Y=Z.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(v3(Z.error))X=Math.min(F1,D1*2**Math.min(z-1,6));else X=N1;return{message:m3(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+X,retryCount:z}}function UZ(Z,$){if(!Z?.nextRetryAt||Z.nextRetryAt<=$)return!1;return!0}function g3(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 X6}from"node:http";import{setTimeout as q1}from"node:timers/promises";var nZ="app_EMoamEEZ73f0CkXaXp7hrann",zZ="https://auth.openai.com",PZ=1455,O1=3000,M1="cortexkit-opencode-openai-auth";function B6(Z){return`${M1}/${Z}`}var H6="main",_1=`"${H6}" is a reserved account id; choose a different label.`;function K6(Z){let $=new Uint8Array(Z),z=String.fromCharCode(...$);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function P1(){let $=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=K6(await crypto.subtle.digest("SHA-256",new TextEncoder().encode($)));return{verifier:$,challenge:z}}function Y6(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 G6(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 iZ(Z){if(Z.id_token){let $=Y6(Z.id_token),z=$&&G6($);if(z)return z}if(Z.access_token){let $=Y6(Z.access_token);return $?G6($):void 0}return}function L1(Z){return typeof Z==="string"&&Z.toLowerCase()===H6}function p3(Z){if(L1(Z))throw Error(_1);return Z}function S1(Z,$,z){let X=new URLSearchParams({response_type:"code",client_id:nZ,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 R1(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:nZ,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function x1(Z){return Z.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var T1=`<!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>`,cZ=(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">${x1(Z)}</div>
85
+ </div>
86
+ </body>
87
+ </html>`,sZ=[],_Z,w=new Map;function J6(Z,$){return new Promise((z,X)=>{let Y=(J)=>{Z.off("listening",G),X(J)},G=()=>{Z.off("error",Y),z()};Z.once("error",Y),Z.once("listening",G),Z.listen(PZ,$)})}function W6(Z){Z.close(()=>{}),Z.closeIdleConnections?.(),setTimeout(()=>{Z.closeAllConnections?.()},25).unref?.()}function ZZ(){return w.size}function XZ(Z){if(w.delete(Z),ZZ()===0)$Z()}async function E1(){let Z=`http://localhost:${PZ}/auth/callback`;if(sZ.length>0)return{port:PZ,redirectUri:Z};if(_Z)return _Z;_Z=(async()=>{let $=(G,J)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${PZ}`);if(B.pathname==="/auth/callback"){let H=B.searchParams.get("code"),K=B.searchParams.get("state"),W=B.searchParams.get("error"),U=B.searchParams.get("error_description");if(W){let F=U||W;if(K){let V=w.get(K);if(V)V.reject(Error(F)),XZ(K);else if(ZZ()===0)$Z()}else if(ZZ()===0)$Z();J.writeHead(200,{"Content-Type":"text/html"}),J.end(cZ(F));return}if(!K){if(ZZ()===0)$Z();J.writeHead(400,{"Content-Type":"text/html"}),J.end(cZ("Missing state parameter"));return}if(!H){if(ZZ()===0)$Z();J.writeHead(400,{"Content-Type":"text/html"}),J.end(cZ("Missing authorization code"));return}let Q=w.get(K);if(!Q){if(ZZ()===0)$Z();J.writeHead(400,{"Content-Type":"text/html"}),J.end(cZ("Unknown state — authorization may have expired"));return}XZ(K),R1(H,Z,Q.pkce).then((F)=>Q.resolve(F)).catch((F)=>Q.reject(F)),J.writeHead(200,{"Content-Type":"text/html"}),J.end(T1);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),K=H?[H]:[...w.keys()];J.writeHead(200),J.end("Login cancelled");for(let W of K){let U=w.get(W);if(!U)continue;U.reject(Error("Login cancelled")),XZ(W)}if(ZZ()===0)$Z();return}J.writeHead(404),J.end("Not found")},z=X6($);await J6(z,"127.0.0.1");let X=[z],Y=X6($);try{await J6(Y,"::1"),X.push(Y)}catch(G){let J=G.code;if(J!=="EADDRNOTAVAIL"&&J!=="EAFNOSUPPORT")throw W6(z),G}return sZ=X,{port:PZ,redirectUri:Z}})();try{return await _Z}finally{_Z=void 0}}function $Z(){let Z=sZ;sZ=[];for(let $ of Z)W6($)}function C1(Z,$,z=300000,X){return new Promise((Y,G)=>{if(X?.aborted){XZ($),G(Error("Login cancelled"));return}let J=setTimeout(()=>{if(w.get($))XZ($),G(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(J),w.get($))XZ($),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);w.set($,{pkce:Z,state:$,resolve:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);G(H)}})})}async function A1(Z){let $=await fetch(`${zZ}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":B6(Z)},body:JSON.stringify({client_id:nZ})});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 I1(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,J=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-J>G)throw Error("Device authorization expired");let B=await fetch(`${zZ}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":B6($)},body:JSON.stringify({device_auth_id:Z.device_auth_id,user_code:Z.user_code})});if(B.ok){let W=await B.json(),U=await fetch(`${zZ}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:W.authorization_code,redirect_uri:`${zZ}/deviceauth/callback`,client_id:nZ,code_verifier:W.code_verifier}).toString()});if(!U.ok)throw Error(`Token exchange failed: ${U.status}`);return await U.json()}if(B.status!==403&&B.status!==404)throw Error(`Device authorization failed: ${B.status}`);let H=G-(Date.now()-J);if(H<=0)throw Error("Device authorization expired");let K=Math.min(X+O1,H);try{await q1(K,void 0,{signal:z})}catch(W){if(W instanceof Error&&W.name==="AbortError")throw Error("Device authorization cancelled");throw W}}}async function S8(Z){let{label:$,headless:z=!1,signal:X,version:Y}=Z;if(p3($),z){let{deviceData:W,url:U,instructions:Q}=await A1(Y),F=(async()=>{let V=await I1(W,Y,X),q=Date.now(),_=iZ(V);return{id:p3($||_||crypto.randomUUID()),label:$||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:q+(V.expires_in??3600)*1000,enabled:!0,addedAt:q,lastUsed:q,lastRefreshedAt:q,accountId:_}})();return{url:U,instructions:Q,completion:F}}let{redirectUri:G}=await E1(),J=await P1(),B=K6(crypto.getRandomValues(new Uint8Array(32)).buffer),H=S1(G,J,B),K=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let W=await C1(J,B,void 0,X),U=Date.now(),Q=iZ(W);return{id:p3($||Q||crypto.randomUUID()),label:$||void 0,type:"oauth",access:W.access_token,refresh:W.refresh_token,expires:U+(W.expires_in??3600)*1000,enabled:!0,addedAt:U,lastUsed:U,lastRefreshedAt:U,accountId:Q}}finally{XZ(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:K}}function aZ(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 l3(Z){let $=Number(Z);return Number.isFinite($)&&$>0?$:void 0}function Q6(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function V6(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=l3(Z.get(`${Y}-window-minutes`)),J=aZ(Z.get(`${Y}-reset-at`)??void 0);if(X===0&&Z.get(`${Y}-window-minutes`)==="0"&&!J)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:J,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var F6=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function N6(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 x8(Z){if(F6.some((Y)=>N6(Z,Y)==="invalid"))return{};let $={},z=V6(Z,"x-codex-primary-used-percent");if(z)$.primary=z;let X=V6(Z,"x-codex-secondary-used-percent");if(X)$.secondary=X;return $}function T8(Z){let $=F6.map((z)=>N6(Z,z));return $.includes("valid")&&!$.includes("invalid")}function U6(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=l3(Z.window_minutes),z=aZ(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 E8(Z){let $={},z=U6(Z.rate_limits?.primary);if(z)$.primary=z;let X=U6(Z.rate_limits?.secondary);if(X)$.secondary=X;return $}function DZ(Z){if(Z==null||Z==="")return;let $=Number(Z);return Number.isFinite($)&&$>=0?$:void 0}function D6(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=l3(Z.limit_window_seconds),z=aZ(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 j6(Z){let $={},z=D6(Z.rate_limit?.primary_window);if(z)$.primary=z;let X=D6(Z.rate_limit?.secondary_window);if(X)$.secondary=X;let Y=Q6(Z.rate_limit_reset_credits?.available_count);if(Y!==void 0)$.resetCreditsAvailable=Y;let G=Q6(Z.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)$.resetCreditsApplicable=G;let J=Z.spend_control?.individual_limit;if(Z.spend_control===null||J===null)$.spendControlCleared=!0;if(J&&typeof Z.spend_control?.reached==="boolean"){let H=DZ(J.limit),K=DZ(J.used),W=DZ(J.remaining),U=DZ(J.used_percent),Q=DZ(J.remaining_percent);if(H!==void 0&&K!==void 0&&W!==void 0&&U!==void 0&&Q!==void 0)$.spendControl={limit:H,used:K,remaining:W,usedPercent:U,remainingPercent:Q,resetsAt:aZ(J.reset_at),unit:J.unit,source:J.source,reached:Z.spend_control.reached}}let B=Z.credits;if(B&&typeof B.has_credits==="boolean"&&typeof B.unlimited==="boolean"&&typeof B.overage_limit_reached==="boolean"){let H=DZ(B.balance);$.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{}}}return $}import{ClaustrumClient as O0}from"@cortexkit/claustrum-client";import{resolve as q6}from"node:path";import{storeIdentity as w1}from"@cortexkit/claustrum-client";import{SubcClient as O6}from"@cortexkit/subc-client";import{ClaustrumCredentialError as b1}from"@cortexkit/claustrum-client";import{SocketClosedError as f1,SocketTimeoutError as k1,SubcCallError as y1}from"@cortexkit/subc-client";class N extends Error{kind;constructor(Z,$){super($);this.name="ClaustrumConsumerError",this.kind=Z}}var d3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class YZ extends N{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function g(Z){if(Z instanceof YZ||Z instanceof f1||Z instanceof k1)return"unreachable";let $=Z instanceof b1||Z instanceof y1?Z.code:Z instanceof Error&&("code"in Z)?Z.code:void 0;if(typeof $!=="string"||!Object.hasOwn(d3,$))return"answered";return d3[$]}var u3=300000,oZ=300000,c3=1000;class LZ{#Z;#$=0;restart(){this.#$=0}continuous(Z){let $=Z.kind==="changed"&&Z.seq===this.#$+1&&(this.#Z===void 0||Z.epoch===this.#Z);return this.#Z=Z.epoch,this.#$=Z.seq,$}}class rZ{#Z;#$;#Y;#z=!1;constructor(Z,$){this.#Z=Z,this.#$=$}get running(){return this.#Y}request(){if(this.#Y)return this.#z=!0,this.#Y;return this.#Y=(async()=>{do{this.#z=!1;try{await this.#Z()}catch(Z){this.#$(Z)}}while(this.#z)})().finally(()=>{this.#Y=void 0}),this.#Y}}class tZ{#Z;#$=new LZ;#Y;#z="polling";#H;#K;#X=!1;#G;#W=!1;#J=0;constructor(Z){this.#Z=Z,this.#Y=new rZ(async()=>{let $=this.#W;if(this.#W=!1,$||this.#G!==this.#Z.view())await this.#Z.discover()},($)=>{if(!this.#X)this.#Z.onError?.($)})}get mode(){return this.#z}start(){if(this.#X||this.#H||this.#K)return;if(typeof this.#Z.client.watchScoped!=="function"){this.#D("fallback","client-without-watch");return}this.#U(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#K)(this.#Z.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let Z=this.#H;this.#H=void 0,Z?.handle.stop()}#D(Z,$){if(this.#z===Z)return;this.#z=Z,this.#Z.logger?.debug("claustrum vault watch",{mode:Z,reason:$}),this.#Z.onMode?.(Z)}#Q(Z,$){this.#K=(this.#Z.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,!this.#X)$()},Z),this.#K.unref?.()}async#U(Z){let $;try{$=await this.#Z.enrollmentToken()}catch(J){if(this.#X)return;this.#Z.onError?.(J),this.#F("token-unreadable");return}let z=this.#Z.client.watchScoped;if(this.#X||this.#H||!z)return;this.#$.restart(),this.#W=Z;let X,Y;try{Y=z.call(this.#Z.client,(J)=>{if(this.#X||!X||this.#H!==X)return;if(X.notices++,X.notices===1)this.#Z.onReachable?.(),X.acceptedAt=(this.#Z.now??Date.now)(),this.#D("watching","accepted");if(!this.#$.continuous(J))this.#W=!0;this.#G=J.view,this.#Y.request()},{enrollmentToken:$})}catch(J){this.#Z.onError?.(J),this.#F("watch-failed");return}X={handle:Y,notices:0},this.#H=X,this.#D("polling",Z?"resubscribing":"opening");let G=X;Y.closed.then((J)=>this.#V(G,J),(J)=>this.#V(G,{kind:"transport_lost",error:J}))}#V(Z,$){if(this.#X||this.#H!==Z)return;if(this.#H=void 0,$.kind==="stopped")return;if($.kind==="transport_lost")this.#Z.onTransportLost?.();if($.kind==="unsupported"){this.#D("fallback","vault-without-watch");return}if($.kind==="refused"){this.#F("refused");try{this.#Z.onRefused($.error)}catch(z){this.#Z.onError?.(z)}return}if(Z.notices>0){let z=(this.#Z.now??Date.now)();if(Z.acceptedAt!==void 0&&z-Z.acceptedAt>=300000)this.#J=0;let X=Math.min(1000*2**Math.min(this.#J,16),300000);this.#J++,this.#D("polling","resubscribing"),this.#Q(X,()=>void this.#U(!0));return}this.#F($.kind)}#F(Z){this.#D("fallback",Z),this.#Q(300000,()=>void this.#U(!1))}}function M6(Z){let $=Z.identity??w1(Z.projectRoot??process.cwd(),Z.storagePath??process.cwd());return{connectionFile:Z.connectionFile,async getUsage(){let z,X=!1,Y,G=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),J=(async()=>{if(z=Z.connector?await Z.connector({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}):await O6.connect({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}),X)throw z.close(),Error("insula usage timeout");let B=await z.routeOpen({kind:"management_surface",module_id:"insula"},$);return await z.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([J,G])}finally{X=!0,clearTimeout(Y),z?.close()}},watchUsage(z){let X,Y,G=!1,J=(async()=>{let B,H=new Promise((W,U)=>{B=setTimeout(()=>U(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),K=(async()=>{let W=Math.min(Z.handshakeTimeoutMs??3000,3000),U=Z.connector?await Z.connector({connectionFile:Z.connectionFile,handshakeTimeoutMs:W}):await O6.connect({connectionFile:Z.connectionFile,handshakeTimeoutMs:W});if(X=U,G){U.close();return}let Q=await U.routeOpen({kind:"management_surface",module_id:"insula"},$);if(G){U.close();return}Y=U.subscribe(Q,{method:"usage.watch"},z)})();try{await Promise.race([K,H])}catch(W){throw G=!0,W}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{G=!0,X?.close()});return{stop(){if(G)return;G=!0,Y?.unsubscribe(),X?.close()},closed:J}}}}var s3=60000,h1=4*s3,i3=new Map,eZ=new Map;function Z3(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function m1(Z){let $;try{$=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Z))}catch{return}if(!Z3($)||typeof $.kind!=="string"||typeof $.epoch!=="string"||$.epoch.length===0||typeof $.seq!=="number"||!Number.isSafeInteger($.seq)||$.seq<1||$.provider!==void 0&&typeof $.provider!=="string")return;return{kind:$.kind,epoch:$.epoch,seq:$.seq,...typeof $.provider==="string"&&{provider:$.provider}}}function v1(Z){return Z instanceof Error&&"code"in Z&&typeof Z.code==="string"?Z.code:void 0}class _6{transport;key;#Z=[];#$=new rZ(async()=>{try{let Z=await this.transport.getUsage();if(!Z3(Z)||!Array.isArray(Z.result)||Z.error!==void 0)throw Error("unavailable insula usage");this.#Z=Z.result.filter(($)=>Z3($)&&typeof $.provider==="string")}catch{this.#Z=[]}},()=>{});#Y=new LZ;#z="polling";#H=0;#K=0;#X=new Map;#G;#W;#J={};#D=0;constructor(Z,$){this.transport=Z,this.key=$}refresh(Z){if(this.#$.running)return this.#$.running;if(this.#z==="watching")return Promise.resolve();for(let[z,X]of eZ)if(Z-X>=s3)eZ.delete(z);let $=eZ.get(this.key);if($!==void 0&&Z-$<s3)return Promise.resolve();return eZ.set(this.key,Z),this.#$.request()}watchMode(){return this.#z}watch(Z={}){this.#H++;let $=Z.provider;if($===void 0)this.#K++;else this.#X.set($,(this.#X.get($)??0)+1);if(this.#H===1)this.#J=Z,this.#V();let z=!1;return()=>{if(z)return;if(z=!0,$===void 0)this.#K--;else{let X=(this.#X.get($)??1)-1;if(X>0)this.#X.set($,X);else this.#X.delete($)}if(--this.#H===0)this.#Q()}}#Q(){if(this.#W)(this.#J.clearTimeoutImpl??clearTimeout)(this.#W);this.#W=void 0;let Z=this.#G;this.#G=void 0,Z?.handle?.stop(),this.#z="polling"}#U(Z){this.#W=(this.#J.setTimeoutImpl??setTimeout)(()=>{if(this.#W=void 0,this.#H>0&&!this.#G)this.#V()},Z),this.#W.unref?.()}#V(){let Z=this.transport.watchUsage;if(!Z){this.#z="fallback";return}this.#z="polling",this.#Y.restart();let $={notices:0};this.#G=$;let z;try{z=Z.call(this.transport,(X)=>this.#F($,X))}catch(X){this.#B($,X);return}$.handle=z,z.closed.then(()=>this.#B($,void 0),(X)=>this.#B($,X))}#F(Z,$){if(this.#G!==Z)return;if(Z.notices++,Z.notices===1)this.#z="watching";if(Z.notices===2)this.#D=0;let z=m1($);if(!z)this.#Y.restart();if(!(z?this.#Y.continuous(z):!1)||z?.provider===void 0||this.#K>0||this.#X.has(z.provider))this.#$.request()}#B(Z,$){if(this.#G!==Z)return;this.#G=void 0;let z=v1($);if(z==="unknown_method"||z==="usage_watch_limit"){this.#z="fallback";return}if(Z.notices>0){let X=Math.min(c3*2**Math.min(this.#D,16),oZ);this.#D++,this.#z="polling",this.#U(X);return}if(this.#z="fallback",this.#$.request(),$===void 0||g($)==="unreachable")this.#U(oZ)}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||!Z3(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=h1)continue;return{entry:X,context:{fetchedAt:Y,...typeof X.source==="string"&&{source:X.source}}}}return}}function n3(Z,$){let z=JSON.stringify([q6(Z.connectionFile),q6($)]),X=i3.get(z);if(!X)X={source:new _6(Z,z),refs:0},i3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)i3.delete(z)}}}import{ClaustrumCredentialError as f9}from"@cortexkit/claustrum-client";function a3(Z){let $=new AbortController,z=[],X=!1,Y=()=>{if(X)return;X=!0;for(let{source:B,listener:H}of z)B.removeEventListener("abort",H);z.length=0},G=(B)=>{if(X||$.signal.aborted)return;$.abort(B),Y()},J=Z.find((B)=>B.aborted);if(J)return $.abort(J.reason),{signal:$.signal,dispose:Y};for(let B of Z){if($.signal.aborted)break;let H=()=>G(B.reason);if(z.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)G(B.reason)}return{signal:$.signal,dispose:Y}}import{ClaustrumCredentialError as i6}from"@cortexkit/claustrum-client";import{createHash as g1,randomBytes as p1,randomUUID as l1}from"node:crypto";import{constants as P6}from"node:fs";import{chmod as d1,mkdir as u1,open as C6,readFile as o3,realpath as c1,rename as i1,stat as A6,unlink as I6}from"node:fs/promises";import{basename as b6,dirname as l,extname as L6,isAbsolute as S6,join as e3,resolve as s1}from"node:path";import{ClaustrumCredentialError as n1,ClaustrumClient as a1,writeEnrollmentTokenFile as o1}from"@cortexkit/claustrum-client";var r1=1,z3=16384,f6=30000,Z4=/^[0-9a-f]{64}$/,k6=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),y6=new Set(["pending_queue_full"]);function r3(Z){if(!(Z instanceof n1))return;if(k6.has(Z.code))return{code:Z.code,disposition:"terminal"};if(y6.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 N("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${Z}-${$}`}function e1(Z){return a1.connect(Z)}function w6(Z){let $=L6(Z)||".json",z=b6(Z,L6(Z));return{statePath:e3(l(Z),`${z}-state${$}`),tokenPath:Z}}function Z0(Z){let $=Z.override?.trim();if($&&!S6($)&&!Z.cwd)throw new N("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=$?S6($)?$:s1(Z.cwd,$):e3(Z.stateDir,`${Z.host}-enrollment.json`);return w6(z)}function h6(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function $3(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0}function m6(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=1}function SZ(){return new N("invalid-state","invalid Claustrum enrollment state")}function G3(Z){if(!h6(Z)||Z.version!==r1||typeof Z.proposedName!=="string"||Z.proposedName.length===0)throw SZ();if(Z.phase==="pending"){if(!Z4.test(String(Z.requestSecret??""))||Z.requestId!==void 0&&(typeof Z.requestId!=="string"||Z.requestId.length===0)||!$3(Z.createdAt)||!$3(Z.updatedAt))throw SZ();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)||!m6(Z.tokenGeneration)||!$3(Z.updatedAt))throw SZ();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"||!$3(Z.updatedAt))throw SZ();return{version:1,phase:Z.phase,proposedName:Z.proposedName,...Z.errorCode!==void 0&&{errorCode:Z.errorCode},updatedAt:Z.updatedAt}}throw SZ()}function $4(Z){if(!h6(Z)||!Z4.test(String(Z.token??""))||!m6(Z.token_generation))throw new N("invalid-token","invalid Claustrum enrollment token file");return{token:Z.token,token_generation:Z.token_generation}}function $0(Z){if(!Z.isFile())throw new N("unsafe-file","Claustrum enrollment file must be a regular file");if((Z.mode&63)!==0)throw new N("unsafe-file","Claustrum enrollment file must be owner-only");let $=process.geteuid?.();if($!==void 0&&Z.uid!==$)throw new N("unsafe-file","Claustrum enrollment file must be owned by the current user")}function R6(Z){try{return JSON.parse(Z)}catch{throw new N("invalid-state","Claustrum enrollment file is not valid JSON")}}async function d(Z){if(JZ)try{await t3(l(Z));let z=await Y3(Z,!0);if(Buffer.byteLength(z)>z3)throw new N("unsafe-file","Claustrum enrollment file is too large");return R6(z)}catch(z){if(z.code==="ENOENT")return;throw z}let $;try{$=await C6(Z,P6.O_RDONLY|P6.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new N("unsafe-file","Claustrum enrollment file could not be opened safely")}try{$0(await $.stat());let z=Buffer.alloc(z3+1),{bytesRead:X}=await $.read(z,0,z.byteLength,0);if(X>z3)throw new N("unsafe-file","Claustrum enrollment file is too large");return R6(z.subarray(0,X).toString("utf8"))}finally{await $.close()}}function x6(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 z0(Z,$,z){try{let[X,Y]=await Promise.all([o3(z.passwdPath??"/etc/passwd","utf8"),o3(z.groupPath??"/etc/group","utf8")]),G=x6(X,7),J=x6(Y,4);if(!G||!J)return!1;let B=G.filter((U)=>Number(U[2])===Z),H=J.filter((U)=>Number(U[2])===$);if(B.length!==1||H.length!==1)return!1;let K=B[0]?.[0],W=H[0]?.[3]??"";return(W===""||W.split(",").every((U)=>U===K))&&!G.some((U)=>Number(U[2])!==Z&&Number(U[3])===$)}catch{return!1}}function v6(Z){if(!Z.passwdPath&&!Z.groupPath)return;return{fs:{readFile:($)=>o3($==="/etc/passwd"?Z.passwdPath??$:$==="/etc/group"?Z.groupPath??$:$)}}}async function g6(Z,$={}){if(!JZ){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await c1(Z)}catch{return}let G;for(;;){let J=await A6(Y).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0){if(G===void 0)G=X!==void 0&&await z0(z,X,$);if((J.mode&2)!==0||J.uid!==z||J.gid!==X||!G)throw new N("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=l(Y);if(B===Y)return;Y=B}}try{await T6(Z,v6($))}catch(z){if(!(z instanceof w3))throw z;throw new N("unsafe-file",`Claustrum enrollment parent refused: ${z.path} (${z.reason??z.code}). Use a folder that other users cannot write or replace.`)}}async function X3(Z,$={}){if(JZ){await t3(Z,!1,v6($));return}await u1(Z,{recursive:!0,mode:448});let z=await A6(Z),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new N("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((z.mode&63)!==0)await d1(Z,448)}async function GZ(Z,$,z={}){let X=l(Z);await X3(X,z),await g6(X,z);let Y=`${JSON.stringify($)}
89
+ `;if(Buffer.byteLength(Y)>z3)throw new N("invalid-state","Claustrum enrollment state is too large");if(JZ)return E6(Z,Y);let G=e3(X,`.${b6(Z)}.${process.pid}.${l1()}.tmp`),J,B=!1;try{J=await C6(G,"wx",384),B=!0,await J.writeFile(Y,"utf8"),await J.chmod(384),await J.sync(),await J.close(),J=void 0,await i1(G,Z),B=!1}finally{if(await J?.close().catch(()=>{}),B)await I6(G).catch(()=>{})}}async function z4(Z,$){let z=await d(Z.tokenPath),X=z===void 0?void 0:$4(z),Y=await d(Z.statePath),G=Y===void 0?void 0:G3(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 p(G)}async function X0(Z,$){let z;try{z=await z4(Z,$)}catch(X){if(!(X instanceof N)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await d(Z.statePath);if(Y===void 0)return"unreadable";let G=G3(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 u(Z){let $=await d(Z);if($===void 0)throw new N("not-enrolled","Claustrum enrollment is not configured");return $4($)}function p(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 p6(){return new N("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class l6{#Z;#$;#Y;#z;#H;#K;#X;constructor(Z){this.#X=Z.ancestorOptions??{},this.#Z=Z.client,this.#$=Z.paths,this.#Y=Z.proposedName,this.#z=Z.now??Date.now,this.#H=Z.mintSecret??(()=>p1(32).toString("hex")),this.#K=Z.writeTokenFile??o1}async status(){return z4(this.#$,this.#Y)}async resetTerminal(){return d6(this.#$,this.#Y)}async#G(Z,$){let z={version:1,phase:"blocked",proposedName:Z.proposedName,errorCode:$,updatedAt:this.#z()};return await GZ(this.#$.statePath,z,this.#X),p(z)}async reconcile(){await X3(l(this.#$.statePath),this.#X);let Z=await T({name:"ceremony",path:this.#$.statePath,ttlMs:f6,renew:!0});if(!Z)return{state:"busy"};try{let $=await d(this.#$.tokenPath),z=$===void 0?void 0:$4($),X=await d(this.#$.statePath),Y=X===void 0?void 0:G3(X);if(Y&&Y.proposedName!==this.#Y)throw p6();if(z){if(!Y||Y.phase==="pending"){let J={version:1,phase:"approved",proposedName:Y?.proposedName??this.#Y,tokenGeneration:z.token_generation,updatedAt:this.#z()};await GZ(this.#$.statePath,J,this.#X),Y=J}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:z.token_generation}}if(Y?.phase==="approved"){let J={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#z()};return await GZ(this.#$.statePath,J,this.#X),p(J)}if(Y&&Y.phase!=="pending")return p(Y);if(!Y){let J=this.#z();if(Y={version:1,phase:"pending",proposedName:this.#Y,requestSecret:this.#H(),createdAt:J,updatedAt:J},!Z4.test(Y.requestSecret))throw new N("invalid-state","invalid minted Claustrum enrollment secret");await GZ(this.#$.statePath,Y,this.#X)}if(!Y.requestId)try{let J=g1("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B=await this.#Z.enrollPropose({name:Y.proposedName,requestSecretHash:J});Y={...Y,requestId:B.requestId,updatedAt:this.#z()},await GZ(this.#$.statePath,Y,this.#X)}catch(J){let B=r3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};return this.#G(Y,B.code)}let G=Y.requestId;if(!G)return p(Y);try{let J=await this.#Z.enrollPoll({requestId:G,requestSecret:Y.requestSecret});if(J.status==="pending")return p(Y);if(J.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#z()};return await GZ(this.#$.statePath,H,this.#X),p(H)}await X3(l(this.#$.tokenPath),this.#X),await g6(l(this.#$.tokenPath),this.#X),await this.#K(this.#$.tokenPath,{token:J.token,token_generation:J.tokenGeneration});let B={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:J.name,tokenGeneration:J.tokenGeneration,updatedAt:this.#z()};return await GZ(this.#$.statePath,B,this.#X),p(B)}catch(J){let B=r3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:G,retryCode:B.code};return this.#G(Y,B.code)}}finally{await Z.release()}}}async function d6(Z,$){await X3(l(Z.statePath));let z=await T({name:"ceremony",path:Z.statePath,ttlMs:f6,renew:!0});if(!z)return"busy";try{if(await d(Z.tokenPath)!==void 0)return"refused-approved";let X=await d(Z.statePath);if(X===void 0)return"idle";let Y=G3(X);if(Y.proposedName!==$)throw p6();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await I6(Z.statePath),"reset"}finally{await z.release()}}var RZ="claustrum-tombstone:v1:";function J3(Z){return`${RZ}${Z}`}function X4(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function B3(Z){return typeof Z==="string"&&Z.startsWith(RZ)}function u6(Z,$){if(!X4(Z)||Z.type!=="oauth")return!1;return Z.refresh===J3($)}function c6(Z,$){if(u6(Z,$))return"placeholder";if(X4(Z)&&Z.type==="oauth"&&typeof Z.refresh==="string"&&Z.refresh.length>0&&!B3(Z.refresh))return"login";if(X4(Z)&&Z.type==="api"&&typeof Z.key==="string"&&Z.key.length>0)return"login";return"empty"}function Y0(Z){let $=c6(Z.auth,Z.provider);if(Z.mode==="custody"&&$==="login")throw new N("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 N("host-slot-placeholder",`${Z.provider} host slot holds the vault placeholder; sign in to use local accounts`);return $}function s6(Z,$){return $!==void 0&&!$.fromKeptReceipt&&!Z.fromKeptReceipt&&$.credentialId===Z.credentialId&&$.accountIdentity===Z.accountIdentity&&$.recordVersion!==Z.recordVersion}function G0(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 G4=b("claustrum");function B4(Z,$,z,X=G4){let Y=s6($,z);return X.debug("scoped 401 re-authorized",{site:Z,credentialId:$.credentialId,servedVersion:$.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:G0($,z)}),Y}var J4=300000,n6=60000;function Y4(){return new N("invalid-material","Claustrum returned invalid credential material")}function J0(Z){let $=Z.trim();if($.startsWith("{")){let z;try{z=JSON.parse($)}catch{throw Y4()}if(!z||typeof z!=="object")throw Y4();let X=z,Y=X.access_token??X.access;$=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test($)||$.startsWith(RZ))throw Y4();return $}function B0(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}function H0(Z){let{grants:$,grantTuples:z}=Z;if($===void 0||z===void 0)return;return Object.freeze({grants:$,tuples:Object.freeze(z.map(({selectorKind:X,selector:Y,operation:G})=>Object.freeze({selectorKind:X,selector:Y,operation:G})))})}class H3{#Z;#$;#Y;#z;#H;#K;#X;#G=new WeakMap;#W=new WeakMap;#J=new Map;#D=new WeakMap;#Q;#U;#V=!1;#F=new YZ;#B;#N=!1;#M=-1/0;#O=2000;#j=!1;constructor(Z){let $=Z.tokenPath;if(Z.readToken)this.#$=Z.readToken;else if($)this.#$=()=>u($);else throw new N("not-enrolled","Claustrum enrollment token path is required");this.#Z=Z.client,this.#z=Z.family,this.#H=Z.parseIdentity,this.#K=Z.requireAssertion??!1,this.#Y=Z.now??Date.now,this.#X=Z.logger??G4,this.#Q=Z.setTimeoutImpl??setTimeout,this.#U=Z.clearTimeoutImpl??clearTimeout}transportLost(Z){if(this.#j||this.#V)return;this.#V=!0,this.#F=Z instanceof i6?Z:new YZ,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#_()}reachable(){if(this.#j||!this.#V)return;if(this.#V=!1,this.#B)this.#U(this.#B);this.#B=void 0,this.#O=2000;for(let Z of this.#J.values())Z.since=null;(this.#X.info??G4.info)("vault receipt serving resumed",{reason:"reachable"})}#_(){if(this.#j||!this.#V||this.#B||this.#N)return;this.#B=this.#Q(()=>{this.#B=void 0,this.#P(!0)},this.#O),this.#B.unref?.()}#P(Z=!1){if(this.#j||!this.#V||this.#N)return;if(this.#Y()-this.#M<1000){this.#_();return}this.#M=this.#Y(),this.#N=!0,this.discover().catch(()=>{if(Z&&this.#V)this.#O=Math.min(this.#O*2,30000)}).finally(()=>{this.#N=!1,this.#_()})}#q(Z){if(this.#j)throw new N("closed","Claustrum scoped custody is closed");Z?.throwIfAborted()}async#S(Z){this.#q(Z);let $=await this.#$();if(this.#q(Z),!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new N("invalid-token","Invalid Claustrum enrollment token");return $.token}async#L(Z,$){this.#q($);let z,X;try{let Y=Z();z=$?await Promise.race([Y,new Promise((G,J)=>{let B=()=>J($.reason);if($.addEventListener("abort",B,{once:!0}),X=()=>$.removeEventListener("abort",B),$.aborted)B()})]):await Y}catch(Y){if(this.#q($),g(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof i6)throw Y;if(g(Y)==="unreachable")throw new YZ;throw new N("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#q($),this.reachable(),z}async discover(Z){let $,z;try{z=await this.#S(Z)}catch(H){throw this.#J.clear(),H}try{$=await this.#L(()=>this.#Z.listScoped(z),Z)}catch(H){throw this.listFailed(H),H}let X=[],Y=[],G=new Map;for(let H of $.rows){let K=B0(H,this.#z);if(!K)continue;Y.push({row:H,type:K}),G.set(H.id,(G.get(H.id)??0)+1)}let J=[];for(let{row:H,type:K}of Y){let W;if(!H.id.trim())W="empty credential id";else if((G.get(H.id)??0)>1)W="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())W="blank account identity";else if(!H.state.trim())W="empty state";if(W){X.push({...H.id.trim()&&{credentialId:H.id},reason:W});continue}J.push(Object.freeze({credentialId:H.id,credentialType:K,...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of X)this.#X.warn("skipped malformed vault record",H);let B=H0($);return{view:$.view,credentials:Object.freeze(J),skipped:Object.freeze(X),...B&&{grantReach:B}}}listFailed(Z){if(g(Z)==="unreachable")this.transportLost(Z);else this.reachable(),this.#J.clear()}forget(Z){this.#J.delete(Z)}retain(Z){let $=new Map(Z.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#J){let Y=$.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}}keptReceiptState(){let Z=null;for(let[$,z]of this.#J){if(!this.#R(z.attempt)){this.forget($);continue}if(z.since!==null)Z=Math.min(Z??z.since,z.since)}return Object.freeze({active:Z!==null,since:Z})}#R(Z){return Z.expiresAtMs===null?Z.credentialType==="api_key":Z.expiresAtMs-this.#Y()>n6}async authorize(Z,$,z="vault"){this.#q($);let{credentialId:X,credentialType:Y,accountIdentity:G}=Z,J=this.#J.get(X);if(J&&(J.attempt.credentialType!==Y||J.attempt.expectedAccountIdentity!==G))this.forget(X),J=void 0;let B;try{B=await this.#S($)}catch(H){throw this.#J.clear(),H}if(this.#V&&J)return this.#P(),this.#x(X,J,B,z);try{let H=await this.#T({credentialId:X,credentialType:Y,accountIdentity:G},B,$);return this.#J.set(X,{attempt:H,routeId:z,since:null}),H}catch(H){if(this.#q($),g(H)!=="unreachable")throw this.forget(X),H;return this.#x(X,J,B,z,H)}}#x(Z,$,z,X,Y=this.#F){if(!$||this.#J.get(Z)!==$||!this.#R($.attempt))throw this.forget(Z),Y;if($.since===null)$.since=this.#Y();let G=Object.freeze(Object.defineProperty({...$.attempt,fromKeptReceipt:!0},"accessToken",{value:$.attempt.accessToken,enumerable:!1}));return this.#G.set(G,z),this.#D.set(G,X),G}async#T(Z,$,z){if(!Z.credentialId)throw new N("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:G}=Z;if(this.#K&&G===void 0)throw new N("identity-unasserted","Claustrum dispatch requires a known account identity");let J=await this.#L(()=>this.#Z.getScoped({credentialId:X,enrollmentToken:$,...Y==="oauth"&&{minTtlMs:J4}}),z);if(J.credentialId!==void 0&&J.credentialId!==X)throw new N("identity-changed","Claustrum served credential identity changed");let B=J.expiresAtMs;if(!Number.isSafeInteger(J.recordVersion)||J.recordVersion<0||B===null&&Y==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#Y()<J4))throw new N("insufficient-validity","Claustrum served credential has insufficient validity");let H=J0(J.material),K=J.accountId?.trim()?J.accountId:void 0;if(this.#K&&(J.credentialId===void 0||K===void 0))throw new N("identity-unasserted","Claustrum served credential did not assert its identity");let W=K===void 0?this.#H?.(H):void 0,U=K??W;if(G!==void 0&&U!==void 0&&U!==G)throw new N("identity-changed","Claustrum served credential identity changed");let Q=U??G,V=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...Q!==void 0&&{accountIdentity:Q},accountIdentitySource:K!==void 0?"asserted":W!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...J.credentialId!==void 0&&{assertedCredentialId:J.credentialId},...K!==void 0&&{assertedAccountIdentity:K},...J.projectId!==void 0&&{projectId:J.projectId},recordVersion:J.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#G.set(V,$),V}async reportFailure(Z,$,z){if($!==401)return;this.#q();let X=this.#G.get(Z);if(!X)throw new N("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#D.get(Z);if(Y!==void 0){this.forget(Z.credentialId),this.#X.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let G=this.#J.get(Z.credentialId);if(G&&G.attempt.recordVersion===Z.recordVersion)this.forget(Z.credentialId);let J=this.#W.get(Z);if(J)return J;let B=this.#L(()=>this.#Z.reportAuthFailureScoped({credentialId:Z.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:Z.recordVersion,reporterSource:z}));this.#W.set(Z,B);try{await B,this.#X.debug("scoped 401 reported",{credentialId:Z.credentialId,recordVersion:Z.recordVersion,reporterSource:z})}catch(H){throw this.#W.delete(Z),H}}close(){if(this.#j)return;if(this.#j=!0,this.#B)this.#U(this.#B);this.#B=void 0,this.#J.clear(),this.#Z.close()}}import{createHash as K0}from"node:crypto";function a6(Z,$,z){if(Z.accountIdentity!==void 0&&z!==void 0)return Z.accountIdentity===z;return Z.credentialId===$}function H4(Z,$,z){return Z.some((X)=>a6(X,$,z))}function K4(Z,$,z){let X={credentialId:$,...z!==void 0&&{accountIdentity:z}};return[...Z.filter((Y)=>Y.credentialId!==$||Y.accountIdentity!==z),X]}function W4(Z,$,z){return Z.filter((X)=>!$.some((Y)=>a6(X,Y,z)))}var r6="vault:";function W0(Z){return K0("sha256").update(Z).digest("hex")}function Q0(Z){let $=Z.credentialId.split(":");return($.length>=3?$.slice(2).join(":").trim():void 0)||Z.email||Z.credentialId}function V0(Z){return Z.identity!==void 0?`identity:${Z.identity}`:`credential:${Z.credential.credentialId}`}function c(Z){return[Z.credentialId,...Z.aliases??[]]}function t6(Z,$,z={}){let X=z.now??Date.now(),Y=z.routePrefix??r6,G=z.reservedRouteIds??new Set,J=Z?.rows??[],B=[...Z?.declined??[]],H=$.skipped.length===0,K=new Set($.credentials.map((D)=>D.credentialId)),W=new Set($.skipped.flatMap((D)=>D.credentialId===void 0?[]:[D.credentialId])),U=$.skipped.some((D)=>D.credentialId===void 0),Q=(D)=>!K.has(D)&&(W.has(D)||U),F=new Map;for(let D of J){if(D.accountIdentity===void 0)continue;for(let O of c(D))if(!F.has(O))F.set(O,D.accountIdentity)}let V=new Map;for(let D of $.credentials){let O=D.accountIdentity!==void 0?{credential:D,identity:D.accountIdentity,claimed:!0}:{credential:D,identity:F.get(D.credentialId),claimed:!1},m=V0(O),v=V.get(m)??[];v.push(O),V.set(m,v)}let q=new Set,_=new Set(G),L=[],yZ=(D,O)=>D.credential.credentialId.localeCompare(O.credential.credentialId),jZ=[...V.values()].map((D)=>D.toSorted(yZ)).sort((D,O)=>D[0]&&O[0]?yZ(D[0],O[0]):0);for(let D of jZ){let O=D[0]?.identity,m=D.filter((M)=>M.credential.state==="active"),v=m.length?m:D,j3=v.filter((M)=>M.claimed),wZ=j3.length?j3:v,q3=new Set(D.map((M)=>M.credential.credentialId)),C4=J.find((M)=>!q.has(M)&&c(M).some((WZ)=>q3.has(WZ))&&(M.accountIdentity===void 0||M.accountIdentity===O)),O3=wZ.find((M)=>M.credential.credentialId===C4?.credentialId)??wZ[0];if(!O3)continue;let x=O3.credential,A=C4??(O===void 0?void 0:J.find((M)=>!q.has(M)&&M.accountIdentity===O));if(A)q.add(A);let a=A?.routeId;if(!a||G.has(a)){let M=`${Y}${x.credentialId}${O===void 0?"":`~${W0(O).slice(0,10)}`}`;a=M;for(let WZ=2;_.has(a);WZ++)a=`${M}~${WZ}`}_.add(a);let h$=A?c(A).filter(Q):[],M3=[...new Set([...D.map((M)=>M.credential.credentialId),...h$])].filter((M)=>M!==x.credentialId).sort((M,WZ)=>M.localeCompare(WZ)),m$=z.mapAccount?.(x)??{};L.push({previousIndex:A?J.indexOf(A):1/0,row:{routeId:a,credentialId:x.credentialId,credentialType:x.credentialType,...O!==void 0&&{accountIdentity:O},...M3.length&&{aliases:M3},state:x.state,label:m$.label?.trim()||Q0(x),...x.email!==void 0&&{email:x.email},...x.orgName!==void 0&&{orgName:x.orgName},enabled:![x.credentialId,...M3].some((M)=>H4(B,M,O)),addedAt:A?.addedAt??X,...A?.quota!==void 0&&{quota:A.quota},...!O3.claimed&&O!==void 0&&{unclaimed:!0}}})}return J.forEach((D,O)=>{if(q.has(D)||!c(D).some(Q))return;if(_.has(D.routeId))return;let[m,...v]=c(D).filter((q3)=>!K.has(q3));if(m===void 0)return;_.add(D.routeId);let{aliases:j3,...wZ}=D;L.push({previousIndex:O,row:{...wZ,credentialId:m,...v.length&&{aliases:v},stale:!0}})}),L.sort((D,O)=>D.previousIndex===O.previousIndex?D.row.credentialId.localeCompare(O.row.credentialId):D.previousIndex-O.previousIndex),{version:1,view:$.view,complete:H,...!H&&{rejected:$.skipped.map((D)=>({...D.credentialId!==void 0&&{credentialId:D.credentialId},reason:D.reason}))},rows:L.map((D)=>D.row),declined:B}}function Q4(Z){return(Z?.rows??[]).filter(($)=>$.enabled&&$.state==="active").map(($)=>({id:$.routeId,kind:$.credentialType==="oauth"?"oauth":"api-key",...$.quota!==void 0&&{quota:$.quota}}))}function xZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function FZ(Z){return Z===void 0||typeof Z==="string"}function U0(Z){let $=xZ(Z)?t(Z.quota):void 0;if(!xZ(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"||!FZ(Z.accountIdentity)||!FZ(Z.email)||!FZ(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 D0=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function o6(Z){if(!Array.isArray(Z))return;let $=[];for(let z of Z){if(!xZ(z)||!FZ(z.credentialId)||typeof z.reason!=="string"||!D0.has(z.reason))return;$.push(z)}return $}function F0(Z){if(!xZ(Z)||Z.version!==1||!FZ(Z.view)||!Array.isArray(Z.rows)||!Array.isArray(Z.declined)||Z.complete!==void 0&&typeof Z.complete!=="boolean"||Z.rejected!==void 0&&!o6(Z.rejected))throw new N("invalid-state","Claustrum roster file is not valid");let $=[];for(let Y of Z.rows){let G=U0(Y);if(!G)throw new N("invalid-state","Claustrum roster file is not valid");$.push(G)}let z=[];for(let Y of Z.declined){if(!xZ(Y)||typeof Y.credentialId!=="string"||!FZ(Y.accountIdentity))throw new N("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=o6(Z.rejected);return{version:1,...typeof Z.view==="string"&&{view:Z.view},complete:Z.complete!==!1,...X&&{rejected:X},rows:$,declined:z}}async function f(Z){let $;try{$=await Y3(Z,JZ)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse($)}catch{throw new N("invalid-state","Claustrum roster file is not valid")}return F0(z)}var N0={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},j0={name:"claustrum-roster",ttlMs:30000};async function NZ(Z,$,z={}){return h3(Z,N0,async(X)=>{let Y=await f(Z),{next:G,result:J}=await $(Y,{assertOwned:()=>X.assertOwned()});if(G)await X.assertOwned(),await y(Z,G,{beforeRename:async()=>{await z.beforePublish?.(),await X.assertOwned()}});return J})}function V4(Z,$){return NZ(Z,(z)=>{let X=z?.rows.find((G)=>G.routeId===$);if(!z||!X)throw new N("route-unavailable","Claustrum route is not in the roster");let Y=K4(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 U4(Z,$){return NZ(Z,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===$);if(!z||!X)throw new N("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:W4(z.declined,c(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function q0(Z,$){if(!c(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")&&c(Z).length===1)return"bind";return"refuse"}function D4(Z,$){return NZ(Z,(z)=>{let X=z?.rows.find((B)=>B.routeId===$.routeId),Y=!z||!X?"refuse":q0(X,$);if(!z||!X||Y==="refuse")return{result:!1};let G=VZ(X.quota,$.observation),J=Y==="bind"?{accountIdentity:$.accountIdentity,unclaimed:!0}:{};return{next:{...z,rows:z.rows.map((B)=>B===X?{...B,...J,quota:G}:B)},result:!0}})}function F4(Z,$){return NZ(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=VZ(X.quota,$.observation);return{next:{...z,rows:z.rows.map((G)=>G===X?{...G,quota:Y}:G)},result:!0}})}async function N4(Z){Z.signal?.throwIfAborted();let $=async()=>await Z.isActive?.()??!0;if(!await $())return;let z=await T({...j0,path:Z.path,renew:!0});if(!z){let X=await f(Z.path);if(Z.signal?.throwIfAborted(),!X?.view)throw new N("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 NZ(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,J=t6(Y,X,G);return{...JSON.stringify(Y)!==JSON.stringify(J)&&{next:J},result:J}})}finally{await z.release()}}class e6{#Z;#$=new AbortController;#Y;#z;#H;#K;#X;#G;#W;#J;#D=!1;#Q;#U;#V;#F;constructor(Z){this.#Z=Z,this.#Y=Z.logger??b("claustrum")}#B(Z){this.#$.signal.throwIfAborted(),Z?.throwIfAborted()}async#N(){return await this.#Z.isCustodyActive?.()??!0}#M(Z,$){let z=a3([this.#$.signal,...$?[$]:[]]);return new Promise((X,Y)=>{let G=()=>{z.signal.removeEventListener("abort",J),z.dispose()},J=()=>{G(),Y(z.signal.reason)};if(z.signal.addEventListener("abort",J,{once:!0}),Z.then((B)=>{if(G(),z.signal.aborted)Y(z.signal.reason);else X(B)},(B)=>{G(),Y(B)}),z.signal.aborted)J()})}async#O(){if(this.#B(),this.#z)return this.#z;if(!this.#K)this.#K=this.#Z.connect().then((Z)=>{if(this.#$.signal.aborted)Z.close(),this.#B();if(this.#H=Z,this.#z=new H3({client:Z,family:this.#Z.family,tokenPath:this.#Z.tokenPath,parseIdentity:this.#Z.parseIdentity,requireAssertion:this.#Z.requireAssertion,now:this.#Z.now,logger:this.#Y,setTimeoutImpl:this.#Z.setTimeoutImpl,clearTimeoutImpl:this.#Z.clearTimeoutImpl}),this.#Z.insula&&Z.insula)this.#Q=n3(Z.insula,this.#Z.tokenPath);return this.#z}).finally(()=>{this.#K=void 0});return this.#M(this.#K)}snapshot(){return this.#G}grantReach(){let Z=this.#W;return Z&&this.#G?.view===Z.view?Z.reach:void 0}watchState(){return Object.freeze({vault:this.#U?.mode??"polling",...this.#Z.insula&&{insula:this.#Q?.source.watchMode()??"polling"}})}#j(){this.#U?.stop(),this.#U=void 0,this.#H=void 0,this.#V?.(),this.#V=void 0}keptReceiptState(){return this.#z?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return Q4(this.#G)}refresh(){if(this.#B(),this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#N()){this.#G=void 0,this.#W=void 0,this.#j(),this.#z?.close(),this.#z=void 0,this.#Q?.release(),this.#Q=void 0;return}let Z=await this.#O(),$,z=await N4({path:this.#Z.rosterPath,custody:{discover:async(Y)=>{return $=await Z.discover(Y),$}},isActive:()=>this.#N(),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.#B();let X=z?.view!==this.#G?.view;if(this.#G=z,Z.retain(z?.rows??[]),$&&z?.view!==void 0)this.#W=$.grantReach?{view:z.view,reach:$.grantReach}:void 0;if(z&&X)this.#Z.onRoster?.(z);return this.#F=(this.#Z.now??Date.now)(),z})().finally(()=>{this.#X=void 0}),this.#X}start(){if(this.#D)return;this.#B(),this.#D=!0;let Z=async()=>{try{if(await this.#_())await this.refresh();await this.refreshInsulaQuota(),this.#P()}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#_(){if(this.#U?.mode!=="watching")return!0;let Z=(this.#Z.now??Date.now)();if(this.#F===void 0||Z-this.#F>=u3)return!0;return!await this.#N()}#P(){let Z=this.#H;if(this.#$.signal.aborted||!Z||!this.#z)return;if(!this.#U){let $=new tZ({client:Z,enrollmentToken:async()=>(await u(this.#Z.tokenPath)).token,view:()=>this.#G?.view,discover:async()=>{while(this.#X)await this.#X.catch(()=>{});await this.refresh()},onRefused:(z)=>{this.#z?.listFailed(z),this.#Z.onError?.(z)},onTransportLost:()=>this.#z?.transportLost(),onReachable:()=>this.#z?.reachable(),onError:(z)=>{if(!this.#$.signal.aborted)this.#Z.onError?.(z)},logger:this.#Y,now:this.#Z.now,setTimeoutImpl:this.#Z.setTimeoutImpl,clearTimeoutImpl:this.#Z.clearTimeoutImpl});this.#U=$,$.start()}if(this.#Z.insula&&this.#Q&&!this.#V)this.#V=this.#Q.source.watch({provider:this.#Z.insula.provider,setTimeoutImpl:this.#Z.setTimeoutImpl,clearTimeoutImpl:this.#Z.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#N())return;try{await u(this.#Z.tokenPath),await this.#O(),await this.#Q?.source.refresh((this.#Z.now??Date.now)())}catch{}}async cachedInsulaQuota(Z){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#N())return;try{return await u(this.#Z.tokenPath),this.#q(Z.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute(Z){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#N())return;try{await u(this.#Z.tokenPath);let z=(await f(this.#Z.rosterPath))?.rows.find((X)=>X.routeId===Z);return this.#q(z?.accountIdentity)}catch{return}}#q(Z){if(!this.#Z.insula||!Z)return;let $=this.#Q?.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.#B($);let z=this.#G??await this.#M(this.refresh(),$);if(!z||!await this.#N())throw this.#z?.close(),this.#z=void 0,this.#j(),this.#Q?.release(),this.#Q=void 0,new N("not-active","Claustrum scoped custody is not active");let X=await f(this.#Z.rosterPath);this.#B($);let Y=z.rows.find((H)=>H.routeId===Z),G=X?.rows.find((H)=>H.routeId===Z);if(G&&!G.enabled){if(Y)this.#z?.forget(Y.credentialId);throw new N("route-declined","Claustrum route is disabled")}if(!Y||!G||G.state!=="active"||G.credentialId!==Y.credentialId||G.accountIdentity!==Y.accountIdentity||G.credentialType!==Y.credentialType){if(Y)this.#z?.forget(Y.credentialId);throw new N("route-unavailable","Claustrum route is disabled, removed or changed")}let J=await this.#M(this.#O(),$),B=a3([this.#$.signal,...$?[$]:[]]);try{return await J.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},B.signal,Z)}finally{B.dispose()}}async reportFailure(Z,$,z){if(this.#B(),!this.#z)throw new N("no-receipt","Claustrum dispatch receipt has no active owner");await this.#z.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&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,z.reporterSource??"direct"),G;if(G.status===401&&!X?.aborted){let J;try{J=await this.authorize(Z,X)}catch{}if(B4(z.site,Y,J,this.#Y))await G.body?.cancel().catch(()=>{}),Y=J,G=await $(J,X)}if(G.status===401)await this.reportFailure(Y,401,z.reporterSource??"direct").catch((J)=>this.#Z.onError?.(J)),Promise.resolve().then(()=>this.refresh()).catch((J)=>{if(!this.#$.signal.aborted)this.#Z.onError?.(J)});return G}async decline(Z){this.#B(),await V4(this.#Z.rosterPath,Z),this.#G=await f(this.#Z.rosterPath),this.#z?.retain(this.#G?.rows??[])}async accept(Z){this.#B(),await U4(this.#Z.rosterPath,Z),this.#G=await f(this.#Z.rosterPath)}async recordQuota(Z,$,z){this.#B();let X=await D4(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.#G=await f(this.#Z.rosterPath);return X}async recordAccountQuota(Z,$,z){this.#B();let X=await F4(this.#Z.rosterPath,{routeId:Z,accountIdentity:$,observation:z});if(X)this.#G=await f(this.#Z.rosterPath);return X}close(){if(this.#$.signal.aborted)return;if(this.#$.abort(new N("closed","Claustrum consumer is closed")),this.#J)(this.#Z.clearTimeoutImpl??clearTimeout)(this.#J);this.#J=void 0,this.#j(),this.#z?.close(),this.#Q?.release(),this.#Q=void 0,this.#G=void 0,this.#W=void 0}}async function A9(Z){let $=await O0.connect(Z);return Object.assign($,{insula:M6(Z)})}var Z$=J3("openai");function $$(Z){return B3(Z)}function BZ(Z){if(!Z||Z.corrupt===!0)return!1;return $$(Z.refresh)}class TZ 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 K3(Z){if($$(Z))throw new TZ}var M0=b("quota"),j4="primary",q4="secondary",_0="app_EMoamEEZ73f0CkXaXp7hrann",P0="https://auth.openai.com";async function r9(Z){K3(Z.refreshToken);let $=await Z.fetchImpl(`${P0}/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:_0}).toString()});if(!$.ok){let Y=g3($.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 L0="https://chatgpt.com/backend-api/wham/usage";async function t9(Z){let $=Z.logger??M0,z=Z.accountKey??"unknown",X=Date.now();$.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await Z.fetchImpl(L0,{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 J=g3(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:J})}let G=j6(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:z$(Y)}),Y}}import{createHash as S0}from"node:crypto";var R0=globalThis.setTimeout,x0=5;function EZ(Z){let $=Z?.quota?.checkIntervalMinutes??x0;return Math.max(1,$)*60000}function T0(Z){return Z?.quota?.enabled!==!1}function W3(Z,$){if(!Z?.resetsAt)return!1;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)&&z<=$}function G7(Z,$,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let G=$===j4?Z?.primary:$===q4?Z?.secondary:void 0,J=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(J)&&J>z)return J;return z+X}function E0(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??15,secondary:$.secondary??$["1w"]??10}}function X$(Z,$,z){if(!T0($))return z+EZ($);let X=E0($),Y=[];for(let G of["primary","secondary"]){let J=Z?.[G];if(!J)continue;if(J.remainingPercent>=X[G])continue;let B=J.resetsAt?Date.parse(J.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=z)return z+EZ($);Y.push(B)}if(!Y.length)return z+EZ($);return Math.min(...Y)+60000}function C0(Z){if(!Z?.quota?.mainQuota||!Z.quota.mainQuotaCheckedAt)return null;return{quota:Z.quota.mainQuota,checkedAt:Z.quota.mainQuotaCheckedAt,tokenFingerprint:Z.quota.mainQuotaToken}}function A0(Z){let $=Z?.quota?.refreshEveryNRequests;return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):0}function E(Z){return S0("sha256").update(Z).digest("hex").slice(0,16)}class i{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!==E(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)!==E($))return this.fallbacks.delete(Z),this.fallbackTokenFps.delete(Z),null;return z}getAllFallbacks(){return this.fallbacks}setMain(Z,$,z,X=!1){if(!X&&!Y$($.quota))return;if(this.mainTokenFp=E(Z),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=$,O4($.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&&!Y$($.quota))return;let G=this.fallbacks.get(Z)?.accountId;if(Y&&G&&Y!==G)this.clearRateLimited(Z);let J=Y??G;if(this.fallbacks.set(Z,{...$,accountId:J}),z)this.fallbackTokenFps.set(Z,E(z));else this.fallbackTokenFps.delete(Z);if(O4($.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 $=E(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=i.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(BZ(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 $=E(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 $=A0(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=C0(Z);if(!z)return;let X=$?E($):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:X$(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=$&&UZ($,this.now())?$:void 0}seedFallbacksFromAccounts(Z){let $=EZ(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 UZ(this.mainLastApiError,this.now())}isFallbackBackedOff(Z,$){if($){if(this.fallbackErrorTokenFps.get(Z)!==E($))return!1}return UZ(this.fallbackApiErrors.get(Z),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(Z,$){return JSON.stringify([Z,E($)])}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<i.API_CALL_GAP_MS)await new Promise((Y)=>{let G=R0(Y,i.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 $=E(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 T({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=E(Z),this.main={quota:Y,refreshAfter:X$(Y,this.storage,G),checkedAt:G},O4(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 T({name:i.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+EZ(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(i.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(i.isAuthError(Z))return;this.mainLastApiError=MZ({error:Z,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(Z,$,z){if(i.isAuthError(z))return;let X=E($),Y=this.fallbackErrorTokenFps.get(Z)===X?this.fallbackApiErrors.get(Z):void 0;this.fallbackApiErrors.set(Z,MZ({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set(Z,X)}}function Y$(Z){return Boolean(Z.primary||Z.secondary)}function O4(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 I0,randomUUID as b0}from"node:crypto";import{setTimeout as f0}from"node:timers/promises";import{readFile as i0}from"node:fs/promises";var HZ=b("refresh"),V3=b("accounts"),k0=1e4,y0=15000,M4=50;function h(Z){return Z.type==="oauth"&&Z.corrupt!==!0}function w0(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 h0="floors-v1";function M7(Z){return Z.costZeroing?.enabled!==!1}class U3 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(Z){super(`Fallback account ${Z} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var m0=[401,403,429],G$={primary:0,secondary:0},v0=!1,P4={primary:5,secondary:10};function j(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var g0=new Set(["__proto__","constructor","prototype"]);function p0(Z){return Z.length>0&&!g0.has(Z)}function l0(Z){return Z instanceof U3||j(Z)&&Z.name==="AccountRemovedDuringRefreshError"&&Z.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function Q3(Z){return{id:typeof Z.id==="string"&&Z.id.trim()?Z.id.trim():b0(),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 J$(Z){if(!j(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 d0(Z){if(!j(Z))return;let $={};for(let Y of["primary","secondary"]){let G=Z[Y];if(!j(G))continue;let J=Number(G.usedPercent),B=Number(G.remainingPercent),H=Number(G.checkedAt);if(!Number.isFinite(J)||!Number.isFinite(B)||!Number.isFinite(H))continue;let K=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;$[Y]={usedPercent:J,remainingPercent:B,checkedAt:H,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(K)&&K>0?{windowMinutes:K}:{}}}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(j(z)){let Y=Number(z.limit),G=Number(z.used),J=Number(z.remaining),B=Number(z.usedPercent),H=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(G)&&Number.isFinite(J)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof z.reached==="boolean")$.spendControl={limit:Y,used:G,remaining:J,usedPercent:B,remainingPercent:H,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=Z.credits;if(j(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 u0(Z){if(!j(Z))return null;if(Z.type==="api"){let $=typeof Z.baseURL==="string"?Z.baseURL.trim():"",z=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!w0($))return null;let X=Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...Q3(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{...Q3(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{...Q3(Z),type:"oauth",corrupt:!0}}return{...Q3(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:J$(Z.lastRefreshError),lastQuotaRefreshError:J$(Z.lastQuotaRefreshError),quota:d0(Z.quota)}}function c0(Z){if(!j(Z))return;let $=Object.create(null);for(let[z,X]of Object.entries(Z)){if(!p0(z)||!j(X))continue;let Y={};if(j(X.inFlight))Y.inFlight={...X.inFlight};if(j(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))Y.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...j(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))Y.cooldownUntil=X.cooldownUntil;if(Object.keys(Y).length>0)$[z]=Y}return Object.keys($).length>0?$:void 0}var B$=new Set;function D$(Z){if(Z.length===0)return;let $=JSON.stringify([...Z].sort());if(B$.has($))return;B$.add($),V3.warn("account load-dropped, preserved on disk",{droppedIds:Z})}function F$(Z){if(!j(Z)||!Array.isArray(Z.accounts))return null;let $=Z.accounts,z=$.map(u0).filter((X)=>X!=null);if(z.length<$.length){let X=new Set;for(let J of $)if(j(J)&&typeof J.id==="string"&&J.id.trim())X.add(J.id.trim());let Y=new Set(z.map((J)=>J.id)),G=[];for(let J of X)if(!Y.has(J))G.push(J);D$(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:j(Z.routing)?Z.routing:void 0,fallbackOn:Array.isArray(Z.fallbackOn)?Z.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:j(Z.refresh)?Z.refresh:void 0,quota:j(Z.quota)?Z.quota:void 0,reset:c0(Z.reset),dump:j(Z.dump)?Z.dump:void 0,costZeroing:j(Z.costZeroing)?Z.costZeroing:void 0,killswitch:j(Z.killswitch)?Z.killswitch:void 0,logging:j(Z.logging)?Z.logging:void 0,cachekeep:j(Z.cachekeep)?Z.cachekeep:void 0,cacheKeep:j(Z.cacheKeep)?Z.cacheKeep:void 0,mainAccountId:typeof Z.mainAccountId==="string"?Z.mainAccountId:void 0,accounts:z}}function N$(Z){if(!("claustrum"in Z))return Z;let{claustrum:$,...z}=Z;return z}async function s(Z){try{return{exists:!0,value:JSON.parse(await i0(Z,"utf8"))}}catch($){if($.code==="ENOENT")return{exists:!1,value:null};throw $}}function n(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}async function s0(Z){let $;try{$=(await s(Z)).value}catch{return null}return x4($)}function j$(Z,$){if(!j(Z))return Z;let z=j($)?$:{},X=j(z.main)?z.main:void 0,Y=j(z.accounts)?z.accounts:{},G=j(Z.quota)?Z.quota:{},J=j(Z.refresh)?Z.refresh:{},B=X??G,H=X??J,W=J.mainRefreshLeaseId!==void 0?{id:J.mainRefreshLeaseId,until:J.mainRefreshLeaseUntil,tokenHash:J.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},Q=Array.isArray(Z.accounts)?Z.accounts.map((F)=>{if(!j(F))return F;let V=typeof F.id==="string"&&j(Y[F.id])?Y[F.id]:{};return{...F,...V}}):void 0;return q$({...Z,refresh:n({...J,mainLastRefreshError:J.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:n({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:Q})}async function n0(Z){let $=await s(Z.configPath);if(!$.exists)return null;let z=await s(Z.statePath);return F$(j$($.value,z.value))}function q$(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}function a0(Z){return n({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 O$(Z){if(Z.type==="api")return n({apiKey:Z.apiKey,lastUsed:Z.lastUsed});if(Z.corrupt)return{};return n({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 D3(Z){return Math.max(Z?.primary?.checkedAt??0,Z?.secondary?.checkedAt??0)}function CZ(Z,$,z){if(z in $)Z[z]=$[z];else delete Z[z]}function o0(Z,$){return Z.access===$.access&&Z.refresh===$.refresh&&Z.expires===$.expires&&Z.lastRefreshedAt===$.lastRefreshedAt}function r0(Z,$){if(!o0(Z,$))return $;if(!("lastRefreshError"in $))return Z;if(!("lastRefreshError"in Z))return $;return($.lastRefreshError?.checkedAt??0)>(Z.lastRefreshError?.checkedAt??0)?$:Z}var t0=300000;function H$(Z,$){if(Z===void 0)return 0;return Z>$+t0?0:Z}function e0(Z,$,z){let X=Date.now(),Y=H$($.lastRefreshedAt,X),G=H$(z.lastRefreshedAt,X),J=$.expires??0,B=z.expires??0,H=G>Y?z:Y>G?$:B>J?z:J>B?$:r0($,z);CZ(Z,H,"access"),CZ(Z,H,"refresh"),CZ(Z,H,"expires"),CZ(Z,H,"lastRefreshedAt"),CZ(Z,H,"lastRefreshError")}function Z2(Z,$){if(!j(Z))return $;let z=Z,X=D3(z.quota),Y=D3($.quota),G=X>Y,J=G?{...z,...$,quota:z.quota,lastQuotaRefreshError:z.lastQuotaRefreshError}:{...z,...$};if(!G&&!("lastQuotaRefreshError"in $))delete J.lastQuotaRefreshError;if(!("lastRefreshError"in $))delete J.lastRefreshError;if(typeof z.lastUsed==="number"&&(typeof $.lastUsed!=="number"||z.lastUsed>$.lastUsed))J.lastUsed=z.lastUsed;return e0(J,z,$),J}function M$(Z){let $=Z.refresh?n({enabled:Z.refresh.enabled,refreshBeforeExpiryMinutes:Z.refresh.refreshBeforeExpiryMinutes}):void 0,z=Z.quota?n({enabled:Z.quota.enabled,checkIntervalMinutes:Z.quota.checkIntervalMinutes,refreshEveryNRequests:Z.quota.refreshEveryNRequests,minimumRemaining:Z.quota.minimumRemaining,failClosedOnUnknownQuota:Z.quota.failClosedOnUnknownQuota}):void 0;return q$({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(a0)})}async function bZ(Z,$=!1){let z=Date.now(),X=z+y0,Y=0;while(Date.now()<=X){Y++;let B=await T({name:"save",ttlMs:k0,path:Z,renew:$});if(B)return B;let H=X-Date.now();if(H<=0)break;await f0(Math.min(M4+R$(M4),H))}let G=Date.now()-z,J=Math.round(G/Math.max(1,Y));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${Z} (${Y} attempts, ~${J}ms apart; retry interval is ${M4}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 _$(Z){let $=Object.fromEntries(Z.accounts.map((z)=>[z.id,O$(z)]));return{version:1,main:n({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 x4(Z){if(!j(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let z of Z.accounts){if(!j(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;$.add(X)}return $}function $2(Z,$,z,X){if(!j(Z)||!Array.isArray(Z.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],G=[];for(let J of $){if(z.has(J))continue;if(X.has(J))continue;let B=Z.accounts.find((H)=>j(H)&&typeof H.id==="string"&&H.id.trim()===J);if(!B)continue;Y.push(B),G.push(J)}return{preservedRawEntries:Y,preservedIds:G}}function z2(Z){if(!Array.isArray(Z))return[];let $=[];for(let z of Z){if(!j(z))continue;if(typeof z.id!=="string")continue;$.push(z.id)}return $}function X2(Z,$,z){let X=x4(Z);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:G}=$2(Z,X,$,z);return D$(G),Y}async function P7(Z,$,z={}){let{configPath:X,statePath:Y}=$,G=await bZ(X);try{let J=await bZ(Y);try{let B=await s(X),H=await s(Y),K=(B.exists?F$(j$(B.value,H.value)):null)??Y2(),W=new Set(K.accounts.map((D)=>D.id)),U=x4(B.value)??new Set,Q=Z(K,{rawRosterIds:[...U],loadedRosterIds:[...W]})??K,F=new Set(z.allowDrop??[]),V=X2(B.value,W,F),q=M$(Q),_=new Set((Array.isArray(q.accounts)?q.accounts:[]).map((D)=>j(D)&&typeof D.id==="string"?D.id.trim():"").filter(Boolean)),L=V.filter((D)=>{if(!j(D))return!1;if(typeof D.id!=="string")return!1;return!_.has(D.id.trim())}),yZ=j(B.value)?B.value:{},jZ={...N$(yZ),...q,accounts:[...Array.isArray(q.accounts)?q.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return K;if(await y(X,jZ),z.canWrite&&!z.canWrite())return K;return await y(Y,_$(Q)),V3.debug("account config written",{accountCount:jZ.accounts.length,accountIds:z2(jZ.accounts)}),Q}finally{await J.release()}}finally{await G.release()}}function Y2(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function G2(Z,$){Z.main=Z.main??{};let z=typeof Z.main.quotaCheckedAt==="number"?Z.main.quotaCheckedAt:D3(Z.main.quota),X=typeof $.quota?.mainQuotaCheckedAt==="number"?$.quota.mainQuotaCheckedAt:D3($.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 J2(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 L4(Z){if(Array.isArray(Z))return Z.map(L4);if(!j(Z))return Z;return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0).map(([$,z])=>[$,L4(z)]))}async function B2(Z,$,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=$.statePath,G=await bZ(Y);try{let J=(await s(Y)).value,B=j(J)?{...J,version:1}:{version:1};if(z.mainQuota)G2(B,Z);if(z.mainRefresh)J2(B,Z);if(z.accounts){let H=z.accounts===!0?null:new Set(z.accounts),K=await s0($.configPath);B.accounts={...j(B.accounts)?B.accounts:{}};for(let W of Z.accounts){if(H&&!H.has(W.id))continue;if(K&&!K.has(W.id))continue;B.accounts[W.id]=Z2(B.accounts[W.id],O$(W))}if(H){for(let W of H)if(!Z.accounts.some((U)=>U.id===W))delete B.accounts[W]}if(K){for(let W of Object.keys(B.accounts))if(!K.has(W))delete B.accounts[W]}}if(X&&!X())return;await y(Y,L4(B))}finally{await G.release()}}function H2(Z){return Z?.fallbackOn?.length?Z.fallbackOn:m0}function L7(Z,$){return H2($).includes(Z)}function K2(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??G$.primary,secondary:$.secondary??$["1w"]??G$.secondary}}function S4(Z){return Z?.quota?.enabled!==!1}function fZ(Z){return Z?.quota?.failClosedOnUnknownQuota??v0}function P$(Z,$,z=Date.now()){if(!S4($))return!0;if(!Z)return!fZ($);let X=K2($),Y=fZ($);for(let G of["primary","secondary"]){let J=Z[G];if(!J)continue;if(W3(J,z)){if(Y)return!1;continue}if(J.remainingPercent<X[G])return!1}return!0}function F3(Z){return Z?.killswitch?.enabled===!0}function K$(Z){return{primary:Z?.primary??Z?.["5h"]??P4.primary,secondary:Z?.secondary??Z?.["1w"]??P4.secondary}}function S7(Z){return Z?.cacheKeep??Z?.cachekeep}function W$(Z){return typeof Z==="number"&&Number.isFinite(Z)?Z:0}function L$(Z,$){if(!Z?.killswitch)return P4;if(Z.killswitch.schema===h0){let{accounts:z,defaults:X}=Z.killswitch,Y=$??"main",G=j(z)&&Object.hasOwn(z,Y)&&j(z[Y])?z[Y]:j(X)?X:void 0;return{primary:W$(G?.primary),secondary:W$(G?.secondary)}}if($&&Z.killswitch.accounts?.[$])return K$(Z.killswitch.accounts[$]);return K$(Z.killswitch.main)}function S$(Z,$,z,X=Date.now()){if(!F3($))return!0;if(!Z)return!fZ($);let Y=L$($,z),G=fZ($);for(let J of["primary","secondary"]){let B=Z[J];if(!B)continue;if(W3(B,X)){if(G)return!1;continue}if(B.remainingPercent<Y[J])return!1}return!0}function R7(Z,$,z,X){if(!F3(X))return 300;let Y=[],G=[{accountId:void 0,quota:Z},...$];for(let{accountId:B,quota:H}of G){if(!H)continue;let K=L$(X,B),W=[],U=!1;for(let Q of["primary","secondary"]){let F=H[Q];if(!F||W3(F,z))continue;if(F.remainingPercent>=K[Q])continue;let V=F.resetsAt?Date.parse(F.resetsAt):NaN;if(!Number.isFinite(V)||V<=z){U=!0;break}W.push(V)}if(U||W.length===0)continue;Y.push(Math.max(...W))}if(Y.length===0)return 300;let J=Math.min(...Y);return Math.max(1,Math.ceil((J-z)/1000))}function Q$(Z){return typeof Z.version==="number"&&Array.isArray(Z.accounts)}async function x7(Z,$){let{configPath:z,statePath:X}=$;if(!Z)return;try{let G=await s(z);if(G.exists&&j(G.value)&&Q$(G.value))return}catch{}let Y=await bZ(z);try{let G=await bZ(X);try{let J=await s(z);if(J.exists&&j(J.value)){if(Q$(J.value))return}if(!Z)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(Z.access){let W=iZ({id_token:"",access_token:Z.access,refresh_token:Z.refresh});if(W)B.mainAccountId=W}let H=J.exists&&j(J.value)?J.value:{},K={...N$(H),...M$(B)};await y(z,K),await y(X,_$(B))}finally{await G.release()}}finally{await Y.release()}}function W2(Z){return Z?.refresh?.enabled!==!1}function Q2(Z){return(Z?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function R$(Z){return Math.floor(Math.random()*(Z+1))}function KZ(Z,$,z){return!Z.access||!Z.expires||Z.expires-z<=Q2($)}function V2(Z,$){return Boolean(Z.access&&typeof Z.expires==="number"&&Z.expires>$)}function AZ(Z,$){return Boolean(Z?.mainAccountId&&$.accountId&&$.accountId===Z.mainAccountId)}class x$ 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 U2="common-auth-placeholder:v1:openai",T$="main";function T7(Z){return j(Z)&&Z.type==="oauth"&&(Z.refresh===U2||Z.refresh===Z$)}function E7(Z){return Z?.accounts.find(($)=>$.id===T$&&$.enabled!==!1&&h($))}function C7(Z){if(!Z)return Z;return{...Z,accounts:Z.accounts.filter(($)=>$.id!==T$)}}function S(Z,$){let z=Z.accounts.findIndex((X)=>X.id===$.id);if(z!==-1)Z.accounts[z]=$}function IZ(Z){return Z instanceof Error?Z.message:String(Z)}function R4(Z,$,z){if($ instanceof TZ)return;Z.lastRefreshError=z6({error:$,now:z,refreshToken:Z.refresh,previous:Z.lastRefreshError})}function _4(Z,$,z){if($ instanceof TZ)return;if(Z.lastQuotaRefreshError=MZ({error:$,now:z,previous:Z.lastQuotaRefreshError}),$?.isRefreshError===!0)R4(Z,$,z)}function V$(Z,$){if(!Z)return!1;if(!Z.resetsAt)return!0;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)?z>$:!0}function D2(Z,$){if(!Z)return!1;return V$(Z.primary,$)||V$(Z.secondary,$)}function F2(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 U$(Z,$,z){return!F2(Z.quota,$,z)}function N2(Z,$,z,X){return v3(z)&&P$(Z.quota,$,X)&&D2(Z.quota,X)}function j2(Z){let $=Z?.quota?.checkIntervalMinutes??5;return Math.max(1,$)*60000}var q2=60000,O2=60000,M2=600000;function _2(Z){return`fallback-oauth-refresh-${I0("sha256").update(Z).digest("base64url").slice(0,16)}`}var P2=1e4,L2=100;class S2{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)K3(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+j2($),checkedAt:z},Z.access,!1,Z.accountId)}async load(){return n0(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save(Z,$){await B2(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(()=>{})},q2+R$(O2)),"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(AZ($,Y))continue;if(BZ(Y))continue;let G=!1,J=Y;try{if(KZ(J,$,this.now())){let B=J.lastRefreshError;if(B&&e(B,J.refresh,this.now()))throw G=!0,Error(uZ(B,this.now()));try{J=await this.refreshAccount(J,$),X=!0}catch(H){if(l0(H))continue;G=!0;let K=$.accounts.find((W)=>W.id===Y.id&&h(W));if(K&&!e(K.lastRefreshError,K.refresh,this.now()))R4(K,H,this.now()),S($,K),X=!0;throw H}}if(this.seedFallbackQuota(J,$),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),$))z.push(J)}catch(B){let H=V2(J,this.now());if(G){if(!H)continue}else if(!H)continue;if(N2(J,$,B,this.now()))HZ.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:J.id,error:IZ(B)}),z.push(J);else if(!fZ($))z.push(J)}}if(X){let Y=structuredClone($);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((G)=>{V3.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:IZ(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($){V3.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:Z.id,error:IZ($)})}}accountPassesQuotaPolicy(Z,$){return P$(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||!W2(Z))return;let $=!1;for(let z of Z.accounts){if(z.enabled===!1||!h(z))continue;if(AZ(Z,z))continue;if(BZ(z))continue;if(!KZ(z,Z,this.now()))continue;if(e(z.lastRefreshError,z.refresh,this.now()))continue;try{HZ.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){HZ.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:IZ(X)}),R4(z,X,this.now()),S(Z,z),$=!0}}if($)await this.save(Z)}async refreshQuotaForDueAccounts(){let Z=await this.load();if(!Z||!S4(Z))return;if(!this.options.fetchQuotaFn)return;let $=!1;for(let z of Z.accounts){if(z.enabled===!1||!h(z))continue;if(AZ(Z,z))continue;if(BZ(z))continue;let X=z;try{if(KZ(X,Z,this.now())){if(e(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,Z),$=!0}if(UZ(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,Z),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):U$(X,Z,this.now())))continue;await this.refreshAccountQuota(X,Z),$=!0}catch(Y){_4(z,Y,this.now()),S(Z,z),$=!0}}if($)await this.save(Z),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(Z={}){let $=await this.load(),z=[];if(!$||!S4($))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(AZ($,G))continue;if(BZ(G))continue;let J=G;try{if(KZ(J,$,this.now())){let B=J.lastRefreshError;if(B&&e(B,J.refresh,this.now()))throw Error(uZ(B,this.now()));J=await this.refreshAccount(J,$),Y=!0}if(!X&&!U$(J,$,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,S($,J),Y=!0;continue}await this.refreshAccountQuota(J,$),Y=!0}catch(B){_4(G,B,this.now()),S($,G),Y=!0,z.push({accountId:G.id,message:IZ(B)})}}if(Y)await this.save($);return{storage:$,errors:z}}async refreshAccount(Z,$,z={}){let X=this.refreshPromises.get(Z.id);if(X){let J=await X;return S($,J),J}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()+P2;while(Date.now()<Y){await new Promise((K)=>setTimeout(K,L2));let G=await this.load(),J=G?.accounts.find((K)=>K.id===Z.id&&h(K));if(!J)continue;if(this.assertNotTombstoned(J),(J.access!==z.access||J.refresh!==z.refresh||(J.expires??0)>(z.expires??0)+60000)&&(X.force||!KZ(J,G,this.now())))return S($,J),HZ.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let H=J.lastRefreshError;if(H&&e(H,J.refresh,this.now()))throw S($,J),Error(uZ(H,this.now()))}return null}assertNotShieldedMainRow(Z,$,z){if(z.asPoolMain||!$)return;if(AZ(Z,$))throw new x$($.id)}async refreshAccountNow(Z,$,z){let X=await this.load(),Y=X?.accounts.find((B)=>B.id===Z.id&&h(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!KZ(Y,X,this.now()))return S($,Y),Y;let G=Y??Z,J=await T({name:_2(G.id),ttlMs:M2,path:this.paths.configPath,renew:!0});if(!J){HZ.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let B=await this.waitForConcurrentFallbackRefresh(Z,$,G,z);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),Y=X?.accounts.find((W)=>W.id===Z.id&&h(W)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!KZ(Y,X,this.now()))return S($,Y),Y;if(!Y)throw new U3(Z.id);G=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});HZ.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:z.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let H=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=H.access,G.refresh=H.refresh,G.expires=H.expires,G.lastRefreshedAt=H.expires-H.expiresIn*1000,G.lastRefreshError=void 0,S($,G),await this.save($),!(await this.load())?.accounts.some((W)=>W.id===Z.id))throw new U3(Z.id);return HZ.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await J.release()}}async refreshAccountQuota(Z,$){let z=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 _4(Z,G,this.now()),S($,Z),G}}}var E$=["primary","secondary"];function T4(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function kZ(Z){return typeof Z==="number"&&Number.isFinite(Z)}function R2(Z,$){if(!T4($))return;let z=$.usedPercent;if(!kZ(z)||z<0||z>100)return;return{label:Z,usedPercent:z,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...kZ($.windowMinutes)&&$.windowMinutes>0?{windowMinutes:$.windowMinutes}:{}}}function x2(Z){let $=Z.spendControl;if(T4($)&&typeof $.reached==="boolean"){let z=(X)=>kZ($[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 b7(Z,$,z){if(!T4(Z)||!kZ($))return;let X=[],Y=[];for(let H of E$){let K=R2(H,Z[H]);if(K)X.push(K);else if(z)Y.push({label:H})}let G=x2(Z),J=Z.resetCreditsAvailable,B=typeof J==="number"&&Number.isSafeInteger(J)&&J>=0?{resetCredits:{value:J,checkedAt:$}}:void 0;if(X.length===0&&Y.length===0&&!G&&!B)return;return{checkedAt:$,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...G?{budget:G}:{},...B?{counters:B}:{}}}function C$(Z){if(!o(Z))return;let $=I(Z),z={};for(let X of E$){let Y=$.limits.find((J)=>J.label===X&&J.kind==="reading");if(!Y||!kZ(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 I$="main";function m7(Z){return Z.find(($)=>$.id.startsWith("vault:")&&$.credentialId==="chatgpt:openai")?.id??null}function v7(Z,$,z){let X=new Map;if(F3($))for(let Y of Z)X.set(Y.id,S$(C$(Y.quota),$,Y.id===I$?void 0:Y.id,z));return X}var g7=5,T2=5000;function p7(Z){if(Z==="ordered")return"roster";return Z==="fallback-first"?"fallback-first":"main-first"}function l7(Z,$=T2){let z=Z.rows.filter((J)=>J.kind==="oauth"&&Z.killswitch.get(J.id)!==!1&&I(J.quota).limits.length===0);if(z.length===0)return;if(k({rows:Z.rows,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:()=>{}}).admitted.some((J)=>Z.killswitch.get(J.id)!==!1))return;let Y=[];if(k({rows:z,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:(J)=>{let B=Z.requestPull(J);if(B)Y.push(B.catch(()=>{}))}}),Y.length===0)return;let G;return Promise.race([Promise.all(Y),new Promise((J)=>{G=setTimeout(J,$)})]).then(()=>{}).finally(()=>clearTimeout(G))}function E4(Z){return Z.reason==="exhausted"||Z.reason==="budget-spent"}function b$(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 A$(Z,$,z){if($.refused.find((Y)=>!E4(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return b$(Z[0],$,z)}function d7(Z){let $=Z.replayable!==!1,z=Z.mainId===void 0?I$:Z.mainId??"",X=$?Z.placement:"main-first",Y=C3({rows:Z.rows,placement:X,formerMainId:z,killswitch:Z.killswitch,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,now:Z.now,requestPull:Z.requestPull}),G=lZ(Z.rows.map((H)=>H.id),X,z),J=new Set(Y.admission.refused.filter((H)=>E4(H)&&Z.killswitch.get(H.id)!==!1).map((H)=>H.id)),B=G.filter((H)=>J.has(H));if(!$){let H=G.includes(z),K=H?z:Y.order[0]??B[0];if(K!==void 0&&Y.order.includes(K))return{kind:"send",order:[K],lastPath:!1};if(K!==void 0&&J.has(K))return{kind:"send",order:[K],lastPath:!0};return{kind:"block",block:H?b$(z,Y.admission,Z.killswitch):A$(G,Y.admission,Z.killswitch)}}if(Y.order.length>0)return{kind:"send",order:Y.order,lastPath:!1};if(B.length>0)return{kind:"send",order:B,lastPath:!0};return{kind:"block",block:A$(G,Y.admission,Z.killswitch)}}function u7(Z){let $=k({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,I(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 f$(Z,$,z){let X=z.exclude,Y=X?Z.rows.filter((J)=>!X.has(J.id)):Z.rows,G=new Map;for(let J of Y){let B=$.resetCredits(J.id);if(B!==void 0)G.set(J.id,B)}return y3({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:(J)=>$.reservePercent(J.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...z.pin===void 0?{}:{pin:{accountId:z.pin}},...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}})}function c7(Z,$,z,X){let Y=f$(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 i7(Z,$,z){let X=Z.killswitch.get(z)===!1,Y=f$(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((J)=>J.id===z);if(!X&&G&&E4(G))return{kind:"last-path"};return{kind:"none"}}function s7(Z,$,z,X){let Y=Z.killswitch.get(z);return k3({quota:$.projections.get(z),now:Z.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as k$}from"node:os";import{join as y$}from"node:path";var E2=["error","warn","info","debug","trace"];function C2(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?y$(k$(),"opencode-openai-auth","opencode-openai-auth.log"):y$(k$(),"opencode-openai-auth.log"))}function A2(){let Z=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return Z&&E2.includes(Z)?Z:void 0}w$({file:C2,level:A2});if(process.once("beforeExit",async()=>{try{await N3()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>N3());
90
+ export{o as vc,VZ as wc,Y1 as xc,p4 as yc,d$ as zc,u4 as Ac,n$ as Bc,I as Cc,a4 as Dc,J1 as Ec,lZ as Fc,B1 as Gc,A3 as Hc,H1 as Ic,Q1 as Jc,j1 as Kc,$6 as Lc,z6 as Mc,e as Nc,uZ as Oc,B6 as Pc,K6 as Qc,P1 as Rc,Y6 as Sc,G6 as Tc,iZ as Uc,S1 as Vc,XZ as Wc,E1 as Xc,C1 as Yc,A1 as Zc,I1 as _c,S8 as $c,x8 as ad,T8 as bd,E8 as cd,N as dd,a3 as ed,t1 as fd,e1 as gd,Z0 as hd,z4 as id,X0 as jd,l6 as kd,Y0 as ld,f as md,e6 as nd,A9 as od,BZ as pd,TZ as qd,r9 as rd,t9 as sd,G7 as td,E as ud,i as vd,h as wd,h0 as xd,M7 as yd,P4 as zd,p0 as Ad,s0 as Bd,n0 as Cd,P7 as Dd,B2 as Ed,H2 as Fd,L7 as Gd,P$ as Hd,F3 as Id,S7 as Jd,L$ as Kd,S$ as Ld,R7 as Md,x7 as Nd,Q2 as Od,AZ as Pd,T$ as Qd,T7 as Rd,E7 as Sd,C7 as Td,M2 as Ud,_2 as Vd,S2 as Wd,b7 as Xd,C$ as Yd,I$ as Zd,m7 as _d,v7 as $d,g7 as ae,p7 as be,l7 as ce,d7 as de,u7 as ee,c7 as fe,i7 as ge,s7 as he};
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as PoolStore, _ as TokenResponse, a as RESPONSES_LITE_MODELS, b as parseJwtClaims, c as CacheKeepManager, d as ResetTargetIdentity, f as OpenAiVault, g as IdTokenClaims, l as MenuMigrationState, n as CODEX_VERSION, o as PoolLifecycleDeps, t as CODEX_USER_AGENT, u as OpenAiMenuOptions, v as beginAccountLogin, x as AccountPaths, y as extractAccountIdFromClaims } from "./codex-request-CjXETpTA.js";
2
- import { v as SidebarMachineState, x as SidebarState } from "./sidebar-state-BfQ4mpZO.js";
1
+ import { S as PoolStore, _ as TokenResponse, a as RESPONSES_LITE_MODELS, b as parseJwtClaims, c as CacheKeepManager, d as ResetTargetIdentity, f as OpenAiVault, g as IdTokenClaims, l as MenuMigrationState, n as CODEX_VERSION, o as PoolLifecycleDeps, t as CODEX_USER_AGENT, u as OpenAiMenuOptions, v as beginAccountLogin, x as AccountPaths, y as extractAccountIdFromClaims } from "./codex-request-B9D0e97Q.js";
2
+ import { v as SidebarMachineState, x as SidebarState } from "./sidebar-state-CVSok7zv.js";
3
3
  import { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin";
4
4
  //#region ../core/dist/provider.d.ts
5
5
  type QuotaWindowName = string;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as q,Q as f,R as g,S as h,T as i,U as j,V as k,W as l,X as m,Y as n,Z as o,_ as p,aa as r,ba as s,ca as t,da as u,ea as v,fa as w,ga as x,ha as y,ia as z,ja as A,ka as B,la as C,m as c,ma as D,n as d,na as E,o as e,oa as F}from"./index-rwbrhkse.js";import"./index-03em8hv1.js";import"./index-6n4pnfkg.js";import{Sc as a,Tc as b}from"./index-f21addzm.js";import"./index-qxbchh2d.js";import"./index-htvcmtcx.js";import"./index-ffg0sgg5.js";import"./index-ehjj89rx.js";import"./index-r2s51ac1.js";import"./index-bc89akak.js";import"./index-xwvze96g.js";export{C as rewriteResponsesLiteBody,A as resolveSidebarSessionId,r as poolResetTarget,a as parseJwtClaims,x as mergePushedQuotaMetadata,k as getMainRefreshLockName,w as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,F as default,s as createResetTargetResolver,h as codexOAuthModelListed,i as codexOAuthModelLimit,z as buildSidebarState,y as buildSidebarMachineState,t as buildResetRedemptionDeps,o as __resetBootQuotaSeedForTest,u as __menuContextForTest,n as __bootQuotaSeedPromiseForTest,q as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,v as POOL_MIGRATION_ENABLED,E as OpenAIAuthPlugin,B as MID_CONVERSATION_EFFORT_MODELS,l as MAIN_REFRESH_LOCK_TTL_MS,m as MAIN_REFRESH_LEASE_TTL_MS,j as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,D as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,p as AuthPersistError,f as ALLOWED_MODELS};
1
+ import{$ as q,Q as f,R as g,S as h,T as i,U as j,V as k,W as l,X as m,Y as n,Z as o,_ as p,aa as r,ba as s,ca as t,da as u,ea as v,fa as w,ga as x,ha as y,ia as z,ja as A,ka as B,la as C,m as c,ma as D,n as d,na as E,o as e,oa as F}from"./index-4v2fs42x.js";import"./index-psjyexj3.js";import"./index-ex6nx3mq.js";import{Sc as a,Tc as b}from"./index-tn8x5tz8.js";import"./index-gn2b097f.js";import"./index-2pgkrebq.js";import"./index-tddr876f.js";import"./index-1mbgsxsr.js";import"./index-8x1aj7q3.js";import"./index-bc89akak.js";import"./index-xwvze96g.js";export{C as rewriteResponsesLiteBody,A as resolveSidebarSessionId,r as poolResetTarget,a as parseJwtClaims,x as mergePushedQuotaMetadata,k as getMainRefreshLockName,w as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,F as default,s as createResetTargetResolver,h as codexOAuthModelListed,i as codexOAuthModelLimit,z as buildSidebarState,y as buildSidebarMachineState,t as buildResetRedemptionDeps,o as __resetBootQuotaSeedForTest,u as __menuContextForTest,n as __bootQuotaSeedPromiseForTest,q as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,v as POOL_MIGRATION_ENABLED,E as OpenAIAuthPlugin,B as MID_CONVERSATION_EFFORT_MODELS,l as MAIN_REFRESH_LOCK_TTL_MS,m as MAIN_REFRESH_LEASE_TTL_MS,j as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,D as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,p as AuthPersistError,f as ALLOWED_MODELS};
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/commands/model.d.ts
1
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/commands/model.d.ts
2
2
  /** The section slots, in the one order every renderer shows them. */
3
3
  declare const SECTION_SLOTS: readonly ['accounts', 'quota', 'routing', 'limits', 'cache', 'diagnostics', 'extra'];
4
4
  type SectionSlot = (typeof SECTION_SLOTS)[number];
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/rpc/port-file.d.ts
1
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/rpc/port-file.d.ts
2
2
  interface PortFileEntry {
3
3
  port: number;
4
4
  token: string;
@@ -1,4 +1,4 @@
1
- import { n as CommandApplyResult, r as CommandDialogPayload, s as NotifyKind, t as CommandApplyRequest } from "./model-CQcw10oW.js";
1
+ import { n as CommandApplyResult, r as CommandDialogPayload, s as NotifyKind, t as CommandApplyRequest } from "./model-BdITTmeb.js";
2
2
  //#region ../core/dist/protocol.d.ts
3
3
  /** The menu, as the slash command opens it in the TUI. */
4
4
  type OpenDialogPayload = CommandDialogPayload;
@@ -1,4 +1,4 @@
1
- import { n as discoverPortFile, r as writePortFile, t as PortFileEntry } from "../port-file-BDJnzgHH.js";
1
+ import { n as discoverPortFile, r as writePortFile, t as PortFileEntry } from "../port-file-DbHIVC9a.js";
2
2
  //#region src/rpc/port-file.d.ts
3
3
  export declare const isOpenaiRpcStateDir: (name: string) => boolean;
4
4
  //#endregion
@@ -1 +1 @@
1
- import{we as c}from"../index-htvcmtcx.js";import{Ae as b,ye as a}from"../index-ffg0sgg5.js";import"../index-r2s51ac1.js";import"../index-bc89akak.js";import"../index-xwvze96g.js";export{a as writePortFile,c as isOpenaiRpcStateDir,b as discoverPortFile};
1
+ import{we as c}from"../index-2pgkrebq.js";import{Ae as b,ye as a}from"../index-tddr876f.js";import"../index-8x1aj7q3.js";import"../index-bc89akak.js";import"../index-xwvze96g.js";export{a as writePortFile,c as isOpenaiRpcStateDir,b as discoverPortFile};
@@ -1,2 +1,2 @@
1
- import { a as RpcNotification, i as OpenDialogPayload, n as ApplyResult, o as isNotifyPayload, r as NotifyPayload, t as ApplyRequest } from "../protocol-C-kagE6O.js";
1
+ import { a as RpcNotification, i as OpenDialogPayload, n as ApplyResult, o as isNotifyPayload, r as NotifyPayload, t as ApplyRequest } from "../protocol-MysYPAho.js";
2
2
  export { type ApplyRequest, type ApplyResult, type NotifyPayload, type OpenDialogPayload, type RpcNotification, isNotifyPayload };
@@ -1 +1 @@
1
- import{Ne as b}from"../index-ehjj89rx.js";import"../index-r2s51ac1.js";import"../index-xwvze96g.js";export{b as isNotifyPayload};
1
+ import{Ne as b}from"../index-1mbgsxsr.js";import"../index-8x1aj7q3.js";import"../index-xwvze96g.js";export{b as isNotifyPayload};
@@ -1,6 +1,6 @@
1
- import { a as RpcNotification, n as ApplyResult, t as ApplyRequest } from "../protocol-C-kagE6O.js";
2
- import { t as PortFileEntry } from "../port-file-BDJnzgHH.js";
3
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/rpc/rpc-client.d.ts
1
+ import { a as RpcNotification, n as ApplyResult, t as ApplyRequest } from "../protocol-MysYPAho.js";
2
+ import { t as PortFileEntry } from "../port-file-DbHIVC9a.js";
3
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/rpc/rpc-client.d.ts
4
4
  export declare const DEFAULT_RPC_TIMEOUT_MS = 2000;
5
5
  //#endregion
6
6
  //#region src/rpc/rpc-client.d.ts
@@ -1 +1 @@
1
- import{Be as F,Ce as f}from"../index-ffg0sgg5.js";import"../index-r2s51ac1.js";import"../index-xwvze96g.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
1
+ import{Be as F,Ce as f}from"../index-tddr876f.js";import"../index-8x1aj7q3.js";import"../index-xwvze96g.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/logger/engine.d.ts
1
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/logger/engine.d.ts
2
2
  interface ChannelLogger {
3
3
  error(message: string, data?: unknown): void;
4
4
  warn(message: string, data?: unknown): void;
@@ -8,7 +8,7 @@ interface ChannelLogger {
8
8
  }
9
9
  declare function createLogger(channel: string): ChannelLogger;
10
10
  //#endregion
11
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/quota/map.d.ts
11
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/quota/map.d.ts
12
12
  interface QuotaReadingEntry {
13
13
  scope: string;
14
14
  label: string;
@@ -63,7 +63,7 @@ interface QuotaMap {
63
63
  counters?: Record<string, QuotaCounter>;
64
64
  }
65
65
  //#endregion
66
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/quota/projection.d.ts
66
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/quota/projection.d.ts
67
67
  interface ProjectedLimit {
68
68
  scope: string;
69
69
  label: string;
@@ -84,6 +84,15 @@ interface ProjectedBudget {
84
84
  remainingPercent?: number;
85
85
  resetsAt?: string;
86
86
  }
87
+ /**
88
+ * A named group of windows, such as antigravity-auth's `Gemini` and
89
+ * `Other models`: every window stored under `scope` belongs to it, and
90
+ * `label` is the group's display name.
91
+ */
92
+ interface QuotaGroup {
93
+ scope: string;
94
+ label: string;
95
+ }
87
96
  interface ProjectedQuota {
88
97
  scope: string;
89
98
  /** One entry per label: longest known window first, unknown lengths last. */
@@ -96,9 +105,16 @@ interface ProjectedQuota {
96
105
  /** Present only when the stored budget is a reading, not cleared. */
97
106
  budget?: ProjectedBudget;
98
107
  counters?: Record<string, QuotaCounter>;
108
+ /**
109
+ * The named groups the windows belong to, in the order the plugin lists
110
+ * them. Set only by a plugin whose windows all belong to such groups; the
111
+ * narrow form then shows one item per group (see `formatQuota`).
112
+ * `projectQuota` never sets it.
113
+ */
114
+ groups?: readonly QuotaGroup[];
99
115
  }
100
116
  //#endregion
101
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/sidebar-file/sidebar-file.d.ts
117
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/sidebar-file/sidebar-file.d.ts
102
118
  interface SidebarFileHooks {
103
119
  /** Runs on the first merge attempt, before checking for older, unlocked writers. */
104
120
  beforeRecheck?: () => void | Promise<void>;
@@ -1,2 +1,2 @@
1
- import { $ as pruneStickyAssignments, A as applyStickyPinOverlay, B as getCollapsedAccountLines, C as SpendControlReading, D as StickyAssignmentPlan, E as StickyAssignmentMap, F as displayWidth, G as hashSidebarSessionId, H as getPresentQuotaWindows, I as drainSidebarWrites, J as normalizeSidebarState, K as isQuotaExhausted, L as exhaustedQuotaResetAt, M as computeQuotaPacing, N as createSidebarBookkeepingQueue, O as StickyPinOverlay, P as createSidebarStateCache, Q as pruneActiveRouting, R as fitCollapsedLabel, S as SidebarStateCache, T as StickyAssignmentChoice, U as getSidebarState, V as getCollapsedQuotaSummary, W as getSidebarStateFile, X as planSidebarStickyAssignment, Y as persistSidebarStickyAssignment, Z as planSidebarStickyAssignmentFromSnapshot, _ as SidebarBookkeepingQueue, a as ActiveRoutingMap, at as resolveSidebarStickyAssignment, b as SidebarSnapshot, c as HOT_PATH_READ_BUDGET_MS, ct as setSidebarMachineState, d as QuotaWindow, dt as sidebarQuotaProjection, et as rememberStickyPin, f as QuotaWindowKey, ft as spendControlExhaustedResetAt, g as SidebarAccountState, h as STICKY_ASSIGNMENT_MAX_ENTRIES, i as ActiveRoutingEntry, it as resolveSessionStickyAccount, j as clearSidebarStickyAssignment, k as StickyPinOverlayEntry, l as PresentQuotaWindow, lt as setSidebarState, m as STICKY_ASSIGNMENT_MAX_AGE_MS, n as ACTIVE_ROUTING_MAX_ENTRIES, nt as resolveActiveAccount, o as CollapsedAccountLine, ot as setLegacySidebarStateFileForTest, p as ResolveStickyAssignmentInput, pt as upsertSidebarActiveRouting, q as isUsableRoutingEntry, r as AccountQuota, rt as resolveSessionSidebarRouting, s as DEFAULT_SIDEBAR_STATE, st as setSidebarLegacyRouting, t as ACTIVE_ROUTING_MAX_AGE_MS, tt as removeSidebarActiveRouting, u as QuotaPacing, ut as settleWithinBudget, v as SidebarMachineState, w as StickyAssignment, x as SidebarState, y as SidebarRoutingAccount, z as formatWindowLabel } from "./sidebar-state-BfQ4mpZO.js";
1
+ import { $ as pruneStickyAssignments, A as applyStickyPinOverlay, B as getCollapsedAccountLines, C as SpendControlReading, D as StickyAssignmentPlan, E as StickyAssignmentMap, F as displayWidth, G as hashSidebarSessionId, H as getPresentQuotaWindows, I as drainSidebarWrites, J as normalizeSidebarState, K as isQuotaExhausted, L as exhaustedQuotaResetAt, M as computeQuotaPacing, N as createSidebarBookkeepingQueue, O as StickyPinOverlay, P as createSidebarStateCache, Q as pruneActiveRouting, R as fitCollapsedLabel, S as SidebarStateCache, T as StickyAssignmentChoice, U as getSidebarState, V as getCollapsedQuotaSummary, W as getSidebarStateFile, X as planSidebarStickyAssignment, Y as persistSidebarStickyAssignment, Z as planSidebarStickyAssignmentFromSnapshot, _ as SidebarBookkeepingQueue, a as ActiveRoutingMap, at as resolveSidebarStickyAssignment, b as SidebarSnapshot, c as HOT_PATH_READ_BUDGET_MS, ct as setSidebarMachineState, d as QuotaWindow, dt as sidebarQuotaProjection, et as rememberStickyPin, f as QuotaWindowKey, ft as spendControlExhaustedResetAt, g as SidebarAccountState, h as STICKY_ASSIGNMENT_MAX_ENTRIES, i as ActiveRoutingEntry, it as resolveSessionStickyAccount, j as clearSidebarStickyAssignment, k as StickyPinOverlayEntry, l as PresentQuotaWindow, lt as setSidebarState, m as STICKY_ASSIGNMENT_MAX_AGE_MS, n as ACTIVE_ROUTING_MAX_ENTRIES, nt as resolveActiveAccount, o as CollapsedAccountLine, ot as setLegacySidebarStateFileForTest, p as ResolveStickyAssignmentInput, pt as upsertSidebarActiveRouting, q as isUsableRoutingEntry, r as AccountQuota, rt as resolveSessionSidebarRouting, s as DEFAULT_SIDEBAR_STATE, st as setSidebarLegacyRouting, t as ACTIVE_ROUTING_MAX_AGE_MS, tt as removeSidebarActiveRouting, u as QuotaPacing, ut as settleWithinBudget, v as SidebarMachineState, w as StickyAssignment, x as SidebarState, y as SidebarRoutingAccount, z as formatWindowLabel } from "./sidebar-state-CVSok7zv.js";
2
2
  export { ACTIVE_ROUTING_MAX_AGE_MS, ACTIVE_ROUTING_MAX_ENTRIES, AccountQuota, ActiveRoutingEntry, ActiveRoutingMap, CollapsedAccountLine, DEFAULT_SIDEBAR_STATE, HOT_PATH_READ_BUDGET_MS, PresentQuotaWindow, QuotaPacing, QuotaWindow, QuotaWindowKey, ResolveStickyAssignmentInput, STICKY_ASSIGNMENT_MAX_AGE_MS, STICKY_ASSIGNMENT_MAX_ENTRIES, SidebarAccountState, SidebarBookkeepingQueue, SidebarMachineState, SidebarRoutingAccount, SidebarSnapshot, SidebarState, SidebarStateCache, SpendControlReading, StickyAssignment, StickyAssignmentChoice, StickyAssignmentMap, StickyAssignmentPlan, StickyPinOverlay, StickyPinOverlayEntry, applyStickyPinOverlay, clearSidebarStickyAssignment, computeQuotaPacing, createSidebarBookkeepingQueue, createSidebarStateCache, displayWidth, drainSidebarWrites, exhaustedQuotaResetAt, fitCollapsedLabel, formatWindowLabel, getCollapsedAccountLines, getCollapsedQuotaSummary, getPresentQuotaWindows, getSidebarState, getSidebarStateFile, hashSidebarSessionId, isQuotaExhausted, isUsableRoutingEntry, normalizeSidebarState, persistSidebarStickyAssignment, planSidebarStickyAssignment, planSidebarStickyAssignmentFromSnapshot, pruneActiveRouting, pruneStickyAssignments, rememberStickyPin, removeSidebarActiveRouting, resolveActiveAccount, resolveSessionSidebarRouting, resolveSessionStickyAccount, resolveSidebarStickyAssignment, setLegacySidebarStateFileForTest, setSidebarLegacyRouting, setSidebarMachineState, setSidebarState, settleWithinBudget, sidebarQuotaProjection, spendControlExhaustedResetAt, upsertSidebarActiveRouting };