@cortexkit/opencode-openai-auth 1.8.1 → 1.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +9 -9
- package/dist/{index-4rf3rkdm.js → index-03hs0rq7.js} +1 -1
- package/dist/{index-fhcnxrtz.js → index-0v7ar02e.js} +1 -1
- package/dist/{index-b7p76qqa.js → index-b0s5cty6.js} +7 -7
- package/dist/{index-vh1sr50d.js → index-bej7x30p.js} +22 -22
- package/dist/{index-h1r8cbet.js → index-dw6yd976.js} +1 -1
- package/dist/index-fyrgwfx3.js +8 -0
- package/dist/index-rw932qm9.js +74 -0
- package/dist/{index-21yxzeet.js → index-yt52fztj.js} +1 -1
- package/dist/{index-ww8w9edq.js → index-z81cged1.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +3 -3
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +86 -42
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +15 -8
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +175 -10
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +86 -42
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +15 -8
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +175 -10
- package/dist/index-73z9ftrg.js +0 -8
- package/dist/index-97cz7kyq.js +0 -74
- /package/dist/{index-mg4w434p.js → index-g556s1mz.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{if as O,jf as U,mf as b,nf as m,of as L,sf as y}from"./index-
|
|
1
|
+
import{if as O,jf as U,mf as b,nf as m,of as L,sf as y}from"./index-g556s1mz.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
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Re as w,Se as O,Te as k}from"./index-
|
|
1
|
+
import{Re as w,Se as O,Te as k}from"./index-yt52fztj.js";import{jf as h,of as D}from"./index-g556s1mz.js";import{uf as j}from"./index-c50p5mem.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.8.3";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
|
|
2
2
|
export{i as Je,n as Ke,a as Le,Bf as Me,Hf as Ne,R as Oe,bf as Pe,Cf as Qe};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as x,J as f,K as g,L as h,M as i,N as j,O as k,P as l,Q as m,R as n,S as o,T as p,U as q,V as r,W as s,X as t,Y as u,Z as v,_ as w,aa as y,ba as z,ca as A,da as B,ea as C,fa as D,ga as E,ha as F,ia as G,j as c,k as d,l as e}from"./index-
|
|
1
|
+
import{$ as x,J as f,K as g,L as h,M as i,N as j,O as k,P as l,Q as m,R as n,S as o,T as p,U as q,V as r,W as s,X as t,Y as u,Z as v,_ as w,aa as y,ba as z,ca as A,da as B,ea as C,fa as D,ga as E,ha as F,ia as G,j as c,k as d,l as e}from"./index-bej7x30p.js";import"./index-rw932qm9.js";import"./index-03hs0rq7.js";import{dd as a,ed as b}from"./index-b0s5cty6.js";import"./index-fyrgwfx3.js";import"./index-z81cged1.js";import"./index-yt52fztj.js";import"./index-dw6yd976.js";import"./index-g556s1mz.js";import"./index-c50p5mem.js";import"./index-hpnj460b.js";export{D as rewriteResponsesLiteBody,B as resolveSidebarSessionId,s as poolResetTarget,a as parseJwtClaims,y as mergePushedQuotaMetadata,l as getMainRefreshLockName,x as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,G as default,t as createResetTargetResolver,j as codexOAuthModelVariantSource,h as codexOAuthModelListed,i as codexOAuthModelLimit,A as buildSidebarState,z as buildSidebarMachineState,u as buildResetRedemptionDeps,p as __resetBootQuotaSeedForTest,v as __menuContextForTest,o as __bootQuotaSeedPromiseForTest,r as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,w as POOL_MIGRATION_ENABLED,F as OpenAIAuthPlugin,C as MID_CONVERSATION_EFFORT_MODELS,m as MAIN_REFRESH_LOCK_TTL_MS,n as MAIN_REFRESH_LEASE_TTL_MS,k as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,E as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,q as AuthPersistError,f as ALLOWED_MODELS};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Pe as b,Qe as c}from"../index-
|
|
1
|
+
import{Pe as b,Qe as c}from"../index-z81cged1.js";import{Ue as a}from"../index-yt52fztj.js";import"../index-g556s1mz.js";import"../index-c50p5mem.js";import"../index-hpnj460b.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
|
package/dist/rpc/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{gf as b}from"../index-
|
|
1
|
+
import{gf as b}from"../index-dw6yd976.js";import"../index-g556s1mz.js";import"../index-hpnj460b.js";export{b as isNotifyPayload};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ve as F,We as f}from"../index-
|
|
1
|
+
import{Ve as F,We as f}from"../index-yt52fztj.js";import"../index-g556s1mz.js";import"../index-hpnj460b.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$b as p,Ac as Q,Bc as R,Cc as S,Dc as T,Mb as a,Nb as b,Ob as c,Pb as d,Qb as e,Rb as f,Sb as g,Tb as h,Ub as i,Vb as j,Wb as k,Xb as l,Yb as m,Zb as n,_b as o,ac as q,bc as r,cc as s,dc as t,ec as u,fc as v,gc as w,hc as x,ic as y,jc as z,kc as A,lc as B,mc as C,nc as D,oc as E,pc as F,qc as G,rc as H,sc as I,tc as J,uc as K,vc as L,wc as M,xc as N,yc as O,zc as P}from"./index-
|
|
1
|
+
import{$b as p,Ac as Q,Bc as R,Cc as S,Dc as T,Mb as a,Nb as b,Ob as c,Pb as d,Qb as e,Rb as f,Sb as g,Tb as h,Ub as i,Vb as j,Wb as k,Xb as l,Yb as m,Zb as n,_b as o,ac as q,bc as r,cc as s,dc as t,ec as u,fc as v,gc as w,hc as x,ic as y,jc as z,kc as A,lc as B,mc as C,nc as D,oc as E,pc as F,qc as G,rc as H,sc as I,tc as J,uc as K,vc as L,wc as M,xc as N,yc as O,zc as P}from"./index-03hs0rq7.js";import"./index-b0s5cty6.js";import"./index-fyrgwfx3.js";import"./index-dw6yd976.js";import"./index-g556s1mz.js";import"./index-hpnj460b.js";export{y as upsertSidebarActiveRouting,p as spendControlExhaustedResetAt,O as sidebarQuotaProjection,I as settleWithinBudget,w as setSidebarState,x as setSidebarMachineState,z as setSidebarLegacyRouting,e as setLegacySidebarStateFileForTest,C as resolveSidebarStickyAssignment,s as resolveSessionStickyAccount,t as resolveSessionSidebarRouting,N as resolveActiveAccount,A as removeSidebarActiveRouting,K as rememberStickyPin,v as pruneStickyAssignments,u as pruneActiveRouting,D as planSidebarStickyAssignmentFromSnapshot,B as planSidebarStickyAssignment,E as persistSidebarStickyAssignment,k as normalizeSidebarState,o as isUsableRoutingEntry,r as isQuotaExhausted,h as hashSidebarSessionId,i as getSidebarStateFile,l as getSidebarState,d as getPresentQuotaWindows,P as getCollapsedQuotaSummary,Q as getCollapsedAccountLines,c as formatWindowLabel,S as fitCollapsedLabel,q as exhaustedQuotaResetAt,G as drainSidebarWrites,R as displayWidth,J as createSidebarStateCache,M as createSidebarBookkeepingQueue,T as computeQuotaPacing,F as clearSidebarStickyAssignment,L as applyStickyPinOverlay,b as accountServesOnCredits,a as accountCreditsText,g as STICKY_ASSIGNMENT_MAX_ENTRIES,f as STICKY_ASSIGNMENT_MAX_AGE_MS,H as HOT_PATH_READ_BUDGET_MS,j as DEFAULT_SIDEBAR_STATE,n as ACTIVE_ROUTING_MAX_ENTRIES,m as ACTIVE_ROUTING_MAX_AGE_MS};
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ae as h,He as u,Ie as P}from"./index-
|
|
1
|
+
import{Ae as h,He as u,Ie as P}from"./index-fyrgwfx3.js";import{if as M,jf as R,of as S}from"./index-g556s1mz.js";import"./index-hpnj460b.js";import{mkdir as Yq,writeFile as Vq}from"node:fs/promises";import{homedir as Wq}from"node:os";import{dirname as Dq,join as b}from"node:path";import{applyEdits as t,modify as r,parse as e}from"jsonc-parser";function qq(z){return z!==null&&typeof z==="object"&&!Array.isArray(z)}async function k(z){try{let q=[],H=e(await S(z,M),q,{allowTrailingComma:!0});return q.length===0&&qq(H)?H:{}}catch(q){if(q instanceof R&&q.code!=="ENOENT")throw q;return{}}}var zq=`// Shared preferences for TUI plugins.
|
|
2
2
|
// Plugins update individual keys in place and preserve comments.
|
|
3
3
|
{}
|
|
4
4
|
`;function g(z){let{file:q,pluginKey:H,beforeCommit:Q}=z,$={...P.preferences,timeoutMs:z.timeoutMs??P.preferences.timeoutMs},Z=Promise.resolve();async function X(U,j){await u(q,$,async(K)=>{let J;try{J=await S(q,M)}catch(G){if(G.code!=="ENOENT")throw G;J=""}if(J.trim()==="")J=zq;let B=t(J,r(J,[H,...U],j,{formattingOptions:{insertSpaces:!0,tabSize:2}}));await h(q,B,{serialize:(G)=>String(G),beforeRename:async()=>{await Q?.(),await K.assertOwned()}})})}return{queueTuiPreferenceUpdate(U,j){let K=[...U],J=structuredClone(j),B=Z.then(()=>X(K,J));return Z=B.catch(()=>{}),B}}}import{readFileSync as Hq,realpathSync as Qq,statSync as Xq,watch as Zq}from"node:fs";import{readFile as $q,stat as Bq}from"node:fs/promises";import{basename as p,dirname as s,join as Gq,resolve as Jq}from"node:path";import{clearTimeout as w,setTimeout as c}from"node:timers";function n(z){let q=Jq(z);if(M)return q;try{return Qq(q)}catch{let H=s(q);return H===q?q:Gq(n(H),p(q))}}function d(z){return z&&`${z.dev}:${z.ino}:${z.mtimeMs}:${z.size}`}function T(z,q,H={}){let Q=globalThis,$=Symbol.for("cortexkit.common-auth.tui-prefs.watchers.v1"),Z=Q[$]??new Map;Q[$]=Z;let X=n(z),U=Z.get(X);if(U)return U.subscribe(q);let j=p(X),K=M?(Y)=>S(Y):H.fs?.readFile??((Y)=>$q(Y,"utf8")),J=H.fs?.stat??Bq,B=null,G=null,x=null,C=null;if(!M)try{let Y=d((H.fs?.statSync??Xq)(X));C=(H.fs?.readFileSync??((V)=>Hq(V,"utf8")))(X),x=Y}catch{}let N=!1,L=new Set,E=Promise.resolve(),v=(Y)=>{return E=E.then(async()=>{if(N)return;let V=d(await J(X).catch(()=>null));if(!Y&&V===x)return;if(V===null){x=null;return}let I=await K(X).catch((W)=>{if(W instanceof R&&W.code!=="ENOENT")if(H.onError)H.onError(W);else process.emitWarning(W.message,W.name);return null});if(N)return;if(I===null)return;if(x=V,I===C)return;C=I;for(let W of[...L]){if(!L.has(W))continue;try{W.notify()}catch{}}}),E},i=()=>{if(N)return;if(B)w(B);B=c(()=>{B=null,v(!0)},150)},O=null;try{O=(H.watchDirectory??Zq)(s(X),(Y,V)=>{let I=V?.toString(),W=I===j||I?.startsWith(`${j}.`)&&I.endsWith(".tmp");if(I!=null&&!W)return;i()}),O.on("error",()=>{O?.close(),O=null})}catch{}let f=()=>{if(N||G)return;G=c(()=>{if(G=null,N)return;v(!1).finally(f)},1000),G.unref()},F={subscribe:(Y)=>{let V={notify:Y};return L.add(V),()=>{if(!L.delete(V)||L.size>0)return;if(N=!0,B)w(B);if(G)w(G);if(O?.close(),Z.get(X)===F)Z.delete(X)}}};return Z.set(X,F),f(),F.subscribe(q)}var Uq="OPENCODE_TUI_PREFERENCES_FILE",Iq="tui-preferences.jsonc";function m(){let z=process.env[Uq];if(z)return z;let q=process.env.OPENCODE_CONFIG_DIR||b(process.env.XDG_CONFIG_HOME||b(Wq(),".config"),"opencode");return b(q,Iq)}function _(z){return typeof z==="object"&&z!==null&&!Array.isArray(z)}function dq(){return k(m())}var Mq="openai-auth",Aq=160,l={forceToTop:!1,order:Aq,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"OPENAI",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function D(z,q){return typeof z==="boolean"?z:q}function A(z,q,H,Q){if(typeof z!=="number"||!Number.isFinite(z))return q;return Math.min(Math.max(Math.round(z),H),Q)}function jq(z,q,H){if(typeof z!=="string"||z.length===0)return q;return z.slice(0,H)}function o(z,q){if(typeof z!=="string")return q;return[...z][0]??q}function pq(z){let q=z[Mq];if(!_(q))return structuredClone(l);let H=l,Q=_(q.header)?q.header:{},$=_(q.sections)?q.sections:{},Z=_(q.appearance)?q.appearance:{},X=A(Z.warnThreshold,H.appearance.warnThreshold,0,99),U=Math.max(A(Z.errorThreshold,H.appearance.errorThreshold,0,100),Math.min(X+1,100));return{forceToTop:D(q.forceToTop,H.forceToTop),order:A(q.order,H.order,-1e4,1e4),startCollapsed:D(q.startCollapsed,H.startCollapsed),rememberCollapsed:D(q.rememberCollapsed,H.rememberCollapsed),collapsed:typeof q.collapsed==="boolean"?q.collapsed:null,pollMs:A(q.pollMs,H.pollMs,500,30000),refreshDebounceMs:A(q.refreshDebounceMs,H.refreshDebounceMs,50,5000),header:{label:jq(Q.label,H.header.label,20),showVersion:D(Q.showVersion,H.header.showVersion)},sections:{quota:D($.quota,H.sections.quota),fallbackAccounts:D($.fallbackAccounts,H.sections.fallbackAccounts),routing:D($.routing,H.sections.routing),health:D($.health,H.sections.health),pacing:D($.pacing,H.sections.pacing)},appearance:{barWidth:A(Z.barWidth,H.appearance.barWidth,4,40),barFilledChar:o(Z.barFilledChar,H.appearance.barFilledChar),barEmptyChar:o(Z.barEmptyChar,H.appearance.barEmptyChar),warnThreshold:X,errorThreshold:U}}}var Nq=-1e5;function sq(z,q,H){let Q=z[q];if(!_(Q))return H;if(Q.forceToTop===!0)return Nq+Object.keys(z).indexOf(q);return A(Q.order,H,-1e4,1e4)}var Kq=`// Shared preferences for opencode TUI plugins.
|
package/dist/v2/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{c as W0}from"../index-
|
|
1
|
+
import{c as W0}from"../index-0v7ar02e.js";import{A as Y0,B as O$,C as yZ,D as fZ,E as V0,F as e$,G as $Z,H as u2,I as A$,L as HZ,M as NZ,N as FZ,V as _Z,W as MZ,_ as U0,d as rZ,e as PZ,ea as o1,f as J1,fa as r1,g as A2,h as i2,i as t2,ia as H0,k as a1,l as n1,m as d1,n as m2,o as s$,p as R1,q as t$,r as VZ,s as UZ,t as a2,u as y$,v as f$,w as z0,x as G0,y as w1,z as Q0}from"../index-bej7x30p.js";import{$a as e2,Bb as L2,Cb as l$,Db as u$,Eb as E1,Fb as p$,Gb as c$,Ib as X0,Jb as j0,Ka as GZ,Kb as B0,Ra as d2,ab as aZ,bb as nZ,cb as oZ,db as tZ,eb as g$,gb as eZ,hb as QZ,pa as iZ,qb as $0,rb as Z0,sa as H$,sb as J0,ta as N$,tb as YZ}from"../index-rw932qm9.js";import{Ub as SZ,hc as bZ,ic as kZ,kc as DZ,oc as wZ}from"../index-03hs0rq7.js";import{Dd as zZ,Ec as Y$,Fd as dZ,Gd as TZ,Hd as V$,Qd as O2,Rd as f2,Wd as U$,Yd as w$,Zd as W$,dd as p2,de as s2,ed as c2,fd as cZ,ke as LZ,le as b2,md as D1,me as F$,nd as X$,ne as K$,od as j$,oe as P$,pd as B$,qe as T$,re as L$,te as _$,ue as M$,ve as T1,we as C$,xd as JZ,xe as E$}from"../index-b0s5cty6.js";import"../index-fyrgwfx3.js";import{Ne as o$,Oe as sZ}from"../index-z81cged1.js";import"../index-yt52fztj.js";import{$e as U2,Ze as pZ}from"../index-dw6yd976.js";import"../index-g556s1mz.js";import{wf as r$}from"../index-c50p5mem.js";import{Af as Z1,Bf as uZ}from"../index-hpnj460b.js";import{AsyncLocalStorage as N4}from"node:async_hooks";import{randomUUID as F4}from"node:crypto";class Z2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function V2($){return`common-auth-placeholder.${$}`}function g1($){let Z=V2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function q2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:V2(Z),z=(Y)=>J===void 0?Y.startsWith("common-auth-placeholder."):Y===J;return z($.access)&&z($.refresh)}var l1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function j1($,Z){let J=Z.now??Date.now,{integrationID:z}=Z,Y=(H)=>g1({integrationID:z,methodID:H,now:J()}),Q=async(H,W)=>{return await Z.onLogin(H,{integrationID:z,methodID:W}),Y(W)},N=(H)=>async(W)=>{let j=H.method.id,U=await H.authorize(W),P={url:U.url,instructions:U.instructions,...U.expiresAt===void 0?{}:{expiresAt:U.expiresAt}};if(U.mode==="auto")return{...P,mode:"auto",callback:U.callback.then((_)=>Q(_,j))};let S=U.callback;return{...P,mode:"code",callback:async(_)=>Q(await S(_),j)}};return $.integration.transform((H)=>{let W=Z.label===void 0?{}:{label:()=>Z.label};for(let P of Z.methods)H.method.update({integrationID:z,method:P.method,authorize:N(P),refresh:async(S)=>{if(!q2(S,z))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Y(S.methodID)},...W});let j=Z.vault;if(j===void 0)return;let U=j.method.id;H.method.update({integrationID:z,method:j.method,authorize:async()=>({url:"",instructions:j.instructions??l1,mode:"auto",callback:Promise.resolve().then(()=>j.activate({integrationID:z,methodID:U})).then(()=>Y(U))}),refresh:async(P)=>{if(!q2(P,z)||P.methodID!==U)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Y(U)},...W})})}function P0($){let Z=[],J;for(let z of $.split(/\r?\n/))if(z.startsWith("data:"))Z.push(z.slice(5).replace(/^ /,""));else if(z.startsWith("event:"))J=z.slice(6).trim();if(Z.length===0)return;return J===void 0?{data:Z.join(`
|
|
2
2
|
`)}:{event:J,data:Z.join(`
|
|
3
|
-
`)}}function Q1($,Z){let J=new TextDecoder,z="",Q=(N)=>{let H=K0(N);if(!H)return;try{$(H)}catch(U){Z(U)}},Y=()=>{for(;;){let N=/\r?\n\r?\n/.exec(z);if(!N)return;let H=z.slice(0,N.index);z=z.slice(N.index+N[0].length),Q(H)}};return new TransformStream({transform(N,H){H.enqueue(N),z+=J.decode(N,{stream:!0}),Y()},flush(){if(z+=J.decode(),Y(),z.trim()!=="")Q(z);z=""}})}var g1=512,l1=1200000,C2="x-common-auth-attempt",P2=($,Z)=>JSON.stringify([$,Z]),G2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function L0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function P0($,Z){let J=$.getReader();return new ReadableStream({async pull(z){let Q;try{Q=await J.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),z.error(Y);return}if(Q.done)Z(),z.close();else z.enqueue(Q.value)},async cancel(z){Z({reason:"cancelled",...z===void 0?{}:{message:String(z)}}),await J.cancel(z)}})}function v2($,Z){for(let[J,z]of Object.entries(Z)){let Q=J.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===Q)delete $[Y];if(z!==null)$[J]=z}}function T0($,Z){for(let[J,z]of Object.entries(Z))if(z===null)$.delete(J);else $.set(J,z)}async function X1($,Z,J={}){let{providerID:z}=Z,Q=J.gateOnPlaceholder,Y=(G)=>Q===void 0||Q.credential(G)===V2(z),N=J.logger,H=Math.max(1,J.maxRecords??g1),U=[...J.hostCredentials??[V2(z)],...Q?[V2(z)]:[]].filter((G)=>G!==""),j=new Map,B=new WeakMap,L=new Map,b=0,_=new Set,I=new Map,a=new Map,x=(G)=>{let X=a.get(G);return X?.ownedSeen===!0&&X.foreignSeen},w=(G,X)=>{I.set(G,X);let V=a.get(G)??{ownedSeen:!1,foreignSeen:!1};if(X)V.ownedSeen=!0;else V.foreignSeen=!0;a.set(G,V)},Q2=(G,X)=>{let V=Q?.refuseMisplaced,P=V?[...X].filter(([,D])=>D.includes(V2(z))):[],F=Y(X)&&(!V||P.length>0);if(V){if(P.length>0&&(P.length!==1||!F))throw w(G.sessionID,!1),new Z2({kind:"placement-refused",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:V(P[0]?.[0]??"")})}return w(G.sessionID,F),F},$2=!1,k=!1,g=new Map,W=0,T=!1,E=new Map,K=(G,X)=>{try{N?.warn(G,X)}catch{}},A=(G)=>G instanceof Error?G.message:String(G),C=new Map,M=(G,X)=>{let V=(C.get(G)??Promise.resolve()).then(X),P=V.then(()=>{},()=>{});return C.set(G,P),P.then(()=>{if(C.get(G)===P)C.delete(G)}),V},h=(G,X)=>{let V=C.get(G);return V?V.then(()=>h(G,X)):X()},q=async(G)=>{try{await Z.dropChoice?.({...G.input,accountId:G.accountId})}catch(X){K("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:G.input.sessionID,error:A(X)})}},m=(G)=>{let X=L.get(G);if(L.delete(G),X?.next){let V=X.next;M(X.sessionID,()=>q(V))}},l=async(G,X)=>{let V=g.get(G);if(!V||V.size===0)return;await Promise.all([...V].map(async(P)=>{try{await P(X)}catch(F){K("opencode2 auth listener threw; the request is unaffected",{event:G,error:A(F)})}}))},u=async(G,X)=>{try{await Z.onAttemptEnd?.(G,X)}catch(V){K("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:G.attemptId,error:A(V)})}},t=(G,X)=>{if(G.ended||!G.attempt)return;let V={...G.status===void 0?{}:{status:G.status},outputStarted:G.outputStarted,...G.limit?{limit:G.limit.signal}:{},...X?{error:X}:{}};if(X)G.endError=X;G.ended=u(G.attempt,V)},p=(G,X)=>t(G,{reason:"abandoned",message:X}),n=(G)=>[...j.values()].filter((X)=>X.key===G),v=(G)=>n(G).at(-1),y=(G)=>{if(j.delete(G.id),L.get(G.key)?.attemptId===G.id||!n(G.key).length)m(G.key)},f=(G)=>{j.set(G.id,G);while(j.size>H){let X=j.values().next().value;if(X===void 0)break;p(X,"dropped to keep the record bound"),y(X)}},o=(G)=>G.accountId===void 0?void 0:{...G.scope,accountId:G.accountId},c=(G,X)=>new Z2({kind:"no-account",providerID:z,sessionID:G.sessionID,requestKind:G.kind,...X===void 0?{}:{message:X}}),s=(G)=>{E.get(G)?.clear(),E.delete(G)},J2=async(G,X)=>{let V=()=>c(G,`${z} ${G.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(T)throw V();let P=E.get(G.sessionID);if(!P)P=new Set,E.set(G.sessionID,P);let F={};P.add(F);let D=()=>{if(!P.has(F))throw V()};try{return await X(D)}finally{if(P.delete(F),P.size===0&&E.get(G.sessionID)===P)E.delete(G.sessionID)}},_2=(G,X)=>{for(let[V,P]of X)if(U.some((F)=>P.includes(F)))throw new Z2({kind:"host-credential-on-wire",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:`${z} ${G.kind} request still carries the host's placeholder credential in ${V}; the adapter's account headers must replace it`})},A2=(G)=>{for(let X of n(G))if(X.ended||!X.attempt)y(X);else if(X.transport==="ws"||X.judged)p(X,"a newer attempt of its session and kind began"),y(X)},M2=async(G,X,V,P)=>{let F=P2(G.sessionID,G.kind),{input:D,accountId:R}=await h(G.sessionID,async()=>{V();let r=L.get(F);L.delete(F);let j2=r?.accountId??v(F)?.accountId;A2(F);let B2=r?.next,e=B2!==void 0&&B2.input.modelID===G.modelID&&B2.input.agent===G.agent,R2={...G,phase:"request",...j2===void 0?{}:{previousAccountId:j2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(B2&&!e)await M(G.sessionID,()=>q(B2)),V();let N2=e?B2.accountId:await Z.chooseAccount(R2);return{input:R2,accountId:typeof N2==="string"?N2:void 0}});V();let S={},i;if(R!==void 0){let r=await Z.accountHeaders({...G,accountId:R});if(V(),L0(r))S=r.headers,i=r.attempt;else S=r}let K2=`attempt-${++W}`,z2={id:K2,key:F,scope:G,accountId:R,headers:S,attempt:R===void 0?void 0:{...G,accountId:R,attemptId:K2,transport:P,data:i},...P===void 0?{}:{transport:P},outputStarted:!1};if(f(z2),z2.attempt)l("select",{...G,accountId:z2.attempt.accountId,hook:X,...D.previousAccountId===void 0?{}:{previousAccountId:D.previousAccountId},...D.rerouteFrom===void 0?{}:{rerouteFrom:D.rerouteFrom},handle:z2.attempt});return z2},O=async(G,X,V,P,F)=>{let D=P2(G.sessionID,G.kind),R=P===void 0?void 0:j.get(P);if(R?.key!==D)R=void 0;if(!R){if(R=v(D),n(D).filter((i)=>i.transport===void 0&&!i.ended).length>1&&!k)k=!0,K("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:G.sessionID,kind:G.kind})}if(!R||R.transport!==void 0||R.ended)R=await M2(G,X,F,V);else if(R.transport=V,R.attempt)R.attempt.transport=V;if(V==="ws"){for(let S of n(D))if(S!==R&&S.transport==="ws")p(S,"a newer attempt of its session and kind went out over WebSocket")}return R},d=async(G,X)=>{try{return await X()}catch(V){throw t(G,{reason:"failed",message:A(V)}),V}},X2=(G,X)=>{let V=n(P2(G,X)).filter((P)=>P.transport==="ws").at(-1);return V?.attempt!==void 0&&!V.ended?V:void 0},Z1=(G,X,V)=>{let P=o(G);if(!P||!G.attempt||G.limit)return;G.limit={signal:X,delivered:l("limit",{...P,via:V,limit:X,outputStarted:G.outputStarted,handle:G.attempt})}},w1=(G,X,V,P)=>{let F=o(G);if(!F||!G.attempt)return;l("quota",{...F,transport:X,...P===void 0?{}:{status:P},quota:V,handle:G.attempt})},y1=(G,X,V,P)=>{let F=G.attempt;if(!F)return;let D=Z.inspectEvent?.(P===void 0?{transport:X,data:V,attempt:F}:{transport:X,data:V,event:P,attempt:F});if(!D)return;if(D.quota!==void 0)w1(G,X,D.quota);if(D.outputStarted)G.outputStarted=!0;if(D.limit)Z1(G,D.limit,X);if(D.error!==void 0)t(G,{reason:"failed",message:D.error});else if(D.done)t(G)},H0=(G,X)=>{let V=G.attempt;if(!V||X.accountId===G.accountId)return;if(V.reboundFrom??=V.accountId,V.accountId=X.accountId,"data"in X)V.data=X.data;G.accountId=X.accountId},N0=(G)=>!G.attempt||G.endError!==void 0||G.status!==void 0&&G.status>=400,F0=(G)=>{let X=[...j.values()].filter((S)=>S.scope.sessionID===G),V=X.filter((S)=>S.limit&&!S.rerouted).at(-1);if(V)return V;let P=X.filter((S)=>S.scope.kind==="primary"),F=P.length>0?P:X;if(F.length<=1)return F[0];let D=F.filter((S)=>!S.judged&&N0(S)).at(-1);if(D)return D;let R=F.filter((S)=>S.attempt&&!S.ended);if(R.length>1)return"ambiguous";return R[0]??F.at(-1)},F2={providerID:z},H2=[];H2.push(await $.session.hook("model.request",(G)=>{if(Q)return;return J2(G2(G),async(X)=>{let V=await M2(G2(G),"model.request",X);if(X(),V.accountId===void 0)throw c(V.scope);v2(G.headers,{...V.headers,[C2]:V.id})})},F2)),H2.push(await $.session.hook("http.request",(G)=>{if(Q){if(!Q2(G2(G),G.request.headers))return}return J2(G2(G),async(X)=>{let V=G.request.headers.get(C2)??void 0,P=Q?await M2(G2(G),"http.request",X,"http"):await O(G2(G),"http.request","http",V,X);X();let F=o(P),D=P.attempt;if(!F||!D)throw c(P.scope);await d(P,async()=>{let R=G.request;if(Z.rewriteRequest){if(V!==void 0){let K2=new Headers(R.headers);K2.delete(C2),R=new Request(R,{headers:K2})}R=await Z.rewriteRequest({...F,request:R,attempt:D})??R,X()}let S=new Headers(R.headers);S.delete(C2),T0(S,P.headers),_2(P.scope,S.entries());let i=new Request(R,{headers:S});B.set(i,P),G.request=i})})},F2)),H2.push(await $.session.hook("http.response",async(G)=>{let X=B.get(G.request);if(!X){if(Q)return;if(!$2)$2=!0,K("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:G.sessionID,kind:G.kind});return}let V=G.response;if(Z.answeredBy&&X.attempt){let S=X.attempt,i=await d(X,async()=>Z.answeredBy?.({request:G.request,response:V,attempt:S}));if(i)H0(X,i)}let P=o(X),F=X.attempt;if(!P||!F)return;X.status=V.status;let D=Z.quotaFromHeaders?.(V.headers,V.status,F);if(D!==void 0)w1(X,"http",D,V.status);if(!V.ok&&Z.limitFromResponse){let S=await Z.limitFromResponse({status:V.status,headers:V.headers,body:()=>V.clone().text(),attempt:F});if(S)Z1(X,S,"http")}if(!V.ok||!V.body)t(X);let R=V;if(V.body&&(Z.inspectEvent||Z.onAttemptEnd)){let S=V.body;if(Z.inspectEvent)S=S.pipeThrough(Q1((i)=>y1(X,"http",i.data,i.event),(i)=>K("opencode2 auth event inspection threw",{error:A(i)})));R=new Response(P0(S,(i)=>t(X,i)),{status:V.status,statusText:V.statusText,headers:V.headers})}if(Z.rewriteResponse)R=await Z.rewriteResponse({...P,request:G.request,response:R,attempt:F})??R;if(R!==V)G.response=R},F2)),H2.push(await $.session.hook("experimental.ws.handshake",(G)=>{if(Q){let X=P2(G.sessionID,G.kind);if(_.delete(X),!Q2(G2(G),new Headers(G.headers)))return}return J2(G2(G),async(X)=>{let V;for(let R of Object.keys(G.headers)){if(R.toLowerCase()!==C2)continue;V??=G.headers[R],delete G.headers[R]}let P=Q?await M2(G2(G),"experimental.ws.handshake",X,"ws"):await O(G2(G),"experimental.ws.handshake","ws",V,X);X();let F=o(P),D=P.attempt;if(!F||!D)throw c(P.scope);await d(P,async()=>{if(!Q?.refuseMisplaced)v2(G.headers,P.headers);let R=Z.rewriteHandshakeURL?.({...F,url:G.url,attempt:D});if(R!==void 0)G.url=R;if(Q?.refuseMisplaced)v2(G.headers,P.headers);if(_2(P.scope,Object.entries(G.headers)),Q)_.add(P.key)})})},F2));let f1=Z.rewriteWebSocketFrame?.bind(Z);if(f1)H2.push(await $.session.hook("experimental.ws.send",async(G)=>{let X=G2(G);if(Q&&!_.has(P2(X.sessionID,X.kind)))return;let V=X2(X.sessionID,X.kind),P=await f1({...X,attempt:V?.attempt,frame:G.frame});if(P!==void 0)G.frame=P},F2));H2.push(await $.session.hook("experimental.ws.receive",(G)=>{if(Q&&!_.has(P2(G.sessionID,G.kind)))return;let X=X2(G.sessionID,G.kind);if(!X)return;try{y1(X,"ws",G.frame)}catch(V){K("opencode2 auth frame inspection threw",{error:A(V)})}},F2)),H2.push(await $.session.hook("retry",async(G)=>{if(Q&&I.get(G.sessionID)!==!0)return;let X=G.decision,V=()=>l("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});if(x(G.sessionID)){await V();return}let P=F0(G.sessionID);if(!P)return;if(P==="ambiguous"){await l("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let F=P;await J2(F.scope,async(D)=>{let R=D;if(x(G.sessionID)){await V();return}F.judged=!0;let S=F.attempt;if(S&&!F.outputStarted){if(!F.limit){let z2=Z.limitFromError?.(G.error,S);if(z2)Z1(F,z2,"error")}if(F.ended)await F.ended;if(F.limit)await F.limit.delivered}R();let{decision:i,reason:K2}=await M(F.scope.sessionID,async()=>{if(R(),x(G.sessionID))return{decision:X,reason:"host-decides"};let z2=L.get(F.key);if(L.delete(F.key),z2?.next)await q(z2.next);if(R(),x(G.sessionID))return{decision:X,reason:"host-decides"};let r=X,j2,B2,e;if(F.accountId===void 0||!S)r={retry:!1},j2="no-account";else if(F.outputStarted)r={retry:!1},j2="output-started";else if(F.limit){let R2={accountId:F.accountId,limit:F.limit.signal},N2,z1={...F.scope,phase:"retry",previousAccountId:F.accountId,rerouteFrom:R2};try{N2=await Z.chooseAccount(z1)}catch(G1){K("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:F.scope.sessionID,error:A(G1)})}let L2=typeof N2==="object"?N2.hold:void 0,I2=typeof N2==="string"?N2:L2?F.accountId:void 0;if(I2!==void 0)e={accountId:I2,input:z1};try{R()}catch(G1){if(e)await q(e);throw G1}if(x(G.sessionID)){if(e)await q(e);return{decision:X,reason:"host-decides"}}if(L2&&Number.isFinite(L2.delayMs)&&L2.delayMs>=0)r={retry:!0,delay:Math.min(L2.delayMs,l1)},j2="hold";else if(!L2&&I2!==void 0&&I2!==F.accountId)F.rerouted=!0,B2=R2,r={retry:!0,delay:0},j2="reroute";else{if(L2&&e)await q(e),e=void 0;j2="host-decides-last-account"}}else j2="host-decides";if(G.decision=r,r.retry&&F.accountId!==void 0&&j.has(F.id))L.set(F.key,{attemptId:F.id,sessionID:F.scope.sessionID,order:++b,accountId:F.accountId,...B2===void 0?{}:{rerouteFrom:B2},...e===void 0?{}:{next:e}});else if(e)await q(e);return{decision:r,reason:j2}});R(),await l("retry",{sessionID:G.sessionID,...F.accountId===void 0?{}:{accountId:F.accountId},kind:F.scope.kind,attempt:G.attempt,reason:K2,hostDecision:X,decision:i,...S===void 0?{}:{handle:S}})})},F2));let I1=(G)=>{if(s(G),I.delete(G),!a.get(G)?.foreignSeen)a.delete(G);for(let X of _)if(JSON.parse(X)[0]===G)_.delete(X);for(let X of[...j.values()]){if(X.scope.sessionID!==G)continue;p(X,"its session was forgotten"),j.delete(X.id)}for(let[X,V]of L)if(V.sessionID===G)m(X)},J1=new AbortController,v1=$.event;if(v1)(async()=>{try{for await(let G of v1.subscribe({signal:J1.signal}))if(G.type==="session.deleted")I1(G.data.sessionID);else if(G.type==="session.status"&&G.data.status.type==="idle"){let X=G.data.sessionID,V=++b;M(X,async()=>{for(let[P,F]of L)if(F.sessionID===X&&F.order<V){if(L.delete(P),F.next)await q(F.next)}})}}catch(G){if(!J1.signal.aborted)K("opencode2 auth stopped listening for session deletion",{error:A(G)})}})();return{on(G,X){let V=g.get(G);if(!V)V=new Set,g.set(G,V);let P=X;return V.add(P),()=>{V.delete(P)}},accountFor(G,X){return v(P2(G,X))?.accountId},forgetSession:I1,get size(){return j.size},async dispose(){if(T)return;T=!0;for(let G of E.keys())s(G);J1.abort();for(let G of j.values())p(G,"the installation was disposed");j.clear();for(let G of L.keys())m(G);_.clear(),I.clear(),a.clear(),g.clear(),await Promise.all(C.values()),await Promise.all(H2.map(async(G)=>{try{await G.dispose()}catch(X){K("opencode2 auth hook did not dispose cleanly",{error:A(X)})}}))}}}import{createHash as _0}from"node:crypto";var M0=1024,C0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),u1=($)=>p1($,"user"),E0=($)=>C0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function O0($){return _0("sha256").update(JSON.stringify($)).digest("hex")}class q2{runtime;maxSessions;#$=new Map;constructor($,Z=M0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let z=this.#$.get($),Q=Array.isArray(Z.input)?Z.input:[],Y=Q.filter(u1),N=Q.findLastIndex(u1),H=N<0?void 0:O0(Q[N]),U=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,j,B,L;if(U)j=Y.length>0,B=H??z?.fingerprint,L=z?.userCount===void 0?void 0:z.userCount+Y.length;else{B=H,L=Y.length;let _=N>=0&&N>Q.findLastIndex(E0),I=z!==void 0&&!z.completed&&z.fingerprint===B&&z.userCount===L;j=_&&!I}let b=j||!z?{turnID:(J?.uuid??T2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:z.turnID,turnStartedAt:z.turnStartedAt};return this.#Z($,{...b,completed:!1,fingerprint:B,userCount:L}),b}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function j1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var c1=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function A0(){let $=globalThis;return $[c1]??=crypto.randomUUID(),$[c1]}class S2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??A0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new q2}get($){let Z=this.runtime?.uuid??T2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(h2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($),this.frameTurns.forget($)}}var B1={version:d1,"user-agent":a1,originator:"codex_exec"};var R0=1024,x0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,g2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),o1=($)=>g2($)&&($.type==="message"||("role"in $))&&$.role==="user",r1=($)=>g2($)&&$.type==="configuration_update";class V1{http;#$=new Map;constructor($=new S2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!i1.has(z))return!1;if(x0.test(z))return!1;let Q=g2($.reasoning)?$.reasoning:void 0,Y=typeof Q?.effort==="string"?Q.effort:void 0;if(!Y)return!1;let N=this.#$.get(Z.sessionID);if(N===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===N)return!1;let H=Array.isArray($.input)?$.input:void 0;if(!H||H.length===0)return!1;let U=H.findLastIndex(o1);if(U<0){if(J==="http")return!1;return $.reasoning={...Q,effort:N},!0}if($.reasoning={...Q,effort:N},!r1(H[U-1]))H.splice(U,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>R0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function h2($){try{let Z=JSON.parse($);return g2(Z)?Z:void 0}catch{return}}async function s1($,Z,J,z,Q=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),N=h2(Y);if(N)delete N.max_output_tokens;let H=new Headers($.headers),U=m2({rewriteLite:n1,init:{body:N?JSON.stringify(N):$.body===null?void 0:Y},headers:H,metadata:Q.get(Z.sessionID),installationID:Q.installationID,runtime:Q.runtime,websocket:!1,responsesLite:z,applyEffort:(j)=>{J.apply(j,Z,"http")}});return new Request($,{headers:H,body:U.init?.body})}function t1($,Z,J,z){let Q=z.sessions.get($.sessionID),Y=z.frameTurns.get($.sessionID);if(!Q||!Y)return;let N=j1(Q,Y),H=new Headers({"content-type":"application/json"});for(let j of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let B=J.get(j);if(B!==null)H.set(j,B)}m2({init:{body:$.bodyText},headers:H,metadata:N,installationID:z.installationID,runtime:z.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let U=new URL(Z);if(U.protocol==="wss:")U.protocol="https:";if(U.protocol==="ws:")U.protocol="http:";return new Request(U,{method:"POST",headers:H,body:$.bodyText})}function q0($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((z,Q)=>JSON.stringify(z)!==JSON.stringify($[Q]));return J>=0&&r1(Z[J])&&o1(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function e1($,Z,J){let z=h2($);if(z?.type!=="response.create")return;let Q=J.http.advanceFrame(Z.sessionID,z),Y=J.http.get(Z.sessionID);delete z.max_output_tokens;let N=m2({rewriteLite:()=>{},init:{body:JSON.stringify(z)},headers:new Headers,metadata:j1(Y,Q),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(U)=>{J.apply(U,Z,"ws")}}),H=h2(String(N.init?.body));if(!H)return;if(!q0(z.input,H.input)){if("input"in z)H.input=z.input;else delete H.input;return JSON.stringify(H)}return String(N.init?.body)}function S0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function W1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let z=new URL(`${S0(Z)}/responses`);if(z.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")z.protocol=z.protocol==="https:"?"wss:":"ws:";return z.href}import{resolve as $$}from"node:path";var b0=1024;class l2{accounts=new Map;limit;constructor($=b0){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var Z$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),J$=globalThis,U1=J$[Z$]??new Map;J$[Z$]=U1;function H1($){let Z=JSON.stringify([$$($.configPath),$$($.statePath)]),J=U1.get(Z);if(!J)J=new l2,U1.set(Z,J);return J}var Y2="openai",k0=60000,N1=1,D0="request refused: no account with a usable credential",U2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function w0($){let Z=U2($)?$.counters:void 0,J=U2(Z)?Z.resetCredits:void 0,z=U2(J)?J.value:void 0;return typeof z==="number"&&Number.isFinite(z)?z:void 0}function K1($){try{return JSON.parse($)}catch{return}}function z$($){let Z=p2($);return Z?c2(Z):void 0}var y0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function L1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function f0($,Z){let J=u2($);if(J){let Y=typeof $.status==="number"?$.status:void 0;return L1(J,Z,Y)}if($.type!=="response.failed"||!U2($.response))return;let z=$.response.failed;if(U2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let Q=$.response.error;if(U2(Q)){let Y=typeof Q.code==="string"?Q.code:typeof Q.type==="string"?Q.type:void 0;if(Y&&y0.has(Y))return{reason:Y}}return}function I0($,Z){let J=K1($);if(!U2(J))return;let z=typeof J.type==="string"?J.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:X$(J),complete:!0}};let Q=f0(J,Z);if(Q)return{limit:Q};if(z===void 0||z==="error")return;return E$(z)?void 0:{outputStarted:!0}}function v0($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:Y$($),complete:Q$($)}}function h0($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function O$($){let{source:Z,pins:J}=$,z=$.now??Date.now,Q=$.log,Y=$.vault,N=new V1($.codex),H=new Map,U=new Map,j=(W)=>`${W.sessionID}\x00${W.kind}\x00${W.accountId}`,B=new Map,L=$.sessionAccounts??new l2,b=new P$,_=(W,T,E)=>{let K=E?[]:C$(Z.peek().rows,W,T,Y?.identities()??new Set),A=(Y?.routes()??[]).filter((C)=>C.kind==="oauth"&&B$(b2(C.quota),W,T));return[...K.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota,row:C})),...A.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota}))]},I=(W,T,E)=>{let K=F$(W,T,E),A=W.map((q)=>({id:q.id,kind:"oauth",...G$(q.quota)?{quota:q.quota}:{}})),C=W.flatMap((q)=>q.row?[q.row]:[]),M=new Set(W.filter((q)=>!q.row).map((q)=>q.id)),h=Z.rateLimitMarks(C);for(let q of M){let m=B.get(q);if(m===void 0)continue;if(m<=E)B.delete(q);else h.set(q,m)}return{rows:A,now:E,rateLimitMarks:h,refreshBackoff:Z.refreshBackoffFor(C),killswitch:K,requestPull:(q)=>M.has(q)?Y?.requestReading(q):Z.requestReading(q)}},a=(W,T,E,K,A)=>{let C=T$({...W,placement:K$(T),mainId:A});if(C.kind==="block"){Q?.debug("pool admission refused the request",{reason:C.block.reason});return}let M=C.order.filter((h)=>!E.has(h));if(K!==void 0&&M.includes(K))return K;return M[0]},x=(W,T,E,K,A,C,M)=>{let h=new Map(T.map((v)=>[v.id,v.quota])),q={requestBytes:N1,reservePercent:(v)=>V$(E,v===H$?void 0:v),resetCredits:(v)=>w0(h.get(v))},m=F1(W),l=(v,y)=>d2(M,{sessionId:K,requestBytes:N1,validPinnedAccountIds:W.rows.map((f)=>f.id).filter((f)=>!m.excluded.has(f)),excludeAccountIds:v,quotaCheckedAtByAccount:Object.fromEntries(W.rows.map((f)=>[f.id,m.projections.get(f.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(T.map((f)=>[f.id,f.identity])),select:(f)=>_$(W,q,new Set(v),f),persist:y},(f,o)=>M.set(f,o)),u=[...A],t=l(u,C);if(!t)return;let p=t.accountId,n=M$(W,q,p);if(n.kind==="none")return;if(n.kind==="move"){let v=l([...u,p],C);if(v)return v.accountId;return n.reason==="killswitch"?void 0:p}if(n.kind==="detour")return l([...u,p],!1)?.accountId;return p},$2={providerID:Y2,dropChoice(W){let T=j(W);U.get(T)?.drop(),U.delete(T),H.delete(T)},chooseAccount:async(W)=>{let T=await Y?.authority(),E=await $.storage(),K=T!==void 0&&T!=="local",A=()=>{throw new Z2({kind:"no-account",providerID:Y2,sessionID:W.sessionID,requestKind:W.kind,message:a2})};if(K)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())A();Q?.warn("the account pool does not serve requests yet; refusing the request",{kind:W.kind});return}await Z.prepareTokens(Z.peek().rows,E)}let C=z(),M=_(E,C,K),h=L$(I(M.filter((f)=>f.id!==W.rerouteFrom?.accountId),E,C));if(h)await h,C=z(),M=_(E,C,K);let q=new Map(M.map((f)=>[f.id,f])),m=I(M,E,C),l=new Set(W.rerouteFrom?[W.rerouteFrom.accountId]:[]),u=E?.routing?.mode??"main-first",t=W.kind==="primary",p=new Set,n,v,y;try{for(;;){let f=new Set([...l,...p]);if(y=void 0,n=void 0,u==="sticky-balanced"){let c=new Map(J.placementSnapshot(W.sessionID)),s=c.get(W.sessionID);if(y=x(m,M,E,W.sessionID,f,t&&p.size===0,c),y!==void 0&&c.get(W.sessionID)!==s)n=c.get(W.sessionID)}if(y??=a(m,u,f,t?void 0:L.activeAccount(W.sessionID),K?u==="sticky-balanced"?null:N$(Y?.routes()??[]):void 0),y===void 0||p.has(y)){if(l.size>0){let c=new Map(m.rateLimitMarks);for(let s of l)c.delete(s);m={...m,rateLimitMarks:c},l.clear();continue}y=void 0;break}if(t&&u==="sticky-balanced"){let c=F1(m).projections.get(y)?.checkedAt,s=q.get(y)?.identity;v=J.reserve(W.sessionID,{accountId:y,inputBytes:N1,...c!==void 0?{quotaCheckedAt:c}:{},...s!==void 0?{wireIdentity:s}:{}})}let o=q.get(y)?.row;if(o){if(Z.usableToken(o)!==void 0)break;Q?.debug("pool row holds no usable token; choosing again",{accountId:y})}else{if(!Y)break;let c=await Y.authorize(y);if(c){H.set(j({...W,accountId:y}),c);break}Q?.debug("the vault refused to serve an account; choosing again",{accountId:y})}if(v)J.rollback(v);v=void 0,p.add(y)}if(y===void 0&&!K&&M.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(y===void 0&&K&&Y&&(M.length===0||p.size>0)){let f=p.size>0?"vault-refused":U$(Y);throw Q?.warn("vault mode: no vault account can serve; refusing the request",{cause:f}),new Z2({kind:"no-account",providerID:Y2,sessionID:W.sessionID,requestKind:W.kind,message:W$(f,Y.name)})}if(y!==void 0){let f=y,o=v,c=n,s=()=>{if(o)J.finish(o,c);if(t)L.record(W.sessionID,f),$.onRoute?.(W.sessionID,f,u)};if(W.phase==="retry")U.set(j({...W,accountId:y}),{commit:s,drop:()=>{if(o)J.rollback(o)}}),v=void 0;else s();let J2=Q?.info;b.served(m,y,Q&&J2?{info:(_2,A2)=>J2.call(Q,_2,A2)}:void 0)}return Q?.debug("pool account chosen",{kind:W.kind,accountId:y,mode:u,...W.rerouteFrom?{rerouteFrom:W.rerouteFrom.accountId}:{}}),y}finally{if(v)J.rollback(v)}},accountHeaders:async(W)=>{let{accountId:T}=W,E=j(W),K=U.get(E);U.delete(E);let A=()=>{K?.commit()};try{let C=()=>new Z2({kind:"no-account",providerID:Y2,sessionID:W.sessionID,requestKind:W.kind,message:D0}),M=Y&&await Y.authority()!=="local"?void 0:Z.peek().rows.find((m)=>m.id===T);if(!M&&Y){let m=j(W),l=H.get(m)??await Y.authorize(T);if(H.delete(m),!l)throw Q?.warn("the vault refused to serve an account; refusing the request",{accountId:T}),C();return A(),{headers:{...B1,"session-id":W.sessionID,authorization:`Bearer ${l.accessToken}`,"chatgpt-account-id":l.accountIdentity??z$(l.accessToken)??null},attempt:{kind:"vault",routeId:T,receipt:l}}}let h=M?Z.usableToken(M):void 0;if(!M||!h)throw Q?.warn("pool row holds no usable token; refusing the request",{accountId:T}),C();let q=M.identity??z$(h);return A(),{headers:{...B1,"session-id":W.sessionID,authorization:`Bearer ${h}`,"chatgpt-account-id":q??null},attempt:{kind:"pool",token:h,credentialEpoch:M.credentialEpoch}}}finally{K?.drop()}},async rewriteRequest({request:W,sessionID:T,kind:E}){let K=$.codexEndpoint?W1(W.url,$.codexEndpoint()):W.url,A=K===W.url?W:new Request(K,W);return await s1(A,{sessionID:T,kind:E},N,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:W})=>$.codexEndpoint?W1(W,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:W,sessionID:T,kind:E})=>e1(W,{sessionID:T,kind:E},N),quotaFromHeaders:(W)=>v0(W),async limitFromResponse({status:W,headers:T,body:E}){if(W<400)return;let K=K1(await E().catch(()=>"")),A=u2({...U2(K)?K:{},status:W});if(!A)return;let C=z(),M=L1(A,C,W);if(M.retryAfterMs!==void 0)return M;let h=h0(T);return h===void 0?M:{...M,retryAfterMs:h}},inspectEvent:({data:W})=>I0(W,z()),limitFromError(W){let T=K1(W.message),E=u2({...U2(T)?T:{},...W.status!==void 0?{status:W.status}:{}})??(W.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return E?L1(E,z(),W.status):void 0},async onAttemptEnd(W,T){let E=W.data;if(E?.kind!=="vault"||T.status!==401)return;Q?.warn("a vault account answered 401; reporting it to the vault",{accountId:W.accountId}),await Y?.reportFailure(E.receipt,401)}},k=(W,T,E)=>{let K=E.data;if(K?.kind==="vault"){Y?.recordSnapshot(W,T.snapshot,T.complete,K.receipt);return}if(K?.kind!=="pool")return;if(Z.peek().rows.find((C)=>C.id===W)?.credentialEpoch!==K.credentialEpoch){Q?.debug("quota reading dropped: the row holds another credential",{accountId:W});return}Z.recordSnapshot(W,T.snapshot,K.token,T.complete)},g=(W,T,E)=>{let K=z(),A=E.data?.kind==="vault",C=A?Y?.routes().find((q)=>q.id===W)?.quota:Z.peek().rows.find((q)=>q.id===W)?.quota,M=j$(b2(C),T.reason,K,k0,T.retryAfterMs!==void 0?K+T.retryAfterMs:void 0);if(!A){Z.markRateLimited(W,M);return}let h=B.get(W);if(h===void 0||h<M)B.set(W,M)};return{adapter:$2,attach(W){W.on("quota",(T)=>k(T.accountId,T.quota,T.handle)),W.on("limit",(T)=>{g(T.accountId,T.limit,T.handle),Q?.debug("pool row refused the request",{accountId:T.accountId,via:T.via,reason:T.limit.reason,outputStarted:T.outputStarted})})},forgetSession(W){J.forget(W),L.forget(W),N.forget(W)},activeAccount:(W)=>L.activeAccount(W)}}import{resolve as b$}from"node:path";import{Buffer as m0}from"node:buffer";import{resolve as A$}from"node:path";function k2($){return m0.byteLength(JSON.stringify($))}function g0($){return $.reduce((Z,J)=>Z+k2(J),0)}function P1($,Z){return 2+$+Math.max(0,Z-1)}function l0($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+P1(Z.inputBytes,Z.input.length)+1:0)+(J?20+P1(J.inputBytes,J.input.length)+10+P1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function R$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class x${enabled;caps=i2;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let J=R$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let z=J.previous_response_id,Q=this.entries.get($),Y=Q?.head;if(z&&z!==Y?.responseID){this.forget($);return}let{type:N,previous_response_id:H,input:U,...j}=J;this.keep($,{fields:z&&Q?Q.fields:j,fieldsBytes:z&&Q?Q.fieldsBytes:k2(j),...z&&Y?{head:Y}:{},pending:{input:U,inputBytes:g0(U),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let z=this.entries.get($);if(!z?.pending)return;let Q=R$(Z);if(!Q)return;let Y=z.pending,N=Q.response;if(Q.type==="response.created"&&typeof N?.id==="string")Y.responseID=N.id,Y.responseIDBytes=k2(N.id),this.keep($,z);else if(Q.type==="response.output_item.done"&&Q.item){if(typeof Q.response_id==="string"&&Y.responseID!==void 0&&Q.response_id!==Y.responseID)return;Y.output.push(Q.item),Y.outputBytes+=k2(Q.item),this.keep($,z)}else if(Q.type==="response.completed"&&typeof N?.id==="string"){if(N.id===z.head?.responseID||Y.responseID!==void 0&&N.id!==Y.responseID)return;let H={responseID:N.id,responseIDBytes:Y.responseID===N.id?Y.responseIDBytes:k2(N.id),input:[...z.head?.input??[],...Y.input,...Y.output],inputBytes:(z.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},U={...z,head:H,pending:void 0};if(!this.keep($,U))return;J?.({sessionID:$,responseID:H.responseID,bodyText:this.body(z.fields,H)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=l0(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let z=this.entries.keys().next().value;if(z===void 0)break;this.forget(z)}return this.entries.has($)}}var q$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),S$=globalThis,T1=S$[q$]??new Map;S$[q$]=T1;function n2($){let Z=JSON.stringify([A$($.configPath),A$($.statePath)]),J=T1.get(Z);if(!J)J=new x$,T1.set(Z,J);return J}var u0=5000,p0=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],c0=["x-opencode-parent-session-id","x-parent-session-id"];function y$($){let Z=k$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:D$($?{...$,cachekeep:Z}:$)}}var f$=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),I$=globalThis,D2=I$[f$]??new Map;I$[f$]=D2;function d0($,Z){let J=[],z=()=>J.at(-1)?.location,Q=()=>{let U=z();if(!U)throw Error("no location holds keep-warm");return U},Y=(U,j)=>{H.remove(U),z()?.log?.debug(`cachekeep dropped target (${j})`,{sessionKey:U})},N=async(U)=>{if(U.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let j=U.accountId??"main",B=Q(),L=await B.source.accessFor(j,await B.storage());if(!L)throw Error(`pool row ${j} has no usable token`);return{token:L.token,identity:L.row.identity}},H=w$({...i2,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(U,j)=>Q().fetch(U,j),logger:{debug:(U,j)=>z()?.log?.debug(U,j),warn:(U,j)=>z()?.log?.warn(U,j)},getWindow:()=>z()?.settings().window,getSustain:()=>z()?.settings().sustain===!0,resolveLocal:N,vault:{owns:(U)=>z()?.vault.owns(U)===!0,authority:()=>Q().vault.authority(),send:async(U,j,B)=>{let L=Q();if(await L.vault.authority()!=="vault")return;return L.vault.send(U,j,B)}},activeAccount:(U)=>{if(U===void 0)throw Error("target has no session");let j=z(),B=j?.settings();if(!j||!B?.enabled){Y(U,"keep-warm is off");return}if(!B.subagents&&H.status().targets.some((b)=>b.sessionKey===U&&b.isSubagent)){Y(U,"subagent warming is off");return}let L=j.accounts.activeAccount(U);if(L===void 0){Y(U,"no account recorded for the session");return}return L},verifyCredential:({target:U,mode:j,identity:B})=>{if(U.meta.credentialMode!==j)throw Error(`a target captured in ${U.meta.credentialMode??"an unknown"} mode is not warmed with a ${j} credential`);if(B!==U.meta.chatgptAccountId)throw Y(U.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:H,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??u0}}function a0($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((Q)=>typeof Q?.text==="string"?Q.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function i0($){let Z={};for(let J of p0){let z=$.get(J);if(z)Z[J]=z}return Z}function v$($,Z,J){let z=JSON.stringify([b$($.configPath),b$($.statePath)]),Q=D2.get(z);if(!Q)Q=d0(J,Z.settings()),D2.set(z,Q);let Y=Q,N=n2($);N.setEnabled(Y.settings.enabled);let H={location:{...Z,settings:()=>Y.settings}};Y.holders.push(H);let U=!1,j=async(B)=>{try{let L=H.location.settings();if(U||!L.enabled)return;if(B.kind!=="primary"){if(B.kind==="generate"&&a0(await B.request.clone().text())){if(U)return;Y.manager.remove(B.sessionID)}return}let b=B.attempt.data,_=b?.kind==="pool"?"local":b?.kind==="vault"?"vault":void 0;if(!_)return;let I=B.request.headers,a=c0.some((Q2)=>I.has(Q2))||Z.parentOf!==void 0&&await Z.parentOf(B.sessionID)!==void 0;if(a&&!L.subagents)return;let x=await B.request.clone().text();if(U)return;let w=I.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:B.sessionID,bodyText:x,accountId:B.attempt.accountId,isSubagent:a,meta:{replayHeaders:i0(I),...w?{chatgptAccountId:w}:{},routingSessionId:B.sessionID,url:B.request.url,credentialMode:_}})}catch(L){Z.log?.warn("cachekeep capture failed",{error:L instanceof Error?L.message:String(L)})}};return{manager:Y.manager,configure:(B)=>{Object.assign(Y.settings,B),N.setEnabled(Y.settings.enabled)},capture:j,forget:(B)=>Y.manager.remove(B),async release(){if(U)return;U=!0;let B=Y.holders.indexOf(H);if(B>=0)Y.holders.splice(B,1);if(Y.holders.length>0)return;if(D2.get(z)===Y)D2.delete(z);Y.manager.stop();let L;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((b)=>{L=setTimeout(b,Y.joinTimeoutMs),L.unref?.()})])}finally{clearTimeout(L)}}}}import{mkdirSync as n0}from"node:fs";import{dirname as o0,resolve as r0}from"node:path";function s0(){return h$("opencode2")}var t0=2000;class p${path;options;sessions;frameTurns=new q2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Y=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=l$($,Z.uuid??T2)}get($,Z=T2){let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}:0`},this.sessions.set($,J),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Q()}return J}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Q()}#Q(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??t0),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Y)this.#Y=!0,this.#G=this.#G.then(()=>{return this.#Y=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=_1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((z)=>{let Q=this.sessions.get(z);return Q?[[z,Q]]:[]}),Z=[...this.#Z],J=null;try{if(n0(o0(this.path),{recursive:!0}),J=await this.#B(),!J)return;let z;try{z=_1(this.path)}catch{z=new Map}await this.options.afterRead?.();let Q=!1;for(let Y of Z)if(z.delete(Y))Q=!0;for(let[Y,N]of $){if(z.get(Y)===N.threadID)continue;z.set(Y,N.threadID),Q=!0}if(Q)u$(this.path,z)}catch{return}finally{await J?.release().catch(()=>{})}for(let[z,Q]of $)if(this.sessions.get(z)===Q)this.#$.delete(z);for(let z of Z)if(!this.sessions.has(z))this.#Z.delete(z)}#B(){return g$(this.path,this.options.lockWaitMs??m$)}}var c$=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),d$=globalThis,M1=d$[c$]??new Map;d$[c$]=M1;function a$($=s0()){let Z=r0($),J=M1.get(Z);if(!J)J=new p$(Z),M1.set(Z,J);return J}var i$=Symbol.for("cortexkit.openai-auth.v2.commands"),e0=W2("v2-command");function C1($){e0.warn(`/openai needs the terminal UI (session state: ${$}).`)}function $4(){let $=globalThis;return $[i$]??={locations:new Map},$[i$]}async function $Z($,Z){let J=$4(),z=$.location.directory,Q={menu:Z,session:$.session,closed:new AbortController},Y=await o$(z),N=await n$(t$,Y.dir,()=>e$({...Y,drain:s$,apply:(B)=>{let L=J.locations.get(z);if(!L)throw Error("The OpenAI menu location was closed");return L.menu.apply(B)}})),H=J.locations.get(z);J.locations.set(z,Q),H?.closed.abort(),await H?.registration?.dispose(),J.command??={name:"openai",description:"OpenAI account menu",async execute(B){let L=J.locations.values().next().value?.session;if(!L)return C1("no live location");let b=await L.get({sessionID:B.sessionID}),_=J.locations.get(b.location.directory);if(!_)return C1("location closed");let I=await r$(B.sessionID,_.closed.signal);if(!I||J.locations.get(b.location.directory)!==_){if(!I&&!_.closed.signal.aborted)E1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},B.sessionID);return C1(_.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let a=await _.menu.open(B.sessionID);E1(a,B.sessionID)}};let U=J.command;try{Q.registration=await $.command.transform((B)=>{B.add(U)})}catch(B){if(Q.closed.abort(),J.locations.get(z)===Q)J.locations.delete(z);throw await N.release(),B}let j=!1;return async()=>{if(j)return;if(j=!0,Q.closed.abort(),J.locations.get(z)===Q)J.locations.delete(z);await N.release(),await Q.registration?.dispose()}}var Z4="openai-auth-pool-browser",J4="openai-auth-pool-headless",z4="openai-auth-vault",G4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function w2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function QZ($){return{method:{id:z4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await ZZ($.paths,$.name)!=="vault")throw Error(G4)}}}function XZ($){let Z=(J,z,Q)=>({method:{id:J,type:"oauth",label:z},async authorize(){if($.vault)await w2($.vault);let Y=await $.beginLogin({version:$.version,headless:Q});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(Z4,"ChatGPT (openai-auth pool, browser)",!1),Z(J4,"ChatGPT (openai-auth pool, headless)",!0)]}function O1($){let Z=(J)=>typeof J==="string"?J:"";return x2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===GZ||JZ($)}function Y4($){if($.accountId)return $.accountId;let Z=$.access?p2($.access):void 0;return Z?c2(Z):void 0}async function jZ($,Z,J,z={}){if(z.vault)await w2(z.vault);if(O1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Q=zZ($,{rowLocks:(_)=>YZ(Z,_)}),Y=await Q.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let N={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},H=Y4(J);if(z.vault)await w2(z.vault);let U=H!==void 0?{identity:H}:{};if(z.origin==="import"){let _=Y.rows.find((I)=>H!==void 0&&I.identity===H||I.credential?.type==="oauth"&&I.credential.refresh===J.refresh);if(_)return{id:_.id,operation:"kept"}}let j=Y.rows.filter((_)=>_.type==="oauth"&&!_.invalid),B=H?j.find((_)=>_.identity===H):void 0,L=Y.rows.find((_)=>_.id===o2);if(B)return{id:(await Q.replace(B.id,N,U)).id,operation:"replaced"};if(!L){let _=await Q.add({id:o2,credential:N,...U,...J.label!==void 0?{label:J.label}:{}});return{id:_.id,operation:_.outcome==="added-disabled"?"added-disabled":"added"}}if(!L.invalid&&!L.credential)return{id:(await Q.replace(o2,N,U)).id,operation:"replaced"};let b=await Q.add({id:J.id,credential:N,...U,...J.label!==void 0?{label:J.label}:{}});return{id:b.id,operation:b.outcome==="added-disabled"?"added-disabled":b.outcome==="rotated"?"replaced":"added"}}function Q4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function WZ($){let Z={...$,allowAction:Q4,unavailableSections:[]};return{open:(J)=>BZ(Z,J),apply:(J)=>{let z=J!==null&&typeof J==="object"?J:{},Q=z.values&&typeof z.values==="object"&&!Array.isArray(z.values)?Object.fromEntries(Object.entries(z.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return VZ(Z,{command:"openai",sectionId:typeof z.sectionId==="string"?z.sectionId:"",actionId:typeof z.actionId==="string"?z.actionId:"",...Q?{values:Q}:{},...z.confirmed===!0?{confirmed:!0}:{},...typeof z.itemId==="string"?{itemId:z.itemId}:{},...typeof z.sessionId==="string"?{sessionId:z.sessionId}:{}})}}}function X4($,Z){if(!UZ($.modelID??$.id)){$.enabled=!1;return}let J=HZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((z)=>[z.id,z])).values()]}function FZ($){return $.model.transform((Z)=>{let J=Z.list(Y2);for(let z of J){let Q=NZ(String(z.id)),Y=Q?J.find((N)=>String(N.id)===Q):void 0;Z.update(Y2,String(z.id),(N)=>X4(N,Y?.variants?.map((H)=>({...H,id:String(H.id)}))))}})}class A1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!KZ())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let z=this.pending.keys().next().value;if(z)this.take(z)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>r2({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),z=J&&this.take(J);if(!z)return;let{reason:Q,message:Y}=Z.error,N=Y?`${Q}: ${Y}`:Q;await this.safely(()=>r2({...z,error:s2(N,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>r2({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class R1{counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function MZ($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let z=await LZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,z),PZ(z,$.now(),!0)}}function CZ($){let{source:Z,counts:J,now:z}=$,Q=async(j)=>{let B=await Z.rowAccess(j,await $.storage());if(!B?.row)throw new TZ("unknown_account",`${j==="main"?"Main":"Fallback"} account ${j} was not found.`);return _Z(j,B)},Y=async(j)=>{if($.authority&&await $.authority()!=="local")return{account:j,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[B]=await Z.pollRows(await $.storage(),{ids:[j]});if(!B)return{account:j,ok:!1,error:"targeted quota refresh returned no result"};return{account:B.id,ok:B.ok,...B.error!==void 0?{error:B.error}:{}}},N=(j)=>Z.peek().rows.find((B)=>B.id===j),H=(j)=>{let B=N(j);if(!B)return null;let L=b2(B.quota)??{},b=J.applicable(B),_=Math.max(0,...[L.primary?.checkedAt,L.secondary?.checkedAt].filter((I)=>typeof I==="number"));return{quota:{...L,...b!==void 0?{resetCreditsApplicable:b}:{}},checkedAt:_,refreshAfter:_,...B.identity!==void 0?{accountId:B.identity}:{}}};return{resolveResetTarget:Q,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(j)=>{let B=N(j);if(!B)return!1;let L=Z.rateLimitMarks([B]).get(B.id);return L!==void 0&&L>z()},getMain:()=>H("main"),getFallback:(j)=>H(j)}}}import{resolve as EZ}from"node:path";var j4=1024;class x1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=j4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return d2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var OZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),AZ=globalThis,q1=AZ[OZ]??new Map;AZ[OZ]=q1;function RZ($){let Z=JSON.stringify([EZ($.configPath),EZ($.statePath)]),J=q1.get(Z);if(!J)J=new x1,q1.set(Z,J);return J}import{statSync as B4}from"node:fs";import{resolve as V4}from"node:path";function fZ($){return $.map((Z)=>{try{let J=B4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function S1($){return fZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function xZ($){return fZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+S1($)}class IZ{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:xZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let z=new Set;J={producers:z,stop:$.pins.subscribe((Q,Y)=>{let N=z.values().next().value;if(N)this.publish(N,{sessionId:Q,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let z of this.producers){let Q={stamp:xZ(z),roster:z.vault.snapshot()},Y=this.observations.get(z);if(Q.stamp!==Y?.stamp||Q.roster!==Y?.roster)this.observations.set(z,Q),this.publish(z)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;let z=await $.vault.authority()!=="local",Q=S1($),Y=()=>this.producers.has($)&&$.vault.enrolled()===z&&S1($)===Q,N=await(z?f2($.paths):E2($.paths)),H=z?wZ($.vault.snapshot()?.rows,new Set($.vault.routes().map((j)=>j.id)),N,Date.now()):yZ((await $.source.sidebarView()).rows,N,Date.now());if(await SZ(H,this.file,{canWrite:Y}),!Y()||!Z)return;let U=H.vaultAccounts??H.fallbacks;if(Z.accountId===void 0){await kZ(Z.sessionId,U,this.file,{canWrite:Y});return}if(Z.pin){let j=Date.now();await DZ({sessionId:Z.sessionId,assignment:{accountId:Z.pin.accountId,wireAccountId:Z.pin.wireIdentity,inputBytes:Z.pin.inputBytes??0,quotaCheckedAt:Z.pin.quotaCheckedAt,assignedAt:j,lastSeenAt:j},validPinnedAccountIds:[...z?[]:["main"],...U.filter((B)=>B.enabled).map((B)=>B.id)]},this.file)}await bZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??H.route,updatedAt:Date.now()},U,this.file,{canWrite:Y})}).catch(()=>{W2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var vZ=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),hZ=globalThis,y2=hZ[vZ]??new Map;hZ[vZ]=y2;function mZ($,Z=qZ(),J=2000){let z=V4(Z),Q=y2.get(z);if(!Q)Q=new IZ(z,J),y2.set(z,Q);let Y=Q,N=Y.add($),H=!1;for(let[U,j]of $.pins.snapshot())Y.publish($,{sessionId:U,pin:j,accountId:j.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(U,j,B)=>{Y.publish($,{sessionId:U,accountId:j,route:B})},async release(){if(H)return;if(H=!0,N(),await Y.settled(),Y.empty&&y2.get(z)===Y)y2.delete(z)}}}var $1="cortexkit-openai-auth",H4=5000;async function gZ($,Z,J,z=new S2,Q,Y,N){let H=new A1(J),U=new W4,j=new Map,B=new Map,L=(x)=>{B.delete(x);for(let w of j.keys())if(w.startsWith(`${x}:`))j.delete(w)},b=(x)=>{N?.(x.sessionID),Y?.send(x.sessionID,x.frame)},I=await X1({session:{hook:(x,w,Q2)=>$.session.hook(x,async($2)=>{let k=x==="http.request"?$2:void 0,g=x==="experimental.ws.handshake"?$2:void 0,T=(k?k.request.headers:g?new Headers(g.headers):void 0)?.get("authorization")===`Bearer ${V2(Z.providerID)}`,E={};if(g)j.delete(`${g.sessionID}:${g.kind}`);try{await U.run(E,()=>w($2))}catch(K){if(T&&!(K instanceof Z2))throw aZ(K);throw K}if(k&&T&&E.attempt){let K=k.request.headers.get("thread-id");if(K)k.request.headers.set("session-id",K)}if(k&&T&&E.attempt)await H.captureHttp(k.request,E.attempt);if(k&&T&&E.attempt)await Q?.({sessionID:k.sessionID,kind:k.kind,request:k.request,attempt:E.attempt});if(g&&T&&E.attempt)g.headers["session-id"]=z.get(g.sessionID).threadID;if(x==="experimental.ws.send"){let K=$2,A=j.get(`${K.sessionID}:${K.kind}`);if(A)await H.frame(K.frame,A.attempt);if(A&&K.kind==="primary")b(K)}if(k||g){let K=k??g;if(!K)return;let C=(k?k.request.headers:new Headers(K.headers)).get("authorization")?.replace(/^Bearer /,"");if(T&&C)B.set(K.sessionID,C);else B.delete(K.sessionID);if(g){let M=`${g.sessionID}:${g.kind}`;if(T&&C&&E.attempt)j.set(M,{bearer:C,attempt:E.attempt,url:g.url,headers:new Headers(Object.entries(g.headers).filter(([h])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(h.toLowerCase())))});else j.delete(M)}if(B.size>512){let M=B.keys().next().value;if(M)B.delete(M)}if(j.size>512){let M=j.keys().next().value;if(M)j.delete(M)}}else if(x==="experimental.ws.receive"){let K=$2,A=j.get(`${K.sessionID}:${K.kind}`);if(A){if(z.frameReceived(K.sessionID,K.frame),K.kind==="primary"){let C;if(Y?.receive(K.sessionID,K.frame,(M)=>{C=M}),C)try{let M=t1(C,A.url,A.headers,z);if(M)await Q?.({sessionID:K.sessionID,kind:"primary",request:M,attempt:A.attempt})}catch(M){J.warn("cachekeep WebSocket capture failed",{error:M instanceof Error?M.message:String(M)})}}K.frame=iZ(K.frame,A.bearer)}}else if(x==="retry"){let K=$2,A=B.get(K.sessionID);if(A)Object.assign(K.error,{message:s2(K.error.message,A)})}},Q2)},event:{subscribe:(x)=>async function*(){for await(let w of $.event.subscribe(x)){if(w.type==="session.deleted")L(w.data.sessionID);yield w}}()}},{...Z,rewriteRequest:async(x)=>{let w=U.getStore();if(w)w.attempt=x.attempt;return Z.rewriteRequest?.(x)},rewriteHandshakeURL:(x)=>{let w=U.getStore();if(w)w.attempt=x.attempt;return Z.rewriteHandshakeURL?.(x)},onAttemptEnd:async(x,w)=>{await H.end(x,w),await Z.onAttemptEnd?.(x,w)},rewriteResponse:async(x)=>{await H.response(x.request,x.response.status);let w=await Z.rewriteResponse?.(x)??x.response;return nZ(w,x.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(x)=>{let w=x.get("authorization");return w?.startsWith("Bearer ")?w.slice(7):void 0}},logger:{warn:(x,w)=>J.warn(x,{data:w})}}),a=I.dispose;return{...I,dispose:async()=>{B.clear(),j.clear(),await a(),await H.settle(),H.clear()}}}function D1($={}){return{id:$1,setup:(Z)=>N4(Z,$)}}async function N4($,Z={}){let J2=[];try{let J=W2("opencode2");let z=W2("quota");let Q=Z.version??rZ;await j0({version:Q,...Z.runtimeLayout});let Y=Z.paths??(()=>tZ(oZ()));let N=await f2(Y());let H=N?.logging?.level;if(H&&typeof H==="string")uZ(H);let U=Z.fetch??fetch;let j=Z.now??Date.now;let B=Z.poolMigration??V0;if(!B&&!O2(Y().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let O=(X2)=>{throw new Z2({kind:"no-account",providerID:Y2,sessionID:X2.sessionID,requestKind:X2.kind,message:a2})},d=await gZ($,{providerID:Y2,chooseAccount:O,accountHeaders:O},J);return()=>d.dispose()}let L=Z.vault?.firstRosterWaitMs??z0;let b=B0({host:"opencode",stateDir:Z.vault?.stateDir??dZ(Y().statePath),reservedRouteIds:()=>k.peek().rows.map((O)=>O.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>U},Y());let _=b.vault;let I=async()=>await _.authority()==="local"?E2(Y()):f2(Y());let a=!1;let x=!1;const w=t2(J2,{[Symbol.dispose](){if(!a)b.release()}},0);await _.authority();let Q2=b.firstRoster;let $2=new R1;let k=new G0({paths:Y,refreshProvider:async(O)=>{let d=await cZ({refreshToken:O.refresh,fetchImpl:U,now:j}),X2=pZ({id_token:"",access_token:d.access,refresh_token:d.refresh});return{...d,...X2?{identity:X2}:{}}},pullQuota:MZ({fetchImpl:U,now:j,counts:$2,logger:z}),now:j,vaultIdentities:()=>_.identities(),vaultMode:()=>_.enrolled(),vaultAuthority:()=>_.authority(),vaultFirstRoster:Q2,vaultFirstRosterBackgroundWaitMs:L,log:W2("pool")});if(await _.authority()==="local")await k.load();let g=Z.heartbeat===!1?void 0:await Q0({version:Q,logger:W2("heartbeat")});let W=Z.fence??(()=>sZ({currentVersion:Q}));let T=Z.slot??W0();let E=async()=>eZ(Y(),await T.get({path:{id:"openai"}}));let K=!1;let A=B?Y0({paths:Y,slot:T,version:Q,fence:W,runDeps:{vaultServes:()=>_.serves()},paused:async()=>await _.authority()!=="local",migrate:async(O)=>{let d=await $0(O);if(K=d.status==="refused",!x)await k.load();return d},adopt:async(O)=>{if(x)return{status:"retry",reason:"unsettled"};if(!await k1(Q2,L))return{status:"retry",reason:"vault-roster-pending"};if(x)return{status:"retry",reason:"unsettled"};let d=await Z0(O);if(!x)await k.load();return d}}):void 0;A?.start();b.start();let C=RZ(Y());let M=mZ({paths:Y(),source:k,pins:C,vault:_},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const h=t2(J2,{[Symbol.dispose](){if(!a)M.release()}},0);M.publish();let q=Z.codex??new S2(void 0,void 0,a$());let m=y$(N);let l=n2(Y());let u=v$(Y(),{source:k,storage:I,vault:_,accounts:H1(Y()),settings:()=>m,parentOf:async(O)=>(await $.session.get({sessionID:O}))?.parentID??void 0,fetch:U,log:W2("cachekeep")},{now:j,codexResponsesUrl:e2().codexApiEndpoint,...Z.cacheKeep});const t=t2(J2,{[Symbol.dispose](){if(!a)u.release()}},0);let p=O$({codex:q,onRoute:M.route,source:k,slotPlaceholderWithoutMain:E,storage:I,pins:C,sessionAccounts:H1(Y()),vault:_,awaitVaultRoster:async()=>{await k1(_.awaitRequestRoster(),J0)},responsesLite:()=>e2().responsesLite,codexEndpoint:()=>e2().codexApiEndpoint,now:j,log:J});let n=await gZ($,p.adapter,J,q,(O)=>u.capture(O),l,(O)=>u.forget(O));p.attach(n);let v=async(O)=>{if(await w2(_),O2(Y().configPath))return;if(await A?.idle(),O2(Y().configPath))return;if(K&&!O1(O)&&(await W()).open){await k.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let y=async(O)=>{await v(O);let d=await jZ(k.poolStore(),Y(),O,{vault:_});if(!O2(Y().configPath))await A?.requestAdoption();await k.load(),J.info("ChatGPT login stored in the account pool",d)};let f=await Y1($,{integrationID:Y2,methods:XZ({beginLogin:Z.beginLogin??b1,version:Q,vault:_}),onLogin:(O)=>y(O),label:"ChatGPT (openai-auth account pool)",vault:QZ(_)});let o=await FZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let c=$.command&&$.location?await $Z({session:$.session,command:$.command,location:$.location},Z.controlPlane??WZ({...CZ({source:k,storage:I,counts:$2,now:j,authority:()=>_.authority()}),fetchImpl:U,now:j,randomUUID:U4,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:Q,layoutNotice:X0,loadAccounts:E2,store:()=>k.poolStore(),migration:async()=>{if(O2(Y().configPath))return{migrated:!0};let O=await W();return{migrated:!1,blockers:O.open?[]:O.blockers}},beginAccountLogin:Z.beginLogin??b1,refreshAllQuota:async()=>(await k.pollRows(await E2(Y()))).map((O)=>({...O,account:O.id})),getStickyRouting:async(O)=>C.get(O),cacheKeepManager:u.manager,setCacheKeepEnabled:(O)=>u.configure({enabled:O}),setCacheKeepSubagents:(O)=>u.configure({subagents:O}),setCacheKeepSustain:(O)=>u.configure({sustain:O}),setCacheKeepWindow:(O)=>u.configure({window:O}),afterWrite:()=>k.load(),refreshSidebar:()=>M.publish(),clearStickyRouting:async(O)=>{let d=C.get(O)!==void 0;return C.forget(O),d},vault:_})):void 0;let s=new AbortController;(async()=>{try{for await(let O of $.event.subscribe({signal:s.signal}))if(O.type==="session.deleted")p.forgetSession(O.data.sessionID),u.forget(O.data.sessionID),l.forget(O.data.sessionID)}catch(O){if(!s.signal.aborted)J.warn("stopped listening for session deletion",{error:O instanceof Error?O.message:String(O)})}})();a=!0;return async()=>{x=!0,s.abort();let O=u.release();await c?.(),A?.dispose(),await k.dispose(),await M.release(),await Promise.allSettled([n.dispose(),f.dispose(),o.dispose()]);let d;try{await Promise.race([Promise.all([A?.idle(),k.settled(),q.store?.settled(),O]),new Promise((X2)=>{d=setTimeout(X2,H4),d.unref?.()})])}finally{clearTimeout(d),b.release(),await g?.release()}}}catch(_2){var A2=_2,M2=1}finally{lZ(J2,A2,M2)}}var F4=D1(),m6={id:$1,setup:F4.setup,server:U0.server};export{m6 as default,D1 as createOpenAIAuthPlugin,$1 as OPENAI_AUTH_PLUGIN_ID};
|
|
3
|
+
`)}}function B1($,Z){let J=new TextDecoder,z="",Y=(N)=>{let H=P0(N);if(!H)return;try{$(H)}catch(W){Z(W)}},Q=()=>{for(;;){let N=/\r?\n\r?\n/.exec(z);if(!N)return;let H=z.slice(0,N.index);z=z.slice(N.index+N[0].length),Y(H)}};return new TransformStream({transform(N,H){H.enqueue(N),z+=J.decode(N,{stream:!0}),Q()},flush(){if(z+=J.decode(),Q(),z.trim()!=="")Y(z);z=""}})}var u1=512,p1=1200000,C2="x-common-auth-attempt",T2=($,Z)=>JSON.stringify([$,Z]),G2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function T0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function L0($,Z){let J=$.getReader();return new ReadableStream({async pull(z){let Y;try{Y=await J.read()}catch(Q){Z({reason:"failed",message:Q instanceof Error?Q.message:String(Q)}),z.error(Q);return}if(Y.done)Z(),z.close();else z.enqueue(Y.value)},async cancel(z){Z({reason:"cancelled",...z===void 0?{}:{message:String(z)}}),await J.cancel(z)}})}function v2($,Z){for(let[J,z]of Object.entries(Z)){let Y=J.toLowerCase();for(let Q of Object.keys($))if(Q.toLowerCase()===Y)delete $[Q];if(z!==null)$[J]=z}}function _0($,Z){for(let[J,z]of Object.entries(Z))if(z===null)$.delete(J);else $.set(J,z)}async function V1($,Z,J={}){let{providerID:z}=Z,Y=J.gateOnPlaceholder,Q=(G)=>Y===void 0||Y.credential(G)===V2(z),N=J.logger,H=Math.max(1,J.maxRecords??u1),W=[...J.hostCredentials??[V2(z)],...Y?[V2(z)]:[]].filter((G)=>G!==""),j=new Map,U=new WeakMap,P=new Map,S=0,_=new Set,w=new Map,i=new Map,R=(G)=>{let X=i.get(G);return X?.ownedSeen===!0&&X.foreignSeen},y=(G,X)=>{w.set(G,X);let B=i.get(G)??{ownedSeen:!1,foreignSeen:!1};if(X)B.ownedSeen=!0;else B.foreignSeen=!0;i.set(G,B)},Y2=(G,X)=>{let B=Y?.refuseMisplaced,T=B?[...X].filter(([,D])=>D.includes(V2(z))):[],F=Q(X)&&(!B||T.length>0);if(B){if(T.length>0&&(T.length!==1||!F))throw y(G.sessionID,!1),new Z2({kind:"placement-refused",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:B(T[0]?.[0]??"")})}return y(G.sessionID,F),F},$2=!1,k=!1,g=new Map,V=0,L=!1,E=new Map,K=(G,X)=>{try{N?.warn(G,X)}catch{}},A=(G)=>G instanceof Error?G.message:String(G),C=new Map,M=(G,X)=>{let B=(C.get(G)??Promise.resolve()).then(X),T=B.then(()=>{},()=>{});return C.set(G,T),T.then(()=>{if(C.get(G)===T)C.delete(G)}),B},h=(G,X)=>{let B=C.get(G);return B?B.then(()=>h(G,X)):X()},q=async(G)=>{try{await Z.dropChoice?.({...G.input,accountId:G.accountId})}catch(X){K("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:G.input.sessionID,error:A(X)})}},m=(G)=>{let X=P.get(G);if(P.delete(G),X?.next){let B=X.next;M(X.sessionID,()=>q(B))}},l=async(G,X)=>{let B=g.get(G);if(!B||B.size===0)return;await Promise.all([...B].map(async(T)=>{try{await T(X)}catch(F){K("opencode2 auth listener threw; the request is unaffected",{event:G,error:A(F)})}}))},u=async(G,X)=>{try{await Z.onAttemptEnd?.(G,X)}catch(B){K("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:G.attemptId,error:A(B)})}},t=(G,X)=>{if(G.ended||!G.attempt)return;let B={...G.status===void 0?{}:{status:G.status},outputStarted:G.outputStarted,...G.limit?{limit:G.limit.signal}:{},...X?{error:X}:{}};if(X)G.endError=X;G.ended=u(G.attempt,B)},p=(G,X)=>t(G,{reason:"abandoned",message:X}),n=(G)=>[...j.values()].filter((X)=>X.key===G),v=(G)=>n(G).at(-1),f=(G)=>{if(j.delete(G.id),P.get(G.key)?.attemptId===G.id||!n(G.key).length)m(G.key)},I=(G)=>{j.set(G.id,G);while(j.size>H){let X=j.values().next().value;if(X===void 0)break;p(X,"dropped to keep the record bound"),f(X)}},o=(G)=>G.accountId===void 0?void 0:{...G.scope,accountId:G.accountId},c=(G,X)=>new Z2({kind:"no-account",providerID:z,sessionID:G.sessionID,requestKind:G.kind,...X===void 0?{}:{message:X}}),s=(G)=>{E.get(G)?.clear(),E.delete(G)},J2=async(G,X)=>{let B=()=>c(G,`${z} ${G.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(L)throw B();let T=E.get(G.sessionID);if(!T)T=new Set,E.set(G.sessionID,T);let F={};T.add(F);let D=()=>{if(!T.has(F))throw B()};try{return await X(D)}finally{if(T.delete(F),T.size===0&&E.get(G.sessionID)===T)E.delete(G.sessionID)}},_2=(G,X)=>{for(let[B,T]of X)if(W.some((F)=>T.includes(F)))throw new Z2({kind:"host-credential-on-wire",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:`${z} ${G.kind} request still carries the host's placeholder credential in ${B}; the adapter's account headers must replace it`})},R2=(G)=>{for(let X of n(G))if(X.ended||!X.attempt)f(X);else if(X.transport==="ws"||X.judged)p(X,"a newer attempt of its session and kind began"),f(X)},M2=async(G,X,B,T)=>{let F=T2(G.sessionID,G.kind),{input:D,accountId:x}=await h(G.sessionID,async()=>{B();let r=P.get(F);P.delete(F);let j2=r?.accountId??v(F)?.accountId;R2(F);let B2=r?.next,e=B2!==void 0&&B2.input.modelID===G.modelID&&B2.input.agent===G.agent,x2={...G,phase:"request",...j2===void 0?{}:{previousAccountId:j2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(B2&&!e)await M(G.sessionID,()=>q(B2)),B();let N2=e?B2.accountId:await Z.chooseAccount(x2);return{input:x2,accountId:typeof N2==="string"?N2:void 0}});B();let b={},a;if(x!==void 0){let r=await Z.accountHeaders({...G,accountId:x});if(B(),T0(r))b=r.headers,a=r.attempt;else b=r}let K2=`attempt-${++V}`,z2={id:K2,key:F,scope:G,accountId:x,headers:b,attempt:x===void 0?void 0:{...G,accountId:x,attemptId:K2,transport:T,data:a},...T===void 0?{}:{transport:T},outputStarted:!1};if(I(z2),z2.attempt)l("select",{...G,accountId:z2.attempt.accountId,hook:X,...D.previousAccountId===void 0?{}:{previousAccountId:D.previousAccountId},...D.rerouteFrom===void 0?{}:{rerouteFrom:D.rerouteFrom},handle:z2.attempt});return z2},O=async(G,X,B,T,F)=>{let D=T2(G.sessionID,G.kind),x=T===void 0?void 0:j.get(T);if(x?.key!==D)x=void 0;if(!x){if(x=v(D),n(D).filter((a)=>a.transport===void 0&&!a.ended).length>1&&!k)k=!0,K("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:G.sessionID,kind:G.kind})}if(!x||x.transport!==void 0||x.ended)x=await M2(G,X,F,B);else if(x.transport=B,x.attempt)x.attempt.transport=B;if(B==="ws"){for(let b of n(D))if(b!==x&&b.transport==="ws")p(b,"a newer attempt of its session and kind went out over WebSocket")}return x},d=async(G,X)=>{try{return await X()}catch(B){throw t(G,{reason:"failed",message:A(B)}),B}},X2=(G,X)=>{let B=n(T2(G,X)).filter((T)=>T.transport==="ws").at(-1);return B?.attempt!==void 0&&!B.ended?B:void 0},G1=(G,X,B)=>{let T=o(G);if(!T||!G.attempt||G.limit)return;G.limit={signal:X,delivered:l("limit",{...T,via:B,limit:X,outputStarted:G.outputStarted,handle:G.attempt})}},f1=(G,X,B,T)=>{let F=o(G);if(!F||!G.attempt)return;l("quota",{...F,transport:X,...T===void 0?{}:{status:T},quota:B,handle:G.attempt})},I1=(G,X,B,T)=>{let F=G.attempt;if(!F)return;let D=Z.inspectEvent?.(T===void 0?{transport:X,data:B,attempt:F}:{transport:X,data:B,event:T,attempt:F});if(!D)return;if(D.quota!==void 0)f1(G,X,D.quota);if(D.outputStarted)G.outputStarted=!0;if(D.limit)G1(G,D.limit,X);if(D.error!==void 0)t(G,{reason:"failed",message:D.error});else if(D.done)t(G)},N0=(G,X)=>{let B=G.attempt;if(!B||X.accountId===G.accountId)return;if(B.reboundFrom??=B.accountId,B.accountId=X.accountId,"data"in X)B.data=X.data;G.accountId=X.accountId},F0=(G)=>!G.attempt||G.endError!==void 0||G.status!==void 0&&G.status>=400,K0=(G)=>{let X=[...j.values()].filter((b)=>b.scope.sessionID===G),B=X.filter((b)=>b.limit&&!b.rerouted).at(-1);if(B)return B;let T=X.filter((b)=>b.scope.kind==="primary"),F=T.length>0?T:X;if(F.length<=1)return F[0];let D=F.filter((b)=>!b.judged&&F0(b)).at(-1);if(D)return D;let x=F.filter((b)=>b.attempt&&!b.ended);if(x.length>1)return"ambiguous";return x[0]??F.at(-1)},F2={providerID:z},H2=[];H2.push(await $.session.hook("model.request",(G)=>{if(Y)return;return J2(G2(G),async(X)=>{let B=await M2(G2(G),"model.request",X);if(X(),B.accountId===void 0)throw c(B.scope);v2(G.headers,{...B.headers,[C2]:B.id})})},F2)),H2.push(await $.session.hook("http.request",(G)=>{if(Y){if(!Y2(G2(G),G.request.headers))return}return J2(G2(G),async(X)=>{let B=G.request.headers.get(C2)??void 0,T=Y?await M2(G2(G),"http.request",X,"http"):await O(G2(G),"http.request","http",B,X);X();let F=o(T),D=T.attempt;if(!F||!D)throw c(T.scope);await d(T,async()=>{let x=G.request;if(Z.rewriteRequest){if(B!==void 0){let K2=new Headers(x.headers);K2.delete(C2),x=new Request(x,{headers:K2})}x=await Z.rewriteRequest({...F,request:x,attempt:D})??x,X()}let b=new Headers(x.headers);b.delete(C2),_0(b,T.headers),_2(T.scope,b.entries());let a=new Request(x,{headers:b});U.set(a,T),G.request=a})})},F2)),H2.push(await $.session.hook("http.response",async(G)=>{let X=U.get(G.request);if(!X){if(Y)return;if(!$2)$2=!0,K("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:G.sessionID,kind:G.kind});return}let B=G.response;if(Z.answeredBy&&X.attempt){let b=X.attempt,a=await d(X,async()=>Z.answeredBy?.({request:G.request,response:B,attempt:b}));if(a)N0(X,a)}let T=o(X),F=X.attempt;if(!T||!F)return;X.status=B.status;let D=Z.quotaFromHeaders?.(B.headers,B.status,F);if(D!==void 0)f1(X,"http",D,B.status);if(!B.ok&&Z.limitFromResponse){let b=await Z.limitFromResponse({status:B.status,headers:B.headers,body:()=>B.clone().text(),attempt:F});if(b)G1(X,b,"http")}if(!B.ok||!B.body)t(X);let x=B;if(B.body&&(Z.inspectEvent||Z.onAttemptEnd)){let b=B.body;if(Z.inspectEvent)b=b.pipeThrough(B1((a)=>I1(X,"http",a.data,a.event),(a)=>K("opencode2 auth event inspection threw",{error:A(a)})));x=new Response(L0(b,(a)=>t(X,a)),{status:B.status,statusText:B.statusText,headers:B.headers})}if(Z.rewriteResponse)x=await Z.rewriteResponse({...T,request:G.request,response:x,attempt:F})??x;if(x!==B)G.response=x},F2)),H2.push(await $.session.hook("experimental.ws.handshake",(G)=>{if(Y){let X=T2(G.sessionID,G.kind);if(_.delete(X),!Y2(G2(G),new Headers(G.headers)))return}return J2(G2(G),async(X)=>{let B;for(let x of Object.keys(G.headers)){if(x.toLowerCase()!==C2)continue;B??=G.headers[x],delete G.headers[x]}let T=Y?await M2(G2(G),"experimental.ws.handshake",X,"ws"):await O(G2(G),"experimental.ws.handshake","ws",B,X);X();let F=o(T),D=T.attempt;if(!F||!D)throw c(T.scope);await d(T,async()=>{if(!Y?.refuseMisplaced)v2(G.headers,T.headers);let x=Z.rewriteHandshakeURL?.({...F,url:G.url,attempt:D});if(x!==void 0)G.url=x;if(Y?.refuseMisplaced)v2(G.headers,T.headers);if(_2(T.scope,Object.entries(G.headers)),Y)_.add(T.key)})})},F2));let v1=Z.rewriteWebSocketFrame?.bind(Z);if(v1)H2.push(await $.session.hook("experimental.ws.send",async(G)=>{let X=G2(G);if(Y&&!_.has(T2(X.sessionID,X.kind)))return;let B=X2(X.sessionID,X.kind),T=await v1({...X,attempt:B?.attempt,frame:G.frame});if(T!==void 0)G.frame=T},F2));H2.push(await $.session.hook("experimental.ws.receive",(G)=>{if(Y&&!_.has(T2(G.sessionID,G.kind)))return;let X=X2(G.sessionID,G.kind);if(!X)return;try{I1(X,"ws",G.frame)}catch(B){K("opencode2 auth frame inspection threw",{error:A(B)})}},F2)),H2.push(await $.session.hook("retry",async(G)=>{if(Y&&w.get(G.sessionID)!==!0)return;let X=G.decision,B=()=>l("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});if(R(G.sessionID)){await B();return}let T=K0(G.sessionID);if(!T)return;if(T==="ambiguous"){await l("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let F=T;await J2(F.scope,async(D)=>{let x=D;if(R(G.sessionID)){await B();return}F.judged=!0;let b=F.attempt;if(b&&!F.outputStarted){if(!F.limit){let z2=Z.limitFromError?.(G.error,b);if(z2)G1(F,z2,"error")}if(F.ended)await F.ended;if(F.limit)await F.limit.delivered}x();let{decision:a,reason:K2}=await M(F.scope.sessionID,async()=>{if(x(),R(G.sessionID))return{decision:X,reason:"host-decides"};let z2=P.get(F.key);if(P.delete(F.key),z2?.next)await q(z2.next);if(x(),R(G.sessionID))return{decision:X,reason:"host-decides"};let r=X,j2,B2,e;if(F.accountId===void 0||!b)r={retry:!1},j2="no-account";else if(F.outputStarted)r={retry:!1},j2="output-started";else if(F.limit){let x2={accountId:F.accountId,limit:F.limit.signal},N2,Y1={...F.scope,phase:"retry",previousAccountId:F.accountId,rerouteFrom:x2};try{N2=await Z.chooseAccount(Y1)}catch(X1){K("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:F.scope.sessionID,error:A(X1)})}let P2=typeof N2==="object"?N2.hold:void 0,I2=typeof N2==="string"?N2:P2?F.accountId:void 0;if(I2!==void 0)e={accountId:I2,input:Y1};try{x()}catch(X1){if(e)await q(e);throw X1}if(R(G.sessionID)){if(e)await q(e);return{decision:X,reason:"host-decides"}}if(P2&&Number.isFinite(P2.delayMs)&&P2.delayMs>=0)r={retry:!0,delay:Math.min(P2.delayMs,p1)},j2="hold";else if(!P2&&I2!==void 0&&I2!==F.accountId)F.rerouted=!0,B2=x2,r={retry:!0,delay:0},j2="reroute";else{if(P2&&e)await q(e),e=void 0;j2="host-decides-last-account"}}else j2="host-decides";if(G.decision=r,r.retry&&F.accountId!==void 0&&j.has(F.id))P.set(F.key,{attemptId:F.id,sessionID:F.scope.sessionID,order:++S,accountId:F.accountId,...B2===void 0?{}:{rerouteFrom:B2},...e===void 0?{}:{next:e}});else if(e)await q(e);return{decision:r,reason:j2}});x(),await l("retry",{sessionID:G.sessionID,...F.accountId===void 0?{}:{accountId:F.accountId},kind:F.scope.kind,attempt:G.attempt,reason:K2,hostDecision:X,decision:a,...b===void 0?{}:{handle:b}})})},F2));let h1=(G)=>{if(s(G),w.delete(G),!i.get(G)?.foreignSeen)i.delete(G);for(let X of _)if(JSON.parse(X)[0]===G)_.delete(X);for(let X of[...j.values()]){if(X.scope.sessionID!==G)continue;p(X,"its session was forgotten"),j.delete(X.id)}for(let[X,B]of P)if(B.sessionID===G)m(X)},Q1=new AbortController,m1=$.event;if(m1)(async()=>{try{for await(let G of m1.subscribe({signal:Q1.signal}))if(G.type==="session.deleted")h1(G.data.sessionID);else if(G.type==="session.status"&&G.data.status.type==="idle"){let X=G.data.sessionID,B=++S;M(X,async()=>{for(let[T,F]of P)if(F.sessionID===X&&F.order<B){if(P.delete(T),F.next)await q(F.next)}})}}catch(G){if(!Q1.signal.aborted)K("opencode2 auth stopped listening for session deletion",{error:A(G)})}})();return{on(G,X){let B=g.get(G);if(!B)B=new Set,g.set(G,B);let T=X;return B.add(T),()=>{B.delete(T)}},accountFor(G,X){return v(T2(G,X))?.accountId},forgetSession:h1,get size(){return j.size},async dispose(){if(L)return;L=!0;for(let G of E.keys())s(G);Q1.abort();for(let G of j.values())p(G,"the installation was disposed");j.clear();for(let G of P.keys())m(G);_.clear(),w.clear(),i.clear(),g.clear(),await Promise.all(C.values()),await Promise.all(H2.map(async(G)=>{try{await G.dispose()}catch(X){K("opencode2 auth hook did not dispose cleanly",{error:A(X)})}}))}}}import{createHash as M0}from"node:crypto";var C0=1024,E0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),c1=($)=>d1($,"user"),O0=($)=>E0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function A0($){return M0("sha256").update(JSON.stringify($)).digest("hex")}class E2{runtime;maxSessions;#$=new Map;constructor($,Z=C0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let z=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],Q=Y.filter(c1),N=Y.findLastIndex(c1),H=N<0?void 0:A0(Y[N]),W=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,j,U,P;if(W)j=Q.length>0,U=H??z?.fingerprint,P=z?.userCount===void 0?void 0:z.userCount+Q.length;else{U=H,P=Q.length;let _=N>=0&&N>Y.findLastIndex(O0),w=z!==void 0&&!z.completed&&z.fingerprint===U&&z.userCount===P;j=_&&!w}let S=j||!z?{turnID:(J?.uuid??L2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:z.turnID,turnStartedAt:z.turnStartedAt};return this.#Z($,{...S,completed:!1,fingerprint:U,userCount:P}),S}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function U1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var i1=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function R0(){let $=globalThis;return $[i1]??=crypto.randomUUID(),$[i1]}class S2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??R0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new E2}get($){let Z=this.runtime?.uuid??L2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(h2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var W1={version:a1,"user-agent":n1,originator:"codex_exec"};var x0=1024,q0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,g2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),s1=($)=>g2($)&&($.type==="message"||("role"in $))&&$.role==="user",t1=($)=>g2($)&&$.type==="configuration_update";class H1{http;#$=new Map;constructor($=new S2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!o1.has(z))return!1;if(q0.test(z))return!1;let Y=g2($.reasoning)?$.reasoning:void 0,Q=typeof Y?.effort==="string"?Y.effort:void 0;if(!Q)return!1;let N=this.#$.get(Z.sessionID);if(N===void 0)return this.#Z(Z.sessionID,Q),!1;if(Q===N)return!1;let H=Array.isArray($.input)?$.input:void 0;if(!H||H.length===0)return!1;let W=H.findLastIndex(s1);if(W<0){if(J==="http")return!1;return $.reasoning={...Y,effort:N},!0}if($.reasoning={...Y,effort:N},!t1(H[W-1]))H.splice(W,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>x0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function h2($){try{let Z=JSON.parse($);return g2(Z)?Z:void 0}catch{return}}async function e1($,Z,J,z,Y=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Q=await $.clone().text(),N=h2(Q);if(N)delete N.max_output_tokens;let H=new Headers($.headers),W=m2({rewriteLite:r1,init:{body:N?JSON.stringify(N):$.body===null?void 0:Q},headers:H,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:z,applyEffort:(j)=>{J.apply(j,Z,"http")}});return new Request($,{headers:H,body:W.init?.body})}function $$($,Z,J,z){let Y=z.sessions.get($.sessionID),Q=z.frameTurns.get($.sessionID);if(!Y||!Q)return;let N=U1(Y,Q),H=new Headers({"content-type":"application/json"});for(let j of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let U=J.get(j);if(U!==null)H.set(j,U)}m2({init:{body:$.bodyText},headers:H,metadata:N,installationID:z.installationID,runtime:z.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let W=new URL(Z);if(W.protocol==="wss:")W.protocol="https:";if(W.protocol==="ws:")W.protocol="http:";return new Request(W,{method:"POST",headers:H,body:$.bodyText})}function S0($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((z,Y)=>JSON.stringify(z)!==JSON.stringify($[Y]));return J>=0&&t1(Z[J])&&s1(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function Z$($,Z,J){let z=h2($);if(z?.type!=="response.create")return;let Y=J.http.advanceFrame(Z.sessionID,z),Q=J.http.get(Z.sessionID);delete z.max_output_tokens;let N=m2({rewriteLite:()=>{},init:{body:JSON.stringify(z)},headers:new Headers,metadata:U1(Q,Y),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(W)=>{J.apply(W,Z,"ws")}}),H=h2(String(N.init?.body));if(!H)return;if(!S0(z.input,H.input)){if("input"in z)H.input=z.input;else delete H.input;return JSON.stringify(H)}return String(N.init?.body)}function b0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function N1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let z=new URL(`${b0(Z)}/responses`);if(z.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")z.protocol=z.protocol==="https:"?"wss:":"ws:";return z.href}import{resolve as J$}from"node:path";var k0=1024;class l2{accounts=new Map;limit;constructor($=k0){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var z$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),G$=globalThis,F1=G$[z$]??new Map;G$[z$]=F1;function K1($){let Z=JSON.stringify([J$($.configPath),J$($.statePath)]),J=F1.get(Z);if(!J)J=new l2,F1.set(Z,J);return J}var Q2="openai",D0=60000,P1=1,w0="request refused: no account with a usable credential",W2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function y0($){let Z=W2($)?$.counters:void 0,J=W2(Z)?Z.resetCredits:void 0,z=W2(J)?J.value:void 0;return typeof z==="number"&&Number.isFinite(z)?z:void 0}function L1($){try{return JSON.parse($)}catch{return}}function Q$($){let Z=p2($);return Z?c2(Z):void 0}var f0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function _1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function I0($,Z){let J=u2($);if(J){let Q=typeof $.status==="number"?$.status:void 0;return _1(J,Z,Q)}if($.type!=="response.failed"||!W2($.response))return;let z=$.response.failed;if(W2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let Y=$.response.error;if(W2(Y)){let Q=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(Q&&f0.has(Q))return{reason:Q}}return}function v0($,Z){let J=L1($);if(!W2(J))return;let z=typeof J.type==="string"?J.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:B$(J),complete:!0}};let Y=I0(J,Z);if(Y)return{limit:Y};if(z===void 0||z==="error")return;return A$(z)?void 0:{outputStarted:!0}}function h0($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:X$($),complete:j$($)}}function m0($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function R$($){let{source:Z,pins:J}=$,z=$.now??Date.now,Y=$.log,Q=$.vault,N=new H1($.codex),H=new Map,W=new Map,j=(V)=>`${V.sessionID}\x00${V.kind}\x00${V.accountId}`,U=new Map,P=$.sessionAccounts??new l2,S=new _$,_=(V,L,E)=>{let K=E?[]:O$(Z.peek().rows,V,L,Q?.identities()??new Set),A=(Q?.routes()??[]).filter((C)=>C.kind==="oauth"&&U$(b2(C.quota),V,L));return[...K.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota,row:C})),...A.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota}))]},w=(V,L,E)=>{let K=P$(V,L,E),A=V.map((q)=>({id:q.id,kind:"oauth",...Y$(q.quota)?{quota:q.quota}:{}})),C=V.flatMap((q)=>q.row?[q.row]:[]),M=new Set(V.filter((q)=>!q.row).map((q)=>q.id)),h=Z.rateLimitMarks(C);for(let q of M){let m=U.get(q);if(m===void 0)continue;if(m<=E)U.delete(q);else h.set(q,m)}return{rows:A,now:E,rateLimitMarks:h,refreshBackoff:Z.refreshBackoffFor(C),killswitch:K,requestPull:(q)=>M.has(q)?Q?.requestReading(q):Z.requestReading(q)}},i=(V,L,E,K,A)=>{let C=M$({...V,placement:T$(L),mainId:A});if(C.kind==="block"){Y?.debug("pool admission refused the request",{reason:C.block.reason});return}let M=C.order.filter((h)=>!E.has(h));if(K!==void 0&&M.includes(K))return K;return M[0]},R=(V,L,E,K,A,C,M)=>{let h=new Map(L.map((v)=>[v.id,v.quota])),q={requestBytes:P1,reservePercent:(v)=>W$(E,v===F$?void 0:v),resetCredits:(v)=>y0(h.get(v))},m=T1(V),l=(v,f)=>d2(M,{sessionId:K,requestBytes:P1,validPinnedAccountIds:V.rows.map((I)=>I.id).filter((I)=>!m.excluded.has(I)),excludeAccountIds:v,quotaCheckedAtByAccount:Object.fromEntries(V.rows.map((I)=>[I.id,m.projections.get(I.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(L.map((I)=>[I.id,I.identity])),select:(I)=>C$(V,q,new Set(v),I),persist:f},(I,o)=>M.set(I,o)),u=[...A],t=l(u,C);if(!t)return;let p=t.accountId,n=E$(V,q,p);if(n.kind==="none")return;if(n.kind==="move"){let v=l([...u,p],C);if(v)return v.accountId;return n.reason==="killswitch"?void 0:p}if(n.kind==="detour")return l([...u,p],!1)?.accountId;return p},$2={providerID:Q2,dropChoice(V){let L=j(V);W.get(L)?.drop(),W.delete(L),H.delete(L)},chooseAccount:async(V)=>{let L=await Q?.authority(),E=await $.storage(),K=L!==void 0&&L!=="local",A=()=>{throw new Z2({kind:"no-account",providerID:Q2,sessionID:V.sessionID,requestKind:V.kind,message:i2})};if(K)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())A();Y?.warn("the account pool does not serve requests yet; refusing the request",{kind:V.kind});return}await Z.prepareTokens(Z.peek().rows,E)}let C=z(),M=_(E,C,K),h=L$(w(M.filter((I)=>I.id!==V.rerouteFrom?.accountId),E,C));if(h)await h,C=z(),M=_(E,C,K);let q=new Map(M.map((I)=>[I.id,I])),m=w(M,E,C),l=new Set(V.rerouteFrom?[V.rerouteFrom.accountId]:[]),u=E?.routing?.mode??"main-first",t=V.kind==="primary",p=new Set,n,v,f;try{for(;;){let I=new Set([...l,...p]);if(f=void 0,n=void 0,u==="sticky-balanced"){let c=new Map(J.placementSnapshot(V.sessionID)),s=c.get(V.sessionID);if(f=R(m,M,E,V.sessionID,I,t&&p.size===0,c),f!==void 0&&c.get(V.sessionID)!==s)n=c.get(V.sessionID)}if(f??=i(m,u,I,t?void 0:P.activeAccount(V.sessionID),K?u==="sticky-balanced"?null:K$(Q?.routes()??[]):void 0),f===void 0||p.has(f)){if(l.size>0){let c=new Map(m.rateLimitMarks);for(let s of l)c.delete(s);m={...m,rateLimitMarks:c},l.clear();continue}f=void 0;break}if(t&&u==="sticky-balanced"){let c=T1(m).projections.get(f)?.checkedAt,s=q.get(f)?.identity;v=J.reserve(V.sessionID,{accountId:f,inputBytes:P1,...c!==void 0?{quotaCheckedAt:c}:{},...s!==void 0?{wireIdentity:s}:{}})}let o=q.get(f)?.row;if(o){if(Z.usableToken(o)!==void 0)break;Y?.debug("pool row holds no usable token; choosing again",{accountId:f})}else{if(!Q)break;let c=await Q.authorize(f);if(c){H.set(j({...V,accountId:f}),c);break}Y?.debug("the vault refused to serve an account; choosing again",{accountId:f})}if(v)J.rollback(v);v=void 0,p.add(f)}if(f===void 0&&!K&&M.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(f===void 0&&K&&Q&&(M.length===0||p.size>0)){let I=p.size>0?"vault-refused":N$(Q);throw Y?.warn("vault mode: no vault account can serve; refusing the request",{cause:I}),new Z2({kind:"no-account",providerID:Q2,sessionID:V.sessionID,requestKind:V.kind,message:H$(I,Q.name)})}if(f!==void 0){let I=f,o=v,c=n,s=()=>{if(o)J.finish(o,c);if(t)P.record(V.sessionID,I),$.onRoute?.(V.sessionID,I,u)};if(V.phase==="retry")W.set(j({...V,accountId:f}),{commit:s,drop:()=>{if(o)J.rollback(o)}}),v=void 0;else s();let J2=Y?.info;S.served(m,f,Y&&J2?{info:(_2,R2)=>J2.call(Y,_2,R2)}:void 0)}return Y?.debug("pool account chosen",{kind:V.kind,accountId:f,mode:u,...V.rerouteFrom?{rerouteFrom:V.rerouteFrom.accountId}:{}}),f}finally{if(v)J.rollback(v)}},accountHeaders:async(V)=>{let{accountId:L}=V,E=j(V),K=W.get(E);W.delete(E);let A=()=>{K?.commit()};try{let C=()=>new Z2({kind:"no-account",providerID:Q2,sessionID:V.sessionID,requestKind:V.kind,message:w0}),M=Q&&await Q.authority()!=="local"?void 0:Z.peek().rows.find((m)=>m.id===L);if(!M&&Q){let m=j(V),l=H.get(m)??await Q.authorize(L);if(H.delete(m),!l)throw Y?.warn("the vault refused to serve an account; refusing the request",{accountId:L}),C();return A(),{headers:{...W1,"session-id":V.sessionID,authorization:`Bearer ${l.accessToken}`,"chatgpt-account-id":l.accountIdentity??Q$(l.accessToken)??null},attempt:{kind:"vault",routeId:L,receipt:l}}}let h=M?Z.usableToken(M):void 0;if(!M||!h)throw Y?.warn("pool row holds no usable token; refusing the request",{accountId:L}),C();let q=M.identity??Q$(h);return A(),{headers:{...W1,"session-id":V.sessionID,authorization:`Bearer ${h}`,"chatgpt-account-id":q??null},attempt:{kind:"pool",token:h,credentialEpoch:M.credentialEpoch}}}finally{K?.drop()}},async rewriteRequest({request:V,sessionID:L,kind:E}){let K=$.codexEndpoint?N1(V.url,$.codexEndpoint()):V.url,A=K===V.url?V:new Request(K,V);return await e1(A,{sessionID:L,kind:E},N,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:V})=>$.codexEndpoint?N1(V,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:V,sessionID:L,kind:E})=>Z$(V,{sessionID:L,kind:E},N),quotaFromHeaders:(V)=>h0(V),async limitFromResponse({status:V,headers:L,body:E}){if(V<400)return;let K=L1(await E().catch(()=>"")),A=u2({...W2(K)?K:{},status:V});if(!A)return;let C=z(),M=_1(A,C,V);if(M.retryAfterMs!==void 0)return M;let h=m0(L);return h===void 0?M:{...M,retryAfterMs:h}},inspectEvent:({data:V})=>v0(V,z()),limitFromError(V){let L=L1(V.message),E=u2({...W2(L)?L:{},...V.status!==void 0?{status:V.status}:{}})??(V.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return E?_1(E,z(),V.status):void 0},async onAttemptEnd(V,L){let E=V.data;if(E?.kind!=="vault"||L.status!==401)return;Y?.warn("a vault account answered 401; reporting it to the vault",{accountId:V.accountId}),await Q?.reportFailure(E.receipt,401)}},k=(V,L,E)=>{let K=E.data;if(K?.kind==="vault"){Q?.recordSnapshot(V,L.snapshot,L.complete,K.receipt);return}if(K?.kind!=="pool")return;if(Z.peek().rows.find((C)=>C.id===V)?.credentialEpoch!==K.credentialEpoch){Y?.debug("quota reading dropped: the row holds another credential",{accountId:V});return}Z.recordSnapshot(V,L.snapshot,K.token,L.complete)},g=(V,L,E)=>{let K=z(),A=E.data?.kind==="vault",C=A?Q?.routes().find((q)=>q.id===V)?.quota:Z.peek().rows.find((q)=>q.id===V)?.quota,M=V$(b2(C),L.reason,K,D0,L.retryAfterMs!==void 0?K+L.retryAfterMs:void 0);if(!A){Z.markRateLimited(V,M);return}let h=U.get(V);if(h===void 0||h<M)U.set(V,M)};return{adapter:$2,attach(V){V.on("quota",(L)=>k(L.accountId,L.quota,L.handle)),V.on("limit",(L)=>{g(L.accountId,L.limit,L.handle),Y?.debug("pool row refused the request",{accountId:L.accountId,via:L.via,reason:L.limit.reason,outputStarted:L.outputStarted})})},forgetSession(V){J.forget(V),P.forget(V),N.forget(V)},activeAccount:(V)=>P.activeAccount(V)}}import{resolve as D$}from"node:path";import{Buffer as g0}from"node:buffer";import{resolve as x$}from"node:path";function k2($){return g0.byteLength(JSON.stringify($))}function l0($){return $.reduce((Z,J)=>Z+k2(J),0)}function M1($,Z){return 2+$+Math.max(0,Z-1)}function u0($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+M1(Z.inputBytes,Z.input.length)+1:0)+(J?20+M1(J.inputBytes,J.input.length)+10+M1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function q$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class S${enabled;caps=a2;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let J=q$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let z=J.previous_response_id,Y=this.entries.get($),Q=Y?.head;if(z&&z!==Q?.responseID){this.forget($);return}let{type:N,previous_response_id:H,input:W,...j}=J;this.keep($,{fields:z&&Y?Y.fields:j,fieldsBytes:z&&Y?Y.fieldsBytes:k2(j),...z&&Q?{head:Q}:{},pending:{input:W,inputBytes:l0(W),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let z=this.entries.get($);if(!z?.pending)return;let Y=q$(Z);if(!Y)return;let Q=z.pending,N=Y.response;if(Y.type==="response.created"&&typeof N?.id==="string")Q.responseID=N.id,Q.responseIDBytes=k2(N.id),this.keep($,z);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&Q.responseID!==void 0&&Y.response_id!==Q.responseID)return;Q.output.push(Y.item),Q.outputBytes+=k2(Y.item),this.keep($,z)}else if(Y.type==="response.completed"&&typeof N?.id==="string"){if(N.id===z.head?.responseID||Q.responseID!==void 0&&N.id!==Q.responseID)return;let H={responseID:N.id,responseIDBytes:Q.responseID===N.id?Q.responseIDBytes:k2(N.id),input:[...z.head?.input??[],...Q.input,...Q.output],inputBytes:(z.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},W={...z,head:H,pending:void 0};if(!this.keep($,W))return;J?.({sessionID:$,responseID:H.responseID,bodyText:this.body(z.fields,H)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=u0(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let z=this.entries.keys().next().value;if(z===void 0)break;this.forget(z)}return this.entries.has($)}}var b$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),k$=globalThis,C1=k$[b$]??new Map;k$[b$]=C1;function n2($){let Z=JSON.stringify([x$($.configPath),x$($.statePath)]),J=C1.get(Z);if(!J)J=new S$,C1.set(Z,J);return J}var p0=5000,c0=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],d0=["x-opencode-parent-session-id","x-parent-session-id"];function I$($){let Z=w$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:y$($?{...$,cachekeep:Z}:$)}}var v$=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),h$=globalThis,D2=h$[v$]??new Map;h$[v$]=D2;function i0($,Z){let J=[],z=()=>J.at(-1)?.location,Y=()=>{let W=z();if(!W)throw Error("no location holds keep-warm");return W},Q=(W,j)=>{H.remove(W),z()?.log?.debug(`cachekeep dropped target (${j})`,{sessionKey:W})},N=async(W)=>{if(W.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let j=W.accountId??"main",U=Y(),P=await U.source.accessFor(j,await U.storage());if(!P)throw Error(`pool row ${j} has no usable token`);return{token:P.token,identity:P.row.identity}},H=f$({...a2,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(W,j)=>Y().fetch(W,j),logger:{debug:(W,j)=>z()?.log?.debug(W,j),warn:(W,j)=>z()?.log?.warn(W,j)},getWindow:()=>z()?.settings().window,getSustain:()=>z()?.settings().sustain===!0,resolveLocal:N,vault:{owns:(W)=>z()?.vault.owns(W)===!0,authority:()=>Y().vault.authority(),send:async(W,j,U)=>{let P=Y();if(await P.vault.authority()!=="vault")return;return P.vault.send(W,j,U)}},activeAccount:(W)=>{if(W===void 0)throw Error("target has no session");let j=z(),U=j?.settings();if(!j||!U?.enabled){Q(W,"keep-warm is off");return}if(!U.subagents&&H.status().targets.some((S)=>S.sessionKey===W&&S.isSubagent)){Q(W,"subagent warming is off");return}let P=j.accounts.activeAccount(W);if(P===void 0){Q(W,"no account recorded for the session");return}return P},verifyCredential:({target:W,mode:j,identity:U})=>{if(W.meta.credentialMode!==j)throw Error(`a target captured in ${W.meta.credentialMode??"an unknown"} mode is not warmed with a ${j} credential`);if(U!==W.meta.chatgptAccountId)throw Q(W.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:H,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??p0}}function a0($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function n0($){let Z={};for(let J of c0){let z=$.get(J);if(z)Z[J]=z}return Z}function m$($,Z,J){let z=JSON.stringify([D$($.configPath),D$($.statePath)]),Y=D2.get(z);if(!Y)Y=i0(J,Z.settings()),D2.set(z,Y);let Q=Y,N=n2($);N.setEnabled(Q.settings.enabled);let H={location:{...Z,settings:()=>Q.settings}};Q.holders.push(H);let W=!1,j=async(U)=>{try{let P=H.location.settings();if(W||!P.enabled)return;if(U.kind!=="primary"){if(U.kind==="generate"&&a0(await U.request.clone().text())){if(W)return;Q.manager.remove(U.sessionID)}return}let S=U.attempt.data,_=S?.kind==="pool"?"local":S?.kind==="vault"?"vault":void 0;if(!_)return;let w=U.request.headers,i=d0.some((Y2)=>w.has(Y2))||Z.parentOf!==void 0&&await Z.parentOf(U.sessionID)!==void 0;if(i&&!P.subagents)return;let R=await U.request.clone().text();if(W)return;let y=w.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:U.sessionID,bodyText:R,accountId:U.attempt.accountId,isSubagent:i,meta:{replayHeaders:n0(w),...y?{chatgptAccountId:y}:{},routingSessionId:U.sessionID,url:U.request.url,credentialMode:_}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:Q.manager,configure:(U)=>{Object.assign(Q.settings,U),N.setEnabled(Q.settings.enabled)},capture:j,forget:(U)=>Q.manager.remove(U),async release(){if(W)return;W=!0;let U=Q.holders.indexOf(H);if(U>=0)Q.holders.splice(U,1);if(Q.holders.length>0)return;if(D2.get(z)===Q)D2.delete(z);Q.manager.stop();let P;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((S)=>{P=setTimeout(S,Q.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as o0}from"node:fs";import{dirname as r0,resolve as s0}from"node:path";function t0(){return g$("opencode2")}var e0=2000;class d${path;options;sessions;frameTurns=new E2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=p$($,Z.uuid??L2)}get($,Z=L2){let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}:0`},this.sessions.set($,J),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return J}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??e0),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=E1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((z)=>{let Y=this.sessions.get(z);return Y?[[z,Y]]:[]}),Z=[...this.#Z],J=null;try{if(o0(r0(this.path),{recursive:!0}),J=await this.#B(),!J)return;let z;try{z=E1(this.path)}catch{z=new Map}await this.options.afterRead?.();let Y=!1;for(let Q of Z)if(z.delete(Q))Y=!0;for(let[Q,N]of $){if(z.get(Q)===N.threadID)continue;z.set(Q,N.threadID),Y=!0}if(Y)c$(this.path,z)}catch{return}finally{await J?.release().catch(()=>{})}for(let[z,Y]of $)if(this.sessions.get(z)===Y)this.#$.delete(z);for(let z of Z)if(!this.sessions.has(z))this.#Z.delete(z)}#B(){return u$(this.path,this.options.lockWaitMs??l$)}}var i$=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),a$=globalThis,o2=a$[i$]??new Map;a$[i$]=o2;function $4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function n$($=t0()){let Z=s0($),J=o2,z=o2.get(Z),Y=o2;if(z!==void 0&&!$4(z))J.compatible??=new Map,Y=J.compatible;let Q=Y.get(Z);if(!Q)Q=new d$(Z),Y.set(Z,Q);let N=Q;return N.frameTurns??=new E2,Q}var O1=Symbol.for("cortexkit.openai-auth.v2.commands"),Z4=U2("v2-command");function r2($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function A1($){Z4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function J4(){let $=globalThis;return $[O1]??={locations:new Map},$[O1].locations??=new Map,$[O1]}async function ZZ($,Z){let J=J4(),z=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},Q=await r$(z),N=await o$(e$,Q.dir,()=>$Z({...Q,drain:t$,apply:(P)=>{let S=J.locations.get(z);if(!r2(S))throw Error("The OpenAI menu location was closed");return S.menu.apply(P)}})),H=J.locations.get(z);if(J.locations.set(z,Y),r2(H))H.closed.abort(),await H.registration?.dispose();let W={name:"openai",description:"OpenAI account menu",async execute(P){let S=[...J.locations.values()].find(r2)?.session;if(!S)return A1("no live location");let _=await S.get({sessionID:P.sessionID}),w=J.locations.get(_.location.directory);if(!r2(w))return A1("location closed");let i=await s$(P.sessionID,w.closed.signal);if(!i||J.locations.get(_.location.directory)!==w){if(!i&&!w.closed.signal.aborted)R1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return A1(w.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let R=await w.menu.open(P.sessionID);R1(R,P.sessionID)}};J.command??=W,J.command.execute=W.execute;let j=J.command;try{Y.registration=await $.command.transform((P)=>{P.add(j)})}catch(P){if(Y.closed.abort(),J.locations.get(z)===Y)J.locations.delete(z);throw await N.release(),P}let U=!1;return async()=>{if(U)return;if(U=!0,Y.closed.abort(),J.locations.get(z)===Y)J.locations.delete(z);await N.release(),await Y.registration?.dispose()}}var z4="openai-auth-pool-browser",G4="openai-auth-pool-headless",Q4="openai-auth-vault",Y4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function w2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function XZ($){return{method:{id:Q4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await JZ($.paths,$.name)!=="vault")throw Error(Y4)}}}function jZ($){let Z=(J,z,Y)=>({method:{id:J,type:"oauth",label:z},async authorize(){if($.vault)await w2($.vault);let Q=await $.beginLogin({version:$.version,headless:Y});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(z4,"ChatGPT (openai-auth pool, browser)",!1),Z(G4,"ChatGPT (openai-auth pool, headless)",!0)]}function x1($){let Z=(J)=>typeof J==="string"?J:"";return q2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===QZ||zZ($)}function X4($){if($.accountId)return $.accountId;let Z=$.access?p2($.access):void 0;return Z?c2(Z):void 0}async function BZ($,Z,J,z={}){if(z.vault)await w2(z.vault);if(x1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=GZ($,{rowLocks:(_)=>YZ(Z,_)}),Q=await Y.read();if(Q.status!=="ready")throw Error(`the account pool cannot be read (${Q.status}); the login was not stored`);let N={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},H=X4(J);if(z.vault)await w2(z.vault);let W=H!==void 0?{identity:H}:{};if(z.origin==="import"){let _=Q.rows.find((w)=>H!==void 0&&w.identity===H||w.credential?.type==="oauth"&&w.credential.refresh===J.refresh);if(_)return{id:_.id,operation:"kept"}}let j=Q.rows.filter((_)=>_.type==="oauth"&&!_.invalid),U=H?j.find((_)=>_.identity===H):void 0,P=Q.rows.find((_)=>_.id===s2);if(U)return{id:(await Y.replace(U.id,N,W)).id,operation:"replaced"};if(!P){let _=await Y.add({id:s2,credential:N,...W,...J.label!==void 0?{label:J.label}:{}});return{id:_.id,operation:_.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await Y.replace(s2,N,W)).id,operation:"replaced"};let S=await Y.add({id:J.id,credential:N,...W,...J.label!==void 0?{label:J.label}:{}});return{id:S.id,operation:S.outcome==="added-disabled"?"added-disabled":S.outcome==="rotated"?"replaced":"added"}}function j4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function WZ($){let Z={...$,allowAction:j4,unavailableSections:[]};return{open:(J)=>VZ(Z,J),apply:(J)=>{let z=J!==null&&typeof J==="object"?J:{},Y=z.values&&typeof z.values==="object"&&!Array.isArray(z.values)?Object.fromEntries(Object.entries(z.values).filter(([,Q])=>Q===null||["string","number","boolean"].includes(typeof Q))):void 0;return UZ(Z,{command:"openai",sectionId:typeof z.sectionId==="string"?z.sectionId:"",actionId:typeof z.actionId==="string"?z.actionId:"",...Y?{values:Y}:{},...z.confirmed===!0?{confirmed:!0}:{},...typeof z.itemId==="string"?{itemId:z.itemId}:{},...typeof z.sessionId==="string"?{sessionId:z.sessionId}:{}})}}}function B4($,Z){if(!HZ($.modelID??$.id)){$.enabled=!1;return}let J=NZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((z)=>[z.id,z])).values()]}function KZ($){return $.model.transform((Z)=>{let J=Z.list(Q2);for(let z of J){let Y=FZ(String(z.id)),Q=Y?J.find((N)=>String(N.id)===Y):void 0;Z.update(Q2,String(z.id),(N)=>B4(N,Q?.variants?.map((H)=>({...H,id:String(H.id)}))))}})}class q1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!PZ())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let z=this.pending.keys().next().value;if(z)this.take(z)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>t2({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),z=J&&this.take(J);if(!z)return;let{reason:Y,message:Q}=Z.error,N=Q?`${Y}: ${Q}`:Y;await this.safely(()=>t2({...z,error:e2(N,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>t2({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class S1{counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function CZ($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let z=await TZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,z),LZ(z,$.now(),!0)}}function EZ($){let{source:Z,counts:J,now:z}=$,Y=async(j)=>{let U=await Z.rowAccess(j,await $.storage());if(!U?.row)throw new _Z("unknown_account",`${j==="main"?"Main":"Fallback"} account ${j} was not found.`);return MZ(j,U)},Q=async(j)=>{if($.authority&&await $.authority()!=="local")return{account:j,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[U]=await Z.pollRows(await $.storage(),{ids:[j]});if(!U)return{account:j,ok:!1,error:"targeted quota refresh returned no result"};return{account:U.id,ok:U.ok,...U.error!==void 0?{error:U.error}:{}}},N=(j)=>Z.peek().rows.find((U)=>U.id===j),H=(j)=>{let U=N(j);if(!U)return null;let P=b2(U.quota)??{},S=J.applicable(U),_=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((w)=>typeof w==="number"));return{quota:{...P,...S!==void 0?{resetCreditsApplicable:S}:{}},checkedAt:_,refreshAfter:_,...U.identity!==void 0?{accountId:U.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(j)=>{let U=N(j);if(!U)return!1;let P=Z.rateLimitMarks([U]).get(U.id);return P!==void 0&&P>z()},getMain:()=>H("main"),getFallback:(j)=>H(j)}}}import{resolve as OZ}from"node:path";var V4=1024;class b1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=V4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return d2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var AZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),RZ=globalThis,$1=RZ[AZ]??new Map;RZ[AZ]=$1;function U4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function xZ($){let Z=JSON.stringify([OZ($.configPath),OZ($.statePath)]),J=$1,z=$1.get(Z);if(z!==void 0&&!U4(z)){let Q=$1;Q.compatibleV1??=new Map,J=Q.compatibleV1}let Y=J.get(Z);if(!Y)Y=new b1,J.set(Z,Y);return Y}import{statSync as W4}from"node:fs";import{resolve as H4}from"node:path";function IZ($){return $.map((Z)=>{try{let J=W4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function k1($){return IZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function qZ($){return IZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+k1($)}class vZ{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:qZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let z=new Set;J={producers:z,stop:$.pins.subscribe((Y,Q)=>{let N=z.values().next().value;if(N)this.publish(N,{sessionId:Y,pin:Q,accountId:Q?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let z of this.producers){let Y={stamp:qZ(z),roster:z.vault.snapshot()},Q=this.observations.get(z);if(Y.stamp!==Q?.stamp||Y.roster!==Q?.roster)this.observations.set(z,Y),this.publish(z)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;let z=await $.vault.authority()!=="local",Y=k1($),Q=()=>this.producers.has($)&&$.vault.enrolled()===z&&k1($)===Y,N=await(z?f2($.paths):O2($.paths)),H=z?yZ($.vault.snapshot()?.rows,new Set($.vault.routes().map((j)=>j.id)),N,Date.now()):fZ((await $.source.sidebarView()).rows,N,Date.now());if(await bZ(H,this.file,{canWrite:Q}),!Q()||!Z)return;let W=H.vaultAccounts??H.fallbacks;if(Z.accountId===void 0){await DZ(Z.sessionId,W,this.file,{canWrite:Q});return}if(Z.pin){let j=Date.now();await wZ({sessionId:Z.sessionId,assignment:{accountId:Z.pin.accountId,wireAccountId:Z.pin.wireIdentity,inputBytes:Z.pin.inputBytes??0,quotaCheckedAt:Z.pin.quotaCheckedAt,assignedAt:j,lastSeenAt:j},validPinnedAccountIds:[...z?[]:["main"],...W.filter((U)=>U.enabled).map((U)=>U.id)]},this.file)}await kZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??H.route,updatedAt:Date.now()},W,this.file,{canWrite:Q})}).catch(()=>{U2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var hZ=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),mZ=globalThis,y2=mZ[hZ]??new Map;mZ[hZ]=y2;function gZ($,Z=SZ(),J=2000){let z=H4(Z),Y=y2.get(z);if(!Y)Y=new vZ(z,J),y2.set(z,Y);let Q=Y,N=Q.add($),H=!1;for(let[W,j]of $.pins.snapshot())Q.publish($,{sessionId:W,pin:j,accountId:j.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(W,j,U)=>{Q.publish($,{sessionId:W,accountId:j,route:U})},async release(){if(H)return;if(H=!0,N(),await Q.settled(),Q.empty&&y2.get(z)===Q)y2.delete(z)}}}var z1="cortexkit-openai-auth",K4=5000;async function lZ($,Z,J,z=new S2,Y,Q,N){let H=new q1(J),W=new N4,j=new Map,U=new Map,P=(R)=>{U.delete(R);for(let y of j.keys())if(y.startsWith(`${R}:`))j.delete(y)},S=(R)=>{N?.(R.sessionID),Q?.send(R.sessionID,R.frame)},w=await V1({session:{hook:(R,y,Y2)=>$.session.hook(R,async($2)=>{let k=R==="http.request"?$2:void 0,g=R==="experimental.ws.handshake"?$2:void 0,L=(k?k.request.headers:g?new Headers(g.headers):void 0)?.get("authorization")===`Bearer ${V2(Z.providerID)}`,E={};if(g)j.delete(`${g.sessionID}:${g.kind}`);try{await W.run(E,()=>y($2))}catch(K){if(L&&!(K instanceof Z2))throw aZ(K);throw K}if(k&&L&&E.attempt){let K=k.request.headers.get("thread-id");if(K)k.request.headers.set("session-id",K)}if(k&&L&&E.attempt)await H.captureHttp(k.request,E.attempt);if(k&&L&&E.attempt)await Y?.({sessionID:k.sessionID,kind:k.kind,request:k.request,attempt:E.attempt});if(g&&L&&E.attempt)g.headers["session-id"]=z.get(g.sessionID).threadID;if(R==="experimental.ws.send"){let K=$2,A=j.get(`${K.sessionID}:${K.kind}`);if(A)await H.frame(K.frame,A.attempt);if(A&&K.kind==="primary")S(K)}if(k||g){let K=k??g;if(!K)return;let C=(k?k.request.headers:new Headers(K.headers)).get("authorization")?.replace(/^Bearer /,"");if(L&&C)U.set(K.sessionID,C);else U.delete(K.sessionID);if(g){let M=`${g.sessionID}:${g.kind}`;if(L&&C&&E.attempt)j.set(M,{bearer:C,attempt:E.attempt,url:g.url,headers:new Headers(Object.entries(g.headers).filter(([h])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(h.toLowerCase())))});else j.delete(M)}if(U.size>512){let M=U.keys().next().value;if(M)U.delete(M)}if(j.size>512){let M=j.keys().next().value;if(M)j.delete(M)}}else if(R==="experimental.ws.receive"){let K=$2,A=j.get(`${K.sessionID}:${K.kind}`);if(A){if(z.frameReceived(K.sessionID,K.frame),K.kind==="primary"){let C;if(Q?.receive(K.sessionID,K.frame,(M)=>{C=M}),C)try{let M=$$(C,A.url,A.headers,z);if(M)await Y?.({sessionID:K.sessionID,kind:"primary",request:M,attempt:A.attempt})}catch(M){J.warn("cachekeep WebSocket capture failed",{error:M instanceof Error?M.message:String(M)})}}K.frame=nZ(K.frame,A.bearer)}}else if(R==="retry"){let K=$2,A=U.get(K.sessionID);if(A)Object.assign(K.error,{message:e2(K.error.message,A)})}},Y2)},event:{subscribe:(R)=>async function*(){for await(let y of $.event.subscribe(R)){if(y.type==="session.deleted")P(y.data.sessionID);yield y}}()}},{...Z,rewriteRequest:async(R)=>{let y=W.getStore();if(y)y.attempt=R.attempt;return Z.rewriteRequest?.(R)},rewriteHandshakeURL:(R)=>{let y=W.getStore();if(y)y.attempt=R.attempt;return Z.rewriteHandshakeURL?.(R)},onAttemptEnd:async(R,y)=>{await H.end(R,y),await Z.onAttemptEnd?.(R,y)},rewriteResponse:async(R)=>{await H.response(R.request,R.response.status);let y=await Z.rewriteResponse?.(R)??R.response;return oZ(y,R.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(R)=>{let y=R.get("authorization");return y?.startsWith("Bearer ")?y.slice(7):void 0}},logger:{warn:(R,y)=>J.warn(R,{data:y})}}),i=w.dispose;return{...w,dispose:async()=>{U.clear(),j.clear(),await i(),await H.settle(),H.clear()}}}function y1($={}){return{id:z1,setup:(Z)=>P4(Z,$)}}async function P4($,Z={}){let J2=[];try{let J=U2("opencode2");let z=U2("quota");let Y=Z.version??sZ;await B0({version:Y,...Z.runtimeLayout});let Q=Z.paths??(()=>eZ(rZ()));let N=await f2(Q());let H=N?.logging?.level;if(H&&typeof H==="string")pZ(H);let W=Z.fetch??fetch;let j=Z.now??Date.now;let U=Z.poolMigration??U0;if(!U&&!A2(Q().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let O=(X2)=>{throw new Z2({kind:"no-account",providerID:Q2,sessionID:X2.sessionID,requestKind:X2.kind,message:i2})},d=await lZ($,{providerID:Q2,chooseAccount:O,accountHeaders:O},J);return()=>d.dispose()}let P=Z.vault?.firstRosterWaitMs??G0;let S=V0({host:"opencode",stateDir:Z.vault?.stateDir??iZ(Q().statePath),reservedRouteIds:()=>k.peek().rows.map((O)=>O.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>W},Q());let _=S.vault;let w=async()=>await _.authority()==="local"?O2(Q()):f2(Q());let i=!1;let R=!1;const y=Z1(J2,{[Symbol.dispose](){if(!i)S.release()}},0);await _.authority();let Y2=S.firstRoster;let $2=new S1;let k=new Q0({paths:Q,refreshProvider:async(O)=>{let d=await dZ({refreshToken:O.refresh,fetchImpl:W,now:j}),X2=cZ({id_token:"",access_token:d.access,refresh_token:d.refresh});return{...d,...X2?{identity:X2}:{}}},pullQuota:CZ({fetchImpl:W,now:j,counts:$2,logger:z}),now:j,vaultIdentities:()=>_.identities(),vaultMode:()=>_.enrolled(),vaultAuthority:()=>_.authority(),vaultFirstRoster:Y2,vaultFirstRosterBackgroundWaitMs:P,log:U2("pool")});if(await _.authority()==="local")await k.load();let g=Z.heartbeat===!1?void 0:await X0({version:Y,logger:U2("heartbeat")});let V=Z.fence??(()=>tZ({currentVersion:Y}));let L=Z.slot??W0();let E=async()=>$0(Q(),await L.get({path:{id:"openai"}}));let K=!1;let A=U?Y0({paths:Q,slot:L,version:Y,fence:V,runDeps:{vaultServes:()=>_.serves()},paused:async()=>await _.authority()!=="local",migrate:async(O)=>{let d=await Z0(O);if(K=d.status==="refused",!R)await k.load();return d},adopt:async(O)=>{if(R)return{status:"retry",reason:"unsettled"};if(!await w1(Y2,P))return{status:"retry",reason:"vault-roster-pending"};if(R)return{status:"retry",reason:"unsettled"};let d=await J0(O);if(!R)await k.load();return d}}):void 0;A?.start();S.start();let C=xZ(Q());let M=gZ({paths:Q(),source:k,pins:C,vault:_},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const h=Z1(J2,{[Symbol.dispose](){if(!i)M.release()}},0);M.publish();let q=Z.codex??new S2(void 0,void 0,n$());let m=I$(N);let l=n2(Q());let u=m$(Q(),{source:k,storage:w,vault:_,accounts:K1(Q()),settings:()=>m,parentOf:async(O)=>(await $.session.get({sessionID:O}))?.parentID??void 0,fetch:W,log:U2("cachekeep")},{now:j,codexResponsesUrl:J1().codexApiEndpoint,...Z.cacheKeep});const t=Z1(J2,{[Symbol.dispose](){if(!i)u.release()}},0);let p=R$({codex:q,onRoute:M.route,source:k,slotPlaceholderWithoutMain:E,storage:w,pins:C,sessionAccounts:K1(Q()),vault:_,awaitVaultRoster:async()=>{await w1(_.awaitRequestRoster(),z0)},responsesLite:()=>J1().responsesLite,codexEndpoint:()=>J1().codexApiEndpoint,now:j,log:J});let n=await lZ($,p.adapter,J,q,(O)=>u.capture(O),l,(O)=>u.forget(O));p.attach(n);let v=async(O)=>{if(await w2(_),A2(Q().configPath))return;if(await A?.idle(),A2(Q().configPath))return;if(K&&!x1(O)&&(await V()).open){await k.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let f=async(O)=>{await v(O);let d=await BZ(k.poolStore(),Q(),O,{vault:_});if(!A2(Q().configPath))await A?.requestAdoption();await k.load(),J.info("ChatGPT login stored in the account pool",d)};let I=await j1($,{integrationID:Q2,methods:jZ({beginLogin:Z.beginLogin??D1,version:Y,vault:_}),onLogin:(O)=>f(O),label:"ChatGPT (openai-auth account pool)",vault:XZ(_)});let o=await KZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let c=$.command&&$.location?await ZZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??WZ({...EZ({source:k,storage:w,counts:$2,now:j,authority:()=>_.authority()}),fetchImpl:W,now:j,randomUUID:F4,accountStoragePath:Q().configPath,accountStatePath:Q().statePath,packageVersion:Y,layoutNotice:j0,loadAccounts:O2,store:()=>k.poolStore(),migration:async()=>{if(A2(Q().configPath))return{migrated:!0};let O=await V();return{migrated:!1,blockers:O.open?[]:O.blockers}},beginAccountLogin:Z.beginLogin??D1,refreshAllQuota:async()=>(await k.pollRows(await O2(Q()))).map((O)=>({...O,account:O.id})),getStickyRouting:async(O)=>C.get(O),cacheKeepManager:u.manager,setCacheKeepEnabled:(O)=>u.configure({enabled:O}),setCacheKeepSubagents:(O)=>u.configure({subagents:O}),setCacheKeepSustain:(O)=>u.configure({sustain:O}),setCacheKeepWindow:(O)=>u.configure({window:O}),afterWrite:()=>k.load(),refreshSidebar:()=>M.publish(),clearStickyRouting:async(O)=>{let d=C.get(O)!==void 0;return C.forget(O),d},vault:_})):void 0;let s=new AbortController;(async()=>{try{for await(let O of $.event.subscribe({signal:s.signal}))if(O.type==="session.deleted")p.forgetSession(O.data.sessionID),u.forget(O.data.sessionID),l.forget(O.data.sessionID)}catch(O){if(!s.signal.aborted)J.warn("stopped listening for session deletion",{error:O instanceof Error?O.message:String(O)})}})();i=!0;return async()=>{R=!0,s.abort();let O=u.release();await c?.(),A?.dispose(),await k.dispose(),await M.release(),await Promise.allSettled([n.dispose(),I.dispose(),o.dispose()]);let d;try{await Promise.race([Promise.all([A?.idle(),k.settled(),q.store?.settled(),O]),new Promise((X2)=>{d=setTimeout(X2,K4),d.unref?.()})])}finally{clearTimeout(d),S.release(),await g?.release()}}}catch(_2){var R2=_2,M2=1}finally{uZ(J2,R2,M2)}}var T4=y1(),u6={id:z1,setup:T4.setup,server:H0.server};export{u6 as default,y1 as createOpenAIAuthPlugin,z1 as OPENAI_AUTH_PLUGIN_ID};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-openai-auth",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.3",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -66,13 +66,13 @@
|
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@ai-sdk/openai": "3.0.88",
|
|
69
|
-
"@cortexkit/common-auth": "^0.
|
|
69
|
+
"@cortexkit/common-auth": "^0.29.0",
|
|
70
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
71
71
|
"@opencode/plugin": "2.2.0"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
74
|
"@cortexkit/claustrum-client": "^0.13.0",
|
|
75
|
-
"@cortexkit/private-files": "^0.2.
|
|
75
|
+
"@cortexkit/private-files": "^0.2.2",
|
|
76
76
|
"@cortexkit/subc-client": "^0.22.0",
|
|
77
77
|
"@opentui/core": ">=0.7.0",
|
|
78
78
|
"@opentui/solid": ">=0.7.0",
|