@cortexkit/opencode-openai-auth 1.23.2 → 1.23.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 +2 -2
- package/dist/{index-by5wfvqm.js → index-9kges8jy.js} +1 -1
- package/dist/{index-t876xhkr.js → index-ekt6aq17.js} +1 -1
- package/dist/{index-v8w8j1wx.js → index-vf4nn20q.js} +1 -1
- package/dist/{index-v8wrmhyp.js → index-xkngfyvc.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/v2/server.js +3 -3
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$b as Z5,Aa as a$,Ac as nz,Bb as SJ,Cb as MK,Cc as X$,Db as IJ,Dc as LJ,Ec as H4,Fa as t$,Fc as wK,Ga as e$,Gb as U3,Gc as x1,Ha as Y5,Hb as H3,Ia as J5,Ib as B3,Ic as $5,Ja as az,Jc as I$,Ka as K4,Kb as yW,Kc as b$,La as U9,Lc as Q5,Ma as W1,Mb as W5,Mc as SK,Na as GJ,Nc as z3,Oa as C1,Ob as F$,Oc as IK,Pa as zJ,Pb as m1,Pc as t4,Qa as WJ,Qb as $9,Qc as fY,Ra as KJ,Rb as Gz,Rc as PY,Sa as UJ,Sb as I8,Sc as qY,Ta as HJ,Tb as kY,Tc as G4,Ua as gY,Ub as xY,Uc as k5,Va as _K,Vb as h1,Vc as e4,Wa as DK,Wc as W3,Xa as OK,Xc as G5,Ya as PK,Za as kW,Zb as v8,_a as b8,_b as qJ,_c as bK,ac as RJ,bb as j$,cb as _J,cd as kK,da as Q4,db as xW,dc as TK,ea as n4,eb as hW,ec as RK,ed as xK,fa as $K,fb as vW,fc as bJ,fd as hK,ga as e0,gc as yJ,gd as rK,ha as Iz,hb as A7,hd as JW,ia as x5,ib as wJ,ic as uz,id as sK,jb as qK,jc as pz,jd as aK,kc as b7,kd as WW,la as Q0,lc as k7,ma as GW,mc as G3,nc as _9,pc as kJ,qa as ZK,qc as B4,rc as C5,sa as kz,sc as w5,ta as xz,tb as F9,tc as S5,ua as vY,uc as I5,va as yY,vb as EK,vc as b5,wa as zW,xa as r$,xb as h8,xc as lz,ya as PJ,yc as dz,za as s$,zb as AK,zc as iz}from"./index-by5wfvqm.js";import{Ad as LW,Bd as gK,Cd as fK,Dd as mK,Id as mY,Jd as cY,Kd as cK,Ld as uK,Od as pK,Pd as lK,Qd as dK,Sd as D9,Td as $8,Ud as iK,Vd as nK,Wd as n1,Xd as oK,od as u7,qd as q5,sd as m6,td as vK,wd as yK}from"./index-nd2ks7er.js";import{$e as c$,$f as c6,Af as p4,Ag as fz,Be as g$,Bf as n8,Bg as mz,Ce as f$,Cf as f3,Cg as cz,De as H9,Df as w1,Ef as J4,Ff as s3,Gf as n6,Hf as a4,If as YW,Jf as y6,Kf as J$,Le as m$,Lf as n0,Mf as s8,Nf as HK,Qf as S$,Rf as k1,Sf as BK,Tf as V9,Ue as w$,Vf as S7,We as X8,Wf as x8,Xe as GK,Xf as I7,Ye as r6,Yf as d1,Ze as Q3,Zf as j9,_e as zK,_f as U1,af as u$,ag as VK,bf as R6,bg as NK,cf as C6,cg as R5,de as p1,df as b1,dg as bz,ef as p$,eg as g6,fe as $4,ff as l$,fg as t0,gf as d$,gg as I1,hf as i$,hg as OJ,if as n$,jf as o$,kf as B9,kg as LK,le as MY,lf as l1,me as Sz,mf as R4,mg as xJ,nf as DY,ng as U4,of as c0,og as U6,pf as WK,pg as b6,qe as C7,qf as k8,qg as hz,rf as Y8,rg as w8,sf as KK,sg as jK,te as Y$,uf as UK,ug as vz,vf as a0,vg as yz,wf as u4,xf as K1,xg as FK,yf as i8,yg as gz,zf as e1,zg as w7}from"./index-x00sxt2w.js";import{Hg as XK,Mg as e3}from"./index-49ncs7dr.js";import{Rg as U5,Sg as H5,Tg as B5,Ug as TW,Vg as QK,Wg as f6,Xg as RW,Yg as CW}from"./index-v8wrmhyp.js";import{gh as c7,lh as E4,nh as X5}from"./index-wjp3q15r.js";import{rh as Z9,th as U0}from"./index-td4g5dc9.js";import{Hh as V5,Jh as CK}from"./index-j700j6at.js";import{Lh as cJ}from"./index-q2czrasr.js";import{randomUUID as e7}from"node:crypto";import{statSync as GF}from"node:fs";import Y3 from"node:os";var BJ={hosts:"OpenCode 1, OpenCode 2 and Pi",project:"user-only"},q6={...BJ,overrides:{host:!0}},v6={...BJ,overrides:{host:!0,isolatedHosts:["pi"]}},c4={hosts:"OpenCode 1 only",project:"user-only"},m3=(Y,J)=>Y.flatMap((X)=>J.map(($)=>({source:X,path:$}))),E6=(...Y)=>m3(["opencode-store","pi-store"],Y),i0=(...Y)=>m3(["opencode-store"],Y),T0=f3({plugin:"openai-auth",settings:{routing_mode:{...q6,value:e1(["ordered","main-first","fallback-first","sticky-balanced"]),default:"main-first",legacy:E6(["routing","mode"])},max_same_account_wait:{...q6,value:e1(["off","15m","cache"]),default:"15m",legacy:E6(["routing","maxSameAccountWait"])},wait_for_reset:{...q6,value:a0(),default:!1,legacy:[]},fallback_on:{...q6,hosts:"OpenCode 1 and Pi; not read by OpenCode 2",value:p4(u4()),default:[401,403,429],legacy:E6(["fallbackOn"])},refresh_enabled:{...c4,hosts:"OpenCode 1 legacy fallback refresh only",value:a0(),default:!0,legacy:i0(["refresh","enabled"])},refresh_before_expiry_minutes:{...q6,value:K1(),default:240,legacy:E6(["refresh","refreshBeforeExpiryMinutes"])},quota_enabled:{...q6,value:a0(),default:!0,legacy:E6(["quota","enabled"])},quota_check_interval_minutes:{...c4,hosts:"OpenCode 1 legacy quota freshness and polling only",value:K1({min:1}),default:5,legacy:i0(["quota","checkIntervalMinutes"])},quota_minimum_remaining:{...q6,value:p4(n8({window:e1(["primary","secondary"]),floor:K1()})),default:[],legacy:E6(["quota","minimumRemaining","primary"],["quota","minimumRemaining","5h"],["quota","minimumRemaining","secondary"],["quota","minimumRemaining","1w"])},quota_fail_closed_on_unknown:{...q6,value:a0(),default:!1,legacy:E6(["quota","failClosedOnUnknownQuota"])},cost_zeroing:{...c4,value:a0(),default:!0,legacy:i0(["costZeroing","enabled"])},killswitch_enabled:{...q6,value:a0(),default:!1,legacy:E6(["killswitch","enabled"])},killswitch_default_primary:{...q6,value:K1(),default:5,legacy:E6(["killswitch","defaults","primary"],["killswitch","main","primary"],["killswitch","main","5h"])},killswitch_default_secondary:{...q6,value:K1(),default:10,legacy:E6(["killswitch","defaults","secondary"],["killswitch","main","secondary"],["killswitch","main","1w"])},killswitch_account_floors:{...BJ,value:p4(n8({account:i8(),host:e1(["opencode","pi","both"]),primary:K1(),secondary:K1()})),default:[],legacy:E6(["killswitch","accounts"])},cache_keep_enabled:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","enabled"],["cachekeep","enabled"])},cache_keep_subagents:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","subagents"],["cachekeep","subagents"])},cache_keep_sustain:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","sustain"],["cachekeep","sustain"])},cache_keep_window:{...v6,value:p4(n8({start_hour:u4({min:0,max:23}),end_hour:u4({min:0,max:23})})),default:[],legacy:i0(["cacheKeep","startHour"],["cacheKeep","endHour"],["cachekeep","startHour"],["cachekeep","endHour"])},log_level:{...v6,value:e1(["error","warn","info","debug","trace","default"]),default:"default",legacy:i0(["logging","level"])},request_dumps:{...v6,value:a0(),default:!1,legacy:i0(["dump"],["dump","enabled"])},dump_dir:{...v6,value:i8(),default:"",legacy:i0(["dumpDir"])},dump_max_bytes:{...v6,value:u4({min:0,max:Number.MAX_SAFE_INTEGER}),default:536870912,legacy:i0(["dumpMaxBytes"])},web_sockets:{...c4,value:a0(),default:!1,legacy:i0(["webSockets"])},raw_web_socket:{...c4,value:a0(),default:!1,legacy:i0(["rawWebSocket"])},responses_lite:{...v6,value:a0(),default:!1,legacy:i0(["responsesLite"])},codex_api_endpoint:{...v6,value:i8(),default:"https://chatgpt.com/backend-api/codex/responses",legacy:i0(["codexApiEndpoint"])}}});import{chmod as RU,mkdir as CU}from"node:fs/promises";import{join as wU}from"node:path";import{existsSync as p3,readFileSync as ZU}from"node:fs";import{readFileSync as VU}from"node:fs";var c3="Settings moved to ";function NU(Y){let J=Y.split(/\r?\n/,1)[0]??"";if(!J.startsWith(c3)||!J.endsWith("."))return;return J.slice(c3.length,-1)}function LU(Y){try{return NU(VU(`${Y}.MOVED_READPLEASE`,"utf8"))}catch{return}}function u3(Y,J){let X=LU(Y);return X!==void 0&&n6(X)===n6(J)}function jU(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function FU(Y,J){let X=Y;for(let[$,Q]of J.entries()){if(!jU(X)||!Object.hasOwn(X,Q))return!1;if($===J.length-1)return!0;X=X[Q]}return!1}function _U(Y,J){return Object.values(T0.settings).some((X)=>X.legacy.some(($)=>$.source===`${J}-store`&&FU(Y,$.path)))}function DU(Y){try{return _U(JSON.parse(ZU(Y.configPath,"utf8")),Y.host)}catch{return!1}}function o8(Y){let J=p3(Y.target),X=Y.sources.some((K)=>u3(K.configPath,Y.target)),$=Y.sources.filter((K)=>p3(K.configPath)),Q=$.length>0,G=X&&!J,z=J&&!X&&$.some(DU);return{kind:J?"target-exists":X?"target-removed":Q?"move-needed":"no-source",completed:J||X,targetExists:J,noteNamesTarget:X,sourcePresent:Q,preExistingFile:z,removedFile:G}}function r8(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function l3(Y){try{let J=Number(Y);return Number.isFinite(J)?Math.min(100,Math.max(0,J)):0}catch{return 0}}function VJ(Y,J){let X=U1(Y,J);return{primary:l3(X.primary),secondary:l3(X.secondary)}}function d3(Y,J,X,$){if(!r8(Y))return;for(let Q of["primary","secondary","5h","1w"])if(Y[Q]===null)$.push({source:X,key:`${J}.${Q}`,reason:"invalid"})}function i3(Y){let J={entries:[],unmapped:[]},X=[],$=[];Y.forEach((z,K)=>{if(!z.present)return;if(z.host!=="opencode"&&z.host!=="pi")throw Error("Unsupported killswitch floors source host");let U=z.host,H=r8(z.value)?z.value:{},V=r8(H.killswitch)?H.killswitch:void 0,F={killswitch:H.killswitch},Z=V?.schema===s8,N=Z?VJ({killswitch:{...V,accounts:void 0}}):VJ(F);if(X.push({source:K,floors:N}),!Z)d3(V?.main,"killswitch.main",K,J.unmapped);if(!r8(V?.accounts))return;for(let j of Object.keys(V.accounts)){let P=`killswitch.accounts.${j}`;if(!Z&&j==="main"){J.unmapped.push({source:K,key:P,reason:"shadowed"});continue}if(!Z)d3(V.accounts[j],P,K,J.unmapped);$.push({account:j,host:U,...VJ(F,j==="main"?void 0:j)})}});for(let[z,K]of[["primary",5],["secondary",10]]){if(X.every(({floors:U})=>U[z]===K))continue;for(let{source:U,floors:H}of X)J.entries.push({source:U,setting:`killswitch_default_${z}`,value:H[z]})}let Q=[];for(let z of $){let K=z.account.startsWith("vault:")?Q.find((U)=>U.account===z.account&&U.host!==z.host&&U.primary===z.primary&&U.secondary===z.secondary):void 0;if(K)K.host="both";else Q.push(z)}let G=X[0];if(G&&Q.length>0)J.entries.push({source:G.source,setting:"killswitch_account_floors",value:Q});return J}function H1(Y){if(Y===null||typeof Y!=="object"||Array.isArray(Y))return!1;let J=Object.getPrototypeOf(Y);return J===Object.prototype||J===null}function n3(Y){let J;try{J=JSON.parse(Y)}catch{throw Error("Settings source is not JSON")}if(!H1(J))throw Error("Settings source is not an object");return J}function Y4(Y,J){let X=Y;for(let $ of J){if(!H1(X)||!Object.hasOwn(X,$))return;X=X[$]}return X}function l4(Y,J,X=!1){switch(Y.kind){case"boolean":return typeof J==="boolean";case"string":return typeof J==="string";case"integer":case"number":return typeof J==="number"&&Number.isFinite(J)&&(Y.kind!=="integer"||Number.isInteger(J))&&(Y.min===void 0||J>=Y.min)&&(Y.max===void 0||J<=Y.max);case"oneOf":return typeof J==="string"&&Y.values.includes(J);case"list":return Array.isArray(J)&&Array.from(J).every(($)=>l4(Y.item,$,!0));case"object":return H1(J)&&Object.entries(J).every(([$,Q])=>{let G=Y.fields[$];return Object.hasOwn(Y.fields,$)&&G!==void 0&&l4(G,Q,X)})&&(!X||Object.keys(Y.fields).every(($)=>Object.hasOwn(J,$)));case"record":return H1(J)&&Object.values(J).every(($)=>l4(Y.value,$,!0))}}class t8 extends Error{setting;key;constructor(Y,J){super(`Cannot move setting ${Y}${J?` (${J})`:""}`);this.setting=Y;this.key=J;this.name="CannotMoveSettingError"}}function a8(Y,J){throw new t8(Y,J)}function o3(Y,J,X){try{let $=Number(Y);if(Number.isFinite($))return $}catch{}return a8(J,X)}function OU(Y,J){let X=[];for(let[$,Q]of[["primary","5h"],["secondary","1w"]]){let G=["quota","minimumRemaining"],z=Y4(Y,[...G,$]),K=Y4(Y,[...G,Q]);for(let[H,V]of[[$,z],[Q,K]])if(V===null)J([...G,H].join("."),"invalid");if(z!=null&&K!=null)J([...G,Q].join("."),"shadowed");let U=z??K;if(U==null)continue;X.push({window:$,floor:o3(U,"quota_minimum_remaining",[...G,$].join("."))})}return X}function PU(Y,J,X){let $=Y4(Y,[J,"startHour"]),Q=Y4(Y,[J,"endHour"]);if($===void 0&&Q===void 0)return[];let G,z;try{G=Number($),z=Number(Q)}catch{G=Number.NaN,z=Number.NaN}if(Number.isInteger(G)&&G>=0&&G<=23&&Number.isInteger(z)&&z>=0&&z<=23&&G!==z)return[{start_hour:G,end_hour:z}];if($!==void 0)X(`${J}.startHour`,"invalid");if(Q!==void 0)X(`${J}.endHour`,"invalid");return[]}function qU(Y,J,X){let $=T0.settings[Y],Q=$.default;if(Y==="quota_minimum_remaining")return OU(J,X);let G=H1(J.cacheKeep)?"cacheKeep":"cachekeep";if(Y==="cache_keep_window")return PU(J,G,X);let z=$.legacy[0];if(!z)return a8(Y);let K=z.path;if(Y.startsWith("cache_keep_"))K=[G,...K.slice(1)];if(Y==="request_dumps")K=typeof J.dump==="boolean"?["dump"]:["dump","enabled"];let U=Y4(J,K),H=K.join(".");if(U===void 0)return Q;if(Y==="max_same_account_wait"){if(U===0)return"off";if(U===15)return"15m";if(U==="max")return"cache"}else if(Y==="fallback_on"){if(Array.isArray(U)){let V=U.filter((F)=>Number.isInteger(F));if(V.length!==U.length)X(H,"invalid");return V.length?V:Q}}else if(Y==="refresh_before_expiry_minutes"||Y==="quota_check_interval_minutes"){if(U!=null){let V=o3(U,Y,H);return Y==="quota_check_interval_minutes"?Math.max(1,V):V}}else if(Y==="quota_fail_closed_on_unknown"){if(U!=null)return Boolean(U)}else if(Y==="dump_dir"||Y==="codex_api_endpoint"){if(typeof U==="string"&&U.trim())return U.trim()}else if(l4($.value,U))return U;return X(H,"invalid"),Q}var EU=new Set(["version","accounts","main","commonAuthPool","commonAuthLimits","openaiAuthPool","mainAccountId","reset","claustrum"]),AU=new Set(["refresh.mainLastRefreshError","refresh.mainRefreshLeaseId","refresh.mainRefreshLeaseUntil","refresh.mainRefreshLeaseTokenHash","quota.mainQuota","quota.mainQuotaCheckedAt","quota.mainQuotaToken","quota.mainLastQuotaApiError"]);function MU(Y,J,X){let $=new Set;for(let G of Object.values(T0.settings))for(let z of G.legacy){let K=z.path.join(".");if($.add(K),J==="pi"&&!G.legacy.some((U)=>U.source==="pi-store")&&Y4(Y,z.path)!==void 0){if(K==="dump.enabled"&&Object.hasOwn(Y,"dump"))continue;X(K,"other-host")}}let Q=(G,z="")=>{for(let[K,U]of Object.entries(G)){let H=z?`${z}.${K}`:K;if(!z&&EU.has(K)||AU.has(H)||H==="killswitch.schema")continue;if($.has(H))continue;if([...$].some((V)=>V.startsWith(`${H}.`)))if(H1(U))Q(U,H);else X(H,"invalid");else X(H,"retired")}};if(Q(Y),J==="opencode"&&H1(Y.cacheKeep)&&Y.cachekeep!==void 0)X("cachekeep","shadowed")}function r3(Y){let J={entries:[],unmapped:[]},X=Y.flatMap((Q,G)=>{if(!Q.present)return[];if(Q.host!=="opencode"&&Q.host!=="pi")throw Error("Unsupported settings source host");if(!H1(Q.value))throw Error("Settings source is not an object");let z=(K,U)=>{if(!J.unmapped.some((H)=>H.source===G&&H.key===K&&H.reason===U))J.unmapped.push({source:G,key:K,reason:U})};return MU(Q.value,Q.host,z),[{source:G,host:Q.host,store:Q.value,report:z}]});for(let Q of Object.keys(T0.settings)){if(Q.startsWith("killswitch_default_")||Q==="killswitch_account_floors")continue;let G=T0.settings[Q],z=X.filter((K)=>G.legacy.some((U)=>U.source===`${K.host}-store`)).map((K)=>({source:K.source,value:qU(Q,K.store,K.report)}));if(z.every((K)=>JSON.stringify(K.value)===JSON.stringify(G.default)))continue;for(let K of z)J.entries.push({...K,setting:Q})}let $=i3(Y);J.entries.push(...$.entries),J.unmapped.push(...$.unmapped);for(let Q of J.entries){if(!Object.hasOwn(T0.settings,Q.setting))a8(Q.setting);if(!l4(T0.settings[Q.setting].value,Q.value))a8(Q.setting)}return J}class NJ extends Error{host;path;code;constructor(Y,J,X){super(`Settings source ${Y} ${J}: ${X}`);this.host=Y;this.path=J;this.code=X}}function a3(Y){let J=Y?.code;return typeof J==="string"&&/^[A-Z][A-Z0-9_]*$/.test(J)?J:"SETTINGS_MOVE_FAILED"}function TU(Y,J){if(Y instanceof NJ)return{kind:"cause",host:Y.host,path:Y.path,code:Y.code};if(Y instanceof t8)return{kind:"setting",setting:Y.setting};let X=Y?.path,$=J.find((G)=>G.path===X),Q=a3(Y);if($)return{kind:"cause",host:$.host,path:$.path,code:Q};return{kind:"cause",code:Q}}async function t3({install:Y,fence:J,log:X}){if(Y.separate||Y.sources.length===0)return;let $=[...Y.sources].sort((G,z)=>Number(G.host==="pi")-Number(z.host==="pi")).map((G)=>({host:G.host,path:G.configPath,locks:[{path:G.configPath,name:"save"},{path:G.statePath,name:"save"}],read(z){try{return n3(z)}catch(K){throw new NJ(G.host,G.configPath,K instanceof Error&&K.message==="Settings source is not JSON"?"SOURCE_NOT_JSON":"SOURCE_NOT_OBJECT")}}})),Q=await s3({definition:T0,target:Y.target,separateInstall:!1,sources:$,map:r3,fence:J,log:{warn(){},info(){}}});for(let G of Q.unmapped)X.warn(`Settings move: ${$[G.source]?.host??"unknown"} ${G.key}: ${G.reason}`);for(let G of Q.noteFailures){let z=$.find((K)=>`${K.path}.MOVED_READPLEASE`===G.path);X.warn(`Settings move note: ${z?.host??"unknown"} ${G.path}: ${a3(G.error)}`)}if(Q.outcome==="failed"){Q.failure=TU(Q.cause,$);let G=Q.failure;X.warn(G.kind==="setting"?`Settings move failed: cannot move setting ${G.setting}`:("host"in G)?`Settings move failed: ${G.host} ${G.path}: ${G.code}`:`Settings move failed: ${G.code}`)}return Q}class Y9 extends Error{folder;constructor(Y,J){let X=J instanceof Error?J.message:String(J);super(`Cannot record settings authority in ${Y}: ${X}`,{cause:J});this.folder=Y;this.name="SettingsAuthorityRefusal"}}var $$=Symbol.for("@cortexkit/openai-auth/settings-authority"),Q$=globalThis,e8=Q$[$$]??new Map;Q$[$$]=e8;function d4(Y){return e8.get(n6(Y))}function G$(Y){let J=n6(Y.install.configIdentity),X=e8.get(J);if(X)return X;let $=Promise.resolve().then(()=>SU(Y));return e8.set(J,$),$}async function SU({install:Y,stateHome:J,record:X,log:$,fenceOptions:Q}){let G={decision:Y.separate?"separate":"shared",install:Y,ranMove:!1},z=()=>{return J$(Y.configIdentity,G.decision),G};if(Y.separate){try{await X("separate")}catch{}return z()}let K=X$(J),U=()=>{return G.completion=o8(Y),G.completion},H=(V)=>V.completed||!V.sourcePresent;try{return await CU(K,{recursive:!0,mode:448}),await RU(K,448),await e3(wU(K,"settings-authority"),{name:"settings-authority",...Y$},async(V)=>{if(!H(U()))if(G.fence=await LJ({...Q,stateHome:J}),G.fence.open){G.ranMove=!0;try{G.move=await t3({install:Y,log:$,async fence(){let N=await LJ({...Q,stateHome:J});if(!N.open)G.fence=N;return N.open}})}catch(N){G.move={outcome:"failed",cause:N,unmapped:[],differing:[],noteFailures:[],postPublishFailures:[],failure:{kind:"cause",code:"SETTINGS_MOVE_FAILED"}}}let F=G.move?.outcome,Z=U();G.decision=F==="moved"||F==="done-already"||F==="aborted-target-appeared"||Z.completed?"shared":"legacy"}else G.decision="legacy";await V.assertOwned(),await X(G.decision)}),z()}catch(V){if(!H(U()))throw new Y9(K,V);return G.decision="shared",z()}}var B1=Object.freeze({file:(Y)=>`Settings file: ${Y}`,separate:"Settings stay in this install's account store.",legacyProcess:"Settings stay in the old account store because another process still uses it.",legacyBusy:"Settings stay in the old account store because the stores were busy.",legacySetting:(Y)=>`Settings stay in the old account store because ${Y} couldn't be moved.`,legacyFailed:(Y)=>`Settings stay in the old account store because the move failed: ${Y}.`,sharedMissing:"No settings file, so defaults are in use.",sharedMoved:"Settings were moved to the settings file in this process.",sharedFound:"Settings file found.",waitForResetOn:"wait_for_reset is on: when every account is at a usage limit with a known reset, the turn waits for the reset.",preExistingFile:(Y)=>`Settings come from ${Y}. Preferences in the old account store weren't copied, because this file already existed.`,removedFile:(Y)=>`The settings file ${Y} was removed, so defaults are in use. Old preferences aren't copied again.`,refused:(Y,J)=>`openai-auth didn't start. Process records folder: ${Y}. Cause: ${J}`,report:{"unknown-key":(Y)=>`Unknown settings key: ${Y}.`,"override-not-allowed":(Y)=>`Settings override not allowed: ${Y}.`,"user-only-in-project":(Y)=>`User-only setting found in a project file: ${Y}.`,"invalid-value":(Y)=>`Invalid settings value: ${Y}.`,"invalid-schema-version":(Y)=>`Invalid settings schema version: ${Y}.`,"newer-version-key-ignored":(Y)=>`Settings key from a newer version ignored: ${Y}.`,"duplicate-key":(Y)=>`Duplicate settings key: ${Y}.`,unparseable:(Y)=>`The settings file ${Y} can't be parsed.`,unreadable:(Y)=>`The settings file ${Y} can't be read.`},checks:{duplicateFloors:"Invalid killswitch_account_floors: duplicate account and host pair.",localBoth:"Invalid killswitch_account_floors: only vault accounts may use host both.",duplicateQuota:"Invalid quota_minimum_remaining: duplicate quota window.",warmWindow:"Invalid cache_keep_window: use at most one window with unequal hours."},refusal:{"settings-unparseable":"The settings file can't be read. Fix it or remove it, then try again.","settings-newer-version":"The settings file is from a newer openai-auth. Update openai-auth to change settings.","settings-invalid-value":"That value isn't allowed for this setting.","settings-busy":"The settings file is busy. Try again.","settings-unavailable":"Settings can't be saved for this install."}});function J9(Y){return B1.refusal[Y]}function IU(Y){let J=B1;if(Y.reason==="invalid-value"&&Y.keyPath.length===1)switch(Y.keyPath[0]){case"killswitch_account_floors":if(Y.detail==="Duplicate account and host pair")return J.checks.duplicateFloors;if(Y.detail==="Only vault accounts may use host both")return J.checks.localBoth;break;case"quota_minimum_remaining":if(Y.detail==="Duplicate quota window")return J.checks.duplicateQuota;break;case"cache_keep_window":if(Y.detail==="Use at most one window with unequal hours")return J.checks.warmWindow}let X=Y.reason==="unparseable"||Y.reason==="unreadable"?Y.file.path:Y.keyPath.length?Y.keyPath.join("."):Y.file.path;return J.report[Y.reason](X)}function bU(Y,J,X=!1){let $=B1;if(Y.decision==="separate")return $.separate;if(Y.decision==="shared"){if(!J?.targetExists)return $.sharedMissing;return Y.ranMove&&Y.move?.outcome==="moved"&&!X?$.sharedMoved:$.sharedFound}if(Y.move?.outcome==="busy")return $.legacyBusy;if(Y.move?.outcome==="fence-closed"||Y.fence?.open===!1)return $.legacyProcess;let Q=Y.move?.failure;if(Q?.kind==="setting")return $.legacySetting(Q.setting);let G=Q?.kind==="cause"?"path"in Q?`${Q.host} ${Q.path}: ${Q.code}`:Q.code:"SETTINGS_MOVE_FAILED";return $.legacyFailed(G)}var z$=Symbol.for("@cortexkit/openai-auth/settings-diagnostics"),W$=globalThis,i4=W$[z$]??{logged:new Set,sawTargetMissing:new Set};W$[z$]=i4;async function K$({configPath:Y,snapshot:J,log:X}){let $=d4(Y);if(!$)throw Error("Settings authority has not been decided");let Q;try{Q=await $}catch(U){if(U instanceof Y9||U instanceof Error&&U.name==="SettingsAuthorityRefusal"&&"folder"in U&&typeof U.folder==="string"){let H=U.cause;return{lines:[B1.refused(String(U.folder),H instanceof Error?H.message:String(H))]}}throw U}if(Q.decision==="separate")return{lines:[B1.separate]};let G=Q.decision==="shared"?o8(Q.install):Q.completion,z=n6(Q.install.target);if(Q.decision==="shared"&&!G?.targetExists)i4.sawTargetMissing.add(z);let K=[B1.file(Q.install.target),bU(Q,G,i4.sawTargetMissing.has(z))];if(Q.decision==="shared"&&G){for(let U of["preExistingFile","removedFile"]){if(!G[U])continue;let H=B1[U](Q.install.target);K.push(H);let V=`${U}:${n6(Q.install.target)}`;if(!i4.logged.has(V))i4.logged.add(V),X.warn(H)}if(await J?.refresh(),K.push(...J?.report().map(IU)??[]),J?.get("wait_for_reset"))K.push(B1.waitForResetOn)}return{lines:K}}var m0=(Y)=>Q0(Y)?Y:{},kU=["primary","secondary"];function U$(Y){let{routing:J,killswitch:X}=Y.view(),$=Object.fromEntries(Object.entries(X?.accounts??{}).map(([Q,G])=>[Q,Object.fromEntries(Object.entries(m0(G)).filter(([,z])=>z!==0))]));for(let{account:Q}of Y.get("killswitch_account_floors"))if(!Object.hasOwn($,Q))Object.defineProperty($,Q,{value:{},enumerable:!0,writable:!0,configurable:!0});return{routing:J,killswitch:{...X,accounts:$}}}function xU(Y){let J=new Map,X=(K,U)=>{let H=J.get(K)??new Set;H.add(U),J.set(K,H)},$=!1,Q=!0,G=(K,U=!1)=>{if(!Q)return;if(K[0]!=="killswitch"||K[1]!=="accounts")return;$=!0;let[,,H,V]=K;if(U&&H!==void 0&&(V==="primary"||V==="secondary"))X(H,V)},z=(K,U)=>new Proxy(K,{ownKeys(H){return G(U),Reflect.ownKeys(H)},get(H,V){let F=Reflect.get(H,V);return typeof V==="string"&&Q0(F)?z(F,[...U,V]):F},set(H,V,F){if(typeof V==="string")G([...U,V],!0);return Reflect.set(H,V,F)},deleteProperty(H,V){if(typeof V==="string")G([...U,V],!0);return Reflect.deleteProperty(H,V)}});return{value:z(Y,[]),windows:J,add:X,touched:()=>$,finish:()=>{Q=!1}}}function o4(Y){let{host:J,snapshot:X}=Y,$=Y.writer??J4(T0,{file:Y.file,log:Y.log,separateInstall:!1,createMissing:!0});return{async read(){return await X.refresh(),U$(X)},async update(Q){try{await X.refresh();let G=U$(X),z=xU(structuredClone(G)),K=await Q(z.value)??z.value;z.finish();let U=JSON.parse(JSON.stringify(K)),H=[],V=m0(U.routing),F=m0(G.routing);if(V.mode!==F.mode)H.push({setting:"routing_mode",value:V.mode});if(V.maxSameAccountWait!==F.maxSameAccountWait)H.push({setting:"max_same_account_wait",value:V.maxSameAccountWait===0?"off":V.maxSameAccountWait==="max"?"cache":"15m"});let Z=m0(U.killswitch);if(Z.enabled!==m0(G.killswitch).enabled)H.push({setting:"killswitch_enabled",value:Z.enabled});let N=m0(m0(G.killswitch).accounts),j=m0(Z.accounts);for(let v of new Set([...Object.keys(N),...Object.keys(j)])){let y=Object.hasOwn(N,v)&&!Object.hasOwn(j,v)&&!z.windows.has(v);for(let I of kU)if(y||!Object.is(m0(N[v])[I],m0(j[v])[I]))z.add(v,I)}let P=z.touched()||z.windows.size>0;if(P){if(X.report().some((v)=>v.keyPath[0]==="killswitch_account_floors"||v.reason==="unreadable"||v.reason==="unparseable"))throw new w1("settings-invalid-value",Y.file)}await $.update((v)=>{let y=[...H];if(P){let I=v.status==="ready"&&Object.hasOwn(v.document,"killswitch_account_floors")?v.document.killswitch_account_floors:T0.settings.killswitch_account_floors.default;if(!Array.isArray(I))throw new w1("settings-invalid-value",Y.file);let A=I;for(let[q,C]of z.windows){let m=q.startsWith("vault:"),r=(f)=>m0(f).account===q,l=m0(A.find((f)=>r(f)&&m0(f).host===J)??(m?A.find((f)=>r(f)&&m0(f).host==="both"):void 0));A=A.filter((f)=>!r(f)||!m&&m0(f).host!==J);let R0=m0(j[q]),B0=(f)=>{if(C.has(f))return R0[f];let V0=l[f];return V0===0?void 0:V0},z0=B0("primary"),A0=B0("secondary");if(z0!==void 0||A0!==void 0)A.push({account:q,host:m?"both":J,primary:z0??0,secondary:A0??0})}y.push({setting:"killswitch_account_floors",value:A})}return y},{host:J}),await X.refresh()}catch(G){if(G instanceof w1)throw new n4(G.code,J9(G.code));throw G}}}}import{readFile as tU}from"node:fs/promises";import{readFileSync as yU,statSync as gU}from"node:fs";import{homedir as fU,tmpdir as mU}from"node:os";import{join as Q9}from"node:path";var hU=["killswitch_enabled","killswitch_default_primary","killswitch_default_secondary","killswitch_account_floors","quota_minimum_remaining","cache_keep_window"];function H$(Y,J){return structuredClone(J&&Y==="killswitch_enabled"?!0:T0.settings[Y].default)}function vU(Y,J){let X=[],$=(U,H)=>{X.push({file:{kind:"user",path:J},keyPath:[U],reason:"invalid-value",detail:H})},Q=Y.killswitch_account_floors,G=Q.map(({account:U,host:H})=>JSON.stringify([U,H]));if(new Set(G).size!==G.length)$("killswitch_account_floors","Duplicate account and host pair");if(Q.some(({account:U,host:H})=>H==="both"&&!U.startsWith("vault:")))$("killswitch_account_floors","Only vault accounts may use host both");let z=Y.quota_minimum_remaining.map(({window:U})=>U);if(new Set(z).size!==z.length)$("quota_minimum_remaining","Duplicate quota window");let K=Y.cache_keep_window;if(K.length>1||K.some(({start_hour:U,end_hour:H})=>U===H))$("cache_keep_window","Use at most one window with unequal hours");return X}function B$(Y,J){let X=Y.killswitch_account_floors,$=Object.fromEntries([...X.filter((G)=>G.host==="both"),...X.filter((G)=>G.host===J)].map(({account:G,primary:z,secondary:K})=>[G,{primary:z,secondary:K}])),Q=Y.cache_keep_window[0];return{version:1,accounts:[],routing:{mode:Y.routing_mode,maxSameAccountWait:{off:0,"15m":15,cache:"max"}[Y.max_same_account_wait]},waitForReset:Y.wait_for_reset,fallbackOn:Y.fallback_on,refresh:{enabled:Y.refresh_enabled,refreshBeforeExpiryMinutes:Y.refresh_before_expiry_minutes},quota:{enabled:Y.quota_enabled,checkIntervalMinutes:Y.quota_check_interval_minutes,minimumRemaining:Object.fromEntries(Y.quota_minimum_remaining.map(({window:G,floor:z})=>[G,z])),failClosedOnUnknownQuota:Y.quota_fail_closed_on_unknown},costZeroing:{enabled:Y.cost_zeroing},killswitch:{schema:s8,enabled:Y.killswitch_enabled,defaults:{primary:Y.killswitch_default_primary,secondary:Y.killswitch_default_secondary},accounts:$},logging:{level:Y.log_level==="default"?void 0:Y.log_level},cachekeep:void 0,cacheKeep:{enabled:Y.cache_keep_enabled,subagents:Y.cache_keep_subagents,sustain:Y.cache_keep_sustain,startHour:Q?.start_hour,endHour:Q?.end_hour},dump:{enabled:Y.request_dumps},dumpDir:Y.dump_dir,dumpMaxBytes:Y.dump_max_bytes,webSockets:Y.web_sockets,rawWebSocket:Y.raw_web_socket,responsesLite:Y.responses_lite,codexApiEndpoint:Y.codex_api_endpoint}}function V$(Y,J){return{...J,...Y,accounts:J?.accounts??[],main:J?.main,refresh:{...Y.refresh,mainLastRefreshError:J?.refresh?.mainLastRefreshError,mainRefreshLeaseId:J?.refresh?.mainRefreshLeaseId,mainRefreshLeaseUntil:J?.refresh?.mainRefreshLeaseUntil,mainRefreshLeaseTokenHash:J?.refresh?.mainRefreshLeaseTokenHash},quota:{...Y.quota,mainQuota:J?.quota?.mainQuota,mainQuotaCheckedAt:J?.quota?.mainQuotaCheckedAt,mainQuotaToken:J?.quota?.mainQuotaToken,mainLastQuotaApiError:J?.quota?.mainLastQuotaApiError}}}function ZJ(Y,J){let X=Object.fromEntries(Object.keys(T0.settings).map(($)=>[$,H$($,!0)]));return V$(B$(X,Y),J)}async function N$(Y){let{handle:J,host:X,file:$}=Y,Q,G,z=[],K=!1,U=Promise.resolve(),H=new Set,V=async()=>{if(K)return;if(await J.read(),K)return;let N=Object.fromEntries(await Promise.all(Object.keys(T0.settings).map(async(A)=>[A,await J.get(A,{host:X})])));if(K)return;let j=J.report(),P=vU(N,$);z=[...j,...P];let v=j.some((A)=>A.file.path===$&&(A.reason==="unreadable"||A.reason==="unparseable")),y=(A)=>P.some((q)=>q.keyPath[0]===A)||j.some((q)=>{if(q.reason!=="invalid-value"||q.keyPath[0]!==A)return!1;if(A==="cache_keep_window")return X==="pi"===(q.keyPath[1]==="pi");return!0}),I=(A)=>{N[A]=Q?structuredClone(Q[A]):H$(A,v)};for(let A of hU)if(v||y(A))I(A);if(y("killswitch_account_floors"))N.killswitch_default_primary=Q?.killswitch_default_primary??N.killswitch_default_primary,N.killswitch_default_secondary=Q?.killswitch_default_secondary??N.killswitch_default_secondary;if(Q=N,G=B$(N,X),!K)for(let A of H)A()},F=()=>{return U=U.then(V,V),U},Z=J.watch(()=>{F()});try{await F()}catch(N){throw Z(),N}return{view(N){return V$(structuredClone(G),N)},get(N){return structuredClone(Q[N])},report(){return structuredClone(z)},refresh:F,onChange(N){return H.add(N),()=>{H.delete(N)}},dispose(){K=!0,Z(),H.clear()}}}var _$=U0("config"),L$=!1,cU="openai-auth.json",A6={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function uU(){let Y=process.env[A6.configDir]?.trim();if(Y)return Y;return Q9(process.env.XDG_CONFIG_HOME||Q9(fU(),".config"),"opencode")}function _6(){return process.env[A6.configFile]?.trim()||Q9(uU(),cU)}function D$(Y){try{let J=JSON.parse(yU(Y,"utf8"));return J!=null&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}var O$=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshots"),P$=Symbol.for("@cortexkit/openai-auth/opencode-retired-settings-snapshots"),q$=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshot-warnings"),X4=globalThis;X4[O$]??=new Map;X4[P$]??=new Map;X4[q$]??=new Set;var X9=X4[O$],jJ=X4[P$],Z$=X4[q$];function E$(Y,J){let X=a4(Y),$=X9.get(X)??new Set;if($.size===0)s4.delete(X);jJ.delete(X),X9.set(X,$),$.add(J);let Q=J.onChange(()=>{$.delete(J),$.add(J)}),G=!0;return()=>{if(!G)return;if(G=!1,Q(),$.delete(J),$.size===0)X9.delete(X),jJ.set(X,J),s4.delete(X)}}function A$(Y){let J=a4(Y),X=X9.get(J),$=jJ.get(J);for(let Q of X??[])$=Q;if(!$&&!Z$.has(J))Z$.add(J),_$.warn("Holding protection values strict until the shared settings file is read",{configPath:J});return $}function M6(Y,J=_6()){if(y6(J)!=="shared")return Y??{version:1,accounts:[]};return A$(J)?.view(Y)??ZJ("opencode",Y)}function M$(Y){if(y6(Y)!=="shared")return D$(Y);return A$(Y)?.view()??ZJ("opencode")}function r4(Y,J,X){let $=_J(process.env[Y]);if($!==void 0)return $;if(typeof J==="boolean")return J;return X}function pU(Y){let J=process.env[A6.dumpMaxBytes],X=J??Y;if(X===void 0)return $9;let $=J?.trim()?Number(J):X;if(typeof $==="number"&&Number.isSafeInteger($)&&$>=0)return $;if(!L$)L$=!0,_$.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:A6.dumpMaxBytes});return $9}function FJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var S1;function G9(Y=_6()){let J=_J(process.env[A6.dump]);if(J!==void 0)return J;if(y6(Y)==="shared")return r4(A6.dump,FJ(M$(Y)),!1);let X=Y,$;try{$=gU(X)}catch{}if(S1?.path===X&&S1.mtimeMs===$?.mtimeMs&&S1.ctimeMs===$?.ctimeMs&&S1.size===$?.size)return S1.enabled;let Q=r4(A6.dump,FJ(D$(X)),!1);return S1={path:X,mtimeMs:$?.mtimeMs,ctimeMs:$?.ctimeMs,size:$?.size,enabled:Q},Q}function lU(Y){let J=M$(Y);return{webSockets:r4(A6.webSockets,J.webSockets,!1),rawWebSocket:r4(A6.rawWebSocket,J.rawWebSocket,!1),responsesLite:j$(J.responsesLite),dump:r4(A6.dump,FJ(J),!1),dumpDir:process.env[A6.dumpDir]?.trim()||(typeof J.dumpDir==="string"&&J.dumpDir.trim()?J.dumpDir.trim():Q9(mU(),"opencode-openai-auth-dumps")),dumpMaxBytes:pU(J.dumpMaxBytes),codexApiEndpoint:F$(J.codexApiEndpoint)}}var s4=new Map;function T6(Y=_6()){let J=a4(Y),X=y6(Y)==="shared",$=s4.get(J);if(!$||$.shared!==X)$={shared:X,settings:lU(Y)},s4.set(J,$);return $.settings}function T$(Y=_6()){return s4.delete(a4(Y)),S1=void 0,T6(Y)}import{readFileSync as dU}from"node:fs";var iU="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function nU(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function z4(Y,J={}){return Q4({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:$4,...J})}function DJ(Y){try{let J=JSON.parse(dU(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return t4(J).migratedAt!==void 0}catch{return!1}}async function z9(Y,J){if(!DJ(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function W9(Y,J){if(Y===g6)return iU;if(t4(J.config).pending?.rowId===Y)return nU(Y);return}function oU(Y,J){return G4(Y,g6,J.legacyLocks).filter((X)=>X.name===e4)}function o6(Y,J={}){return oU(Y,J)}var W4="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class V1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function R$(Y){let J=Y.storage,X=I1(J);if(!J||!X||c0(X))return;let $=X,Q=Y.now(),G=(M6(J,Y.configPath).refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!$.access||!$.expires||$.expires-Q<=G)&&!r6($.lastRefreshError,$.refresh,Q))try{$=await Y.refreshAccount($,J)}catch(U){Y.warn?.("pool main row refresh failed",{error:U instanceof Error?U.message:String(U)})}let K=$.access?.trim();if(!K)return;if(typeof $.expires!=="number"||$.expires<=Y.now())return;return{account:$,token:K}}import{readFile as k$}from"node:fs/promises";function K9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function x$(Y){let J=await S$(Y.configPath),X=[];try{let Q=JSON.parse(await k$(Y.statePath,"utf8"));if(K9(Q)){let G=Q.accounts;if(K9(G))X=Object.keys(G)}}catch(Q){if(Q.code!=="ENOENT")throw Q}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((Q)=>!J.has(Q)):[]}}async function rU(Y){try{let J=JSON.parse(await k$(Y.configPath,"utf8"));return K9(J)&&K9(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var C$="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function h$(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&n0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>n0(X)&&X.accountId===Y.mainAccountId)}function sU(Y,J){let X=Y.lastRefreshError;return r6(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=w$}function aU(Y){let J=[],X=[],$=Y.now??Date.now(),Q=h$(Y.storage),G=!1;if(c0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${C$}`});else if(t0(Y.auth)){if(!I1(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),G=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),G=!0;else if(Q&&(!Y.auth.refresh||Q.refresh!==Y.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),G=!0;if(G&&Q){let U={type:"restore-main-credential"};X.push(U);let H=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(H)H.repair=U}let z=Y.storage?.accounts??[];if(z.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!z.some((U)=>U.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let U of z){if(!n0(U)||!c0(U))continue;J.push({code:"tombstoned-account",accountId:U.id,message:`Account ${U.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${C$}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let U of z){if(!n0(U))continue;if(!sU(U,$))continue;let H={type:"clear-refresh-backoff",accountId:U.id};X.push(H),J.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:H})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let U={type:"prune-orphan-state-ids",ids:K};X.push(U),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:U})}return{findings:J,repairs:X}}function v$(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(t0(await Y.readAuth()))return;let $=h$(await Y.loadAccounts(Y.paths));if(!$)return;await Y.setMainAuth({refresh:$.refresh,access:$.access??"",expires:$.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts(($)=>$,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts(($)=>{let Q=$.accounts.find((G)=>G.id===X.accountId&&n0(G));if(Q)Q.lastRefreshError=void 0;return $},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,$,Q,G]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),rU(Y.paths)]),z=aU({auth:Q.type==="missing"?void 0:Q,storage:X,orphanStateIds:$.orphanStateIds,retiredCustodyMode:G,now:Y.now()}),K=await Q4({provider:"openai",quota:$4,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(K.status==="ready")for(let U of K.rows){if(U.disabledReason!==I$)continue;z.findings.push({code:"slot-transfer-origin-unknown",accountId:U.id,message:`Account ${U.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${b$}`})}return z.findings.map((U)=>{let H=U.repair?J(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...H?{repair:H}:{}}})}}]}var eU=X5,y$="OpenAI accounts",YH="ChatGPT accounts in the vault",JH="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function XH(){let{redirectUri:Y}=await d$(),J=await u$(),X=c$(crypto.getRandomValues(new Uint8Array(32)).buffer),$=p$(Y,J,X),Q=i$(J,X);return{url:$,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let G=await Q;return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:b1(G)}}finally{l$(X)}}}}async function $H(Y){let{deviceData:J,url:X,instructions:$}=await n$(Y);return{url:X,instructions:$,method:"auto",async callback(){try{let Q=await o$(J,Y);return{type:"success",refresh:Q.refresh_token,access:Q.access_token,expires:Date.now()+(Q.expires_in??3600)*1000,accountId:b1(Q)}}catch{return{type:"failed"}}}}}function z5({client:Y,getAuth:J,getPaths:X=()=>x1(_6()),fetchImpl:$=fetch,packageVersion:Q=f6,dependencies:G,onMainSlotWritten:z,vault:K}){let U={authorizeBrowser:G?.authorizeBrowser??XH,authorizeHeadless:G?.authorizeHeadless??(()=>$H(Q)),beginAccountLogin:G?.beginAccountLogin??B9,loadAccounts:G?.loadAccounts??k1,mutateAccounts:G?.mutateAccounts??V9,readStoreIds:G?.readStoreIds??x$,openBrowser:G?.openBrowser??eU,now:G?.now??Date.now,openAccountPool:G?.openAccountPool??z4,migrationBlockers:G?.migrationBlockers??(async()=>{let q=await H4({currentVersion:Q});return q.open?[]:q.blockers.map((C)=>({pid:C.pid,version:C.version}))}),...G?.terminal?{terminal:G.terminal}:{},...G?.vaultWait?{vaultWait:G.vaultWait}:{}},H=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(K&&await K.authority()!=="local")return!0;if((await H()).type!=="missing")return!0;let q=X(),C=U.openAccountPool(q);if((await C.read()).status==="ready")return e$(C);return((await U.loadAccounts(q))?.accounts.length??0)>0},F=async(q)=>{if(await Q5(X().configPath,async()=>{if(K&&await K.authority()!=="local")return!1;if(t0(await H()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...q}}),!0}))await z?.().catch(()=>{})},Z=(q)=>({begin:async({headless:C,signal:m})=>{if(K&&await K.authority()!=="local")throw Error(K4);let r=await U.beginAccountLogin({version:Q,headless:C,...m?{signal:m}:{}});return{url:r.url,instructions:r.instructions,completion:r.completion.then(async(l)=>{if(K&&await K.authority()!=="local")throw Error(K4);let R0=await q.read(),B0=R0.status==="ready"?R0.rows.find((A0)=>A0.id===g6)?.identity:void 0;if(l.accountId&&B0&&l.accountId===B0)throw Error("that account is already the OpenCode main credential");return{id:l.id,credential:{type:"oauth",refresh:l.refresh,...l.access!==void 0?{access:l.access}:{},...l.expires!==void 0?{expires:l.expires}:{}},...l.accountId!==void 0?{identity:l.accountId}:{},...l.label!==void 0?{label:l.label}:{}}})}},openBrowser:(C)=>U.openBrowser(C)}),N=async(q)=>{if(K&&await K.authority()!=="local")throw Error(K4);let C=q.credential;if(C?.type!=="oauth"||!C.access)throw Error("no usable access token for a quota check");let m=await Y8({accessToken:C.access,fetchImpl:$,now:U.now,...q.identity?{accountId:q.identity}:{},accountKey:q.id});return U4(m,U.now(),!0)},j=(q)=>v$({paths:X(),migrated:q,readAuth:H,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:F,now:U.now}),P=(q,C)=>({title:y$,store:GJ(C,{rowLocks:(m)=>G4(q,m)}),...U.terminal?{terminal:U.terminal}:{},login:Z(C),protect:(m,r)=>W9(m,r),extraLocks:o6(q),pollQuota:N,doctor:j(!0),status:async()=>{if(K&&await K.authority()==="host")return[g$];let m=await K?.status();if(K&&await K.authority()!=="local"&&m)return[PJ(K.host,K.name,m.enrollment)];return[`Routing: ${(await U.loadAccounts(q))?.routing?.mode??"main-first"}`,...K?[PJ(K.host,K.name,(await K.status()).enrollment)]:[]]},...K&&!H9()?{extraActions:[v(K)]}:{}}),v=(q)=>{let C=q.enrolled();return{id:C?"vault-disconnect":"vault-connect",label:C?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(m)=>{let r=await q.authority();if(r==="host"){m.print(f$);return}if(C){if(r!=="local")await q.disconnect();m.print("Disconnected from the Claustrum vault.");return}if(r!=="local"){m.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}m.print(`Asking the Claustrum vault to enroll ${q.name}…`);let l,R0=await q.waitForApproval({...U.vaultWait,onPending:(B0)=>{let z0=B0.state==="pending"?B0.requestId??B0.retryCode??"":B0.state;if(z0===l)return;l=z0;for(let A0 of r$(q.name,B0))m.print(A0);m.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});m.print(s$(q,R0).text)}}},y=async()=>{let q=await U.migrationBlockers();return t$({title:y$,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...q.length>0?["These processes still hold the move back:",...q.map((C)=>` ${C.pid==="unknown"?"processes that could not be read":`pid ${C.pid}`}: version ${C.version}`)]:[]],actions:[a$({checks:j(!1)})],...U.terminal?{terminal:U.terminal}:{}})},I=async(q)=>{let C=X(),m=U.openAccountPool(C);if(K&&await K.authority()!=="local")return U9(P(C,m),K);if(await z9(C,m)===void 0)return y();let r=P(C,m);return K?U9(r,K):Y5(r)},A=(q)=>async()=>{if(K&&await K.authority()!=="local")throw Error(K4);let C=await q();if(C.method!=="auto")return C;return{...C,callback:async()=>{let m=await C.callback();if(K&&await K.authority()!=="local")return{type:"failed"};return m}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:J5({hasCredential:V,openMenu:I,login:A(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:A(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...K?.enrolled()?[{label:YH,type:"oauth",authorize:async()=>({url:"",instructions:JH,method:"auto",callback:async()=>{let q=await m$(K.paths,K.name);if(q!=="vault"&&q!=="host")return{type:"failed"};try{let C=JSON.parse(await tU(G5(),"utf8"));if(!C||typeof C!=="object"||Array.isArray(C)||Object.hasOwn(C,"openai"))return{type:"failed"}}catch(C){if(C.code!=="ENOENT")return{type:"failed"}}return{...$5,type:"success"}}})}]:[]]}var QH=new Set(["title","compaction","summary"]);function K5(Y,J,X){if(X!==null&&QH.has(X))return;W5(Y,J)}class EJ{#Y=new WeakMap;record(Y,{turnID:J,turnStartedAt:X}=Y){if(X!==void 0)this.#Y.set(Y,{turnID:J,turnStartedAt:X})}forAuxiliary(Y,J){let X=this.#Y.get(Y)??{turnID:(J?.uuid??h1)(),turnStartedAt:(J?.now??Date.now)()};return{threadID:Y.threadID,windowID:Y.windowID,...X,pinnedEffort:Y.pinnedEffort,effortUpdates:Y.effortUpdates?.map(($)=>({...$}))}}}var AJ={rpcRoot:"openai-auth",directoryPrefix:V5,registrationSessionId:"process"},N9=new Map;function SD(Y,J){if(J?.aborted)return Promise.resolve(!1);if(MJ(Y))return Promise.resolve(!0);return new Promise((X)=>{let $=(K)=>{if(clearTimeout(G),J?.removeEventListener("abort",Q),z.delete($),z.size===0)N9.delete(Y);X(K)},Q=()=>$(!1),G=setTimeout(()=>$(!1),2000),z=N9.get(Y)??new Set;N9.set(Y,z),z.add($),J?.addEventListener("abort",Q,{once:!0})})}function L9(Y,J){U5(AJ,Y,J)}function N5(Y=0,J){let X=H5(AJ,Y,J);if(J!==void 0)for(let $ of N9.get(J)??[])$(!0);return X}function MJ(Y){return B5(AJ,Y)}var N1=U0("commands");function v1(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function j5(Y){return Y.configPath??v1(Y).configPath}async function J8(Y){let J=Y.settingsSnapshot,X=j5(Y);if(!J||y6(X)!=="shared")return;let $=await d4(X);if($?.decision!=="shared")return;let Q=$.install.target;return{snapshot:J,file:Q,writer:J4(T0,{file:Q,log:N1,separateInstall:!1,createMissing:!0})}}async function CJ(Y,J,X){let $=await J8(Y);if(!$){await X();return}try{if(J.setting==="cache_keep_window"){if(await $.snapshot.refresh(),$.snapshot.report().some((Q)=>Q.reason==="invalid-value"&&Q.keyPath[0]===J.setting||Q.reason==="unreadable"||Q.reason==="unparseable"))throw new w1("settings-invalid-value",$.file)}await $.writer.update([J],{host:"opencode"}),await $.snapshot.refresh()}catch(Q){if(Q instanceof w1)throw new n4(Q.code,J9(Q.code));throw Q}}function TJ(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function GH(Y){let J=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!J)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let X=Number(J[1]),$=Number(J[2]);if(X>23||$>23||X===$)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:$}}var zH="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore enabling sustain with Magic Context, set a non-expiring `cache_ttl` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.";function WH(Y){let J=(X,$,Q)=>CJ(Y,{setting:X,value:$},()=>C1(Y.store(),o6(v1(Y)),(G)=>{let z={...G.cacheKeep??{}};Q(z),G.cacheKeep=z}));return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let $=await J8(Y);await $?.snapshot.refresh();let Q=j9($?$.snapshot.view():await Y.loadAccounts(v1(Y))),G=Q?.enabled===!0,z=Q?.subagents===!0,K=X.status(),U=K.window?TJ(K.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${K.tracked===0?"no sessions":`${K.tracked} session${K.tracked===1?"":"s"}`}`,`Timer ${K.running?"armed":"idle"} · subagents ${z?"on":"off"} · sustain ${K.sustain?"on":"off"}`,`Window ${U}`,...Y.cacheKeepNotice?[Y.cacheKeepNotice]:[],`TTL ${Math.round(K.ttlMs/1000)}s · lead ${Math.round(K.leadMs/1000)}s · idle cap ${Math.round(K.maxIdleWarmMs/60000)}min (subagents ${Math.round(K.maxSubagentIdleMs/60000)}min)`],items:K.targets.map((H)=>({id:H.sessionKey,label:H.sessionKey,group:"Sessions",detail:[H.accountId??"main",`expires in ${Math.ceil((H.cacheExpiresAt-K.generatedAt)/1000)}s`,...H.lastWarmedAt?[`last warm ${Math.ceil((K.generatedAt-H.lastWarmedAt)/1000)}s ago`]:[],...H.backoffUntil&&H.backoffUntil>K.generatedAt?[`backoff ${Math.ceil((H.backoffUntil-K.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:H})=>{let V=H.enabled===!0;if(await J("cache_keep_enabled",V,(F)=>{F.enabled=V}),Y.setCacheKeepEnabled?.(V),V)X.start();else{for(let F of X.status().targets)if(!F9(F.sessionKey,!1))X.remove(F.sessionKey);if(X.status().tracked===0)X.stop()}return N1.info(V?"cachekeep enabled":"cachekeep disabled"),V?`Keep-warm is on. TTL ${Math.round(K.ttlMs/1000)}s, idle cap ${Math.round(K.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:z?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!z}],run:async({values:H})=>{let V=H.subagents===!0;return await J("cache_keep_subagents",V,(F)=>{F.subagents=V}),Y.setCacheKeepSubagents?.(V),`Subagent warming is ${V?"on":"off"}.`}},{id:"sustain",label:K.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!K.sustain}],run:async({values:H})=>{let V=H.sustain===!0;return await J("cache_keep_sustain",V,(F)=>{F.sustain=V}),Y.setCacheKeepSustain?.(V),V?zH:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...K.window?{value:TJ(K.window)}:{}}],run:async({values:H})=>{let V=H.window;if(typeof V!=="string"||V.trim()==="")return await J("cache_keep_window",[],(j)=>{delete j.startHour,delete j.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let F=GH(V);if(!F.ok)return{ok:!1,text:`Invalid window: ${F.reason}`};let{startHour:Z,endHour:N}=F;return await J("cache_keep_window",[{start_hour:Z,end_hour:N}],(j)=>{j.startHour=Z,j.endHour=N}),Y.setCacheKeepWindow?.({startHour:Z,endHour:N}),`Warming limited to ${TJ(F)} local hours.`}}]}}}}var L5=["error","warn","info","debug","trace"];function KH(Y){return{title:"Diagnostics",build:async()=>{let J=j5(Y),X=d4(J)?await K$({configPath:J,snapshot:Y.settingsSnapshot,log:N1}):{lines:[]},$=await J8(Y),Q=T6(J),G=G9(J),K=($?$.snapshot.view():await Y.loadAccounts(v1(Y)).catch(()=>null))?.logging?.level,U=!K||K==="default"?"info":K,H=G?await Z5(Q.dumpDir):void 0,V=H===void 0?"size unavailable":RJ(H),F=Q.dumpMaxBytes===0?"no cap":`${RJ(Q.dumpMaxBytes)} cap`,Z=Y.layoutNotice?.();return{lines:[G?`Dumps on (${V} / ${F})`:"Dumps off",`Dump directory: ${Q.dumpDir}`,`Log level: ${U}`,...Z?[Z]:[],...X.lines],actions:[{id:"dump",label:G?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!G}],run:async({values:N})=>{let j=N.enabled===!0;await CJ(Y,{setting:"request_dumps",value:j},()=>C1(Y.store(),o6(v1(Y)),(v)=>{v.dump={...v.dump??{},enabled:j}}));let P=T$(J);return N1.info(j?"request dump enabled":"request dump disabled"),j?`Request dumps are on, written to ${P.dumpDir}.
|
|
1
|
+
import{$b as Z5,Aa as a$,Ac as nz,Bb as SJ,Cb as MK,Cc as X$,Db as IJ,Dc as LJ,Ec as H4,Fa as t$,Fc as wK,Ga as e$,Gb as U3,Gc as x1,Ha as Y5,Hb as H3,Ia as J5,Ib as B3,Ic as $5,Ja as az,Jc as I$,Ka as K4,Kb as yW,Kc as b$,La as U9,Lc as Q5,Ma as W1,Mb as W5,Mc as SK,Na as GJ,Nc as z3,Oa as C1,Ob as F$,Oc as IK,Pa as zJ,Pb as m1,Pc as t4,Qa as WJ,Qb as $9,Qc as fY,Ra as KJ,Rb as Gz,Rc as PY,Sa as UJ,Sb as I8,Sc as qY,Ta as HJ,Tb as kY,Tc as G4,Ua as gY,Ub as xY,Uc as k5,Va as _K,Vb as h1,Vc as e4,Wa as DK,Wc as W3,Xa as OK,Xc as G5,Ya as PK,Za as kW,Zb as v8,_a as b8,_b as qJ,_c as bK,ac as RJ,bb as j$,cb as _J,cd as kK,da as Q4,db as xW,dc as TK,ea as n4,eb as hW,ec as RK,ed as xK,fa as $K,fb as vW,fc as bJ,fd as hK,ga as e0,gc as yJ,gd as rK,ha as Iz,hb as A7,hd as JW,ia as x5,ib as wJ,ic as uz,id as sK,jb as qK,jc as pz,jd as aK,kc as b7,kd as WW,la as Q0,lc as k7,ma as GW,mc as G3,nc as _9,pc as kJ,qa as ZK,qc as B4,rc as C5,sa as kz,sc as w5,ta as xz,tb as F9,tc as S5,ua as vY,uc as I5,va as yY,vb as EK,vc as b5,wa as zW,xa as r$,xb as h8,xc as lz,ya as PJ,yc as dz,za as s$,zb as AK,zc as iz}from"./index-9kges8jy.js";import{Ad as LW,Bd as gK,Cd as fK,Dd as mK,Id as mY,Jd as cY,Kd as cK,Ld as uK,Od as pK,Pd as lK,Qd as dK,Sd as D9,Td as $8,Ud as iK,Vd as nK,Wd as n1,Xd as oK,od as u7,qd as q5,sd as m6,td as vK,wd as yK}from"./index-nd2ks7er.js";import{$e as c$,$f as c6,Af as p4,Ag as fz,Be as g$,Bf as n8,Bg as mz,Ce as f$,Cf as f3,Cg as cz,De as H9,Df as w1,Ef as J4,Ff as s3,Gf as n6,Hf as a4,If as YW,Jf as y6,Kf as J$,Le as m$,Lf as n0,Mf as s8,Nf as HK,Qf as S$,Rf as k1,Sf as BK,Tf as V9,Ue as w$,Vf as S7,We as X8,Wf as x8,Xe as GK,Xf as I7,Ye as r6,Yf as d1,Ze as Q3,Zf as j9,_e as zK,_f as U1,af as u$,ag as VK,bf as R6,bg as NK,cf as C6,cg as R5,de as p1,df as b1,dg as bz,ef as p$,eg as g6,fe as $4,ff as l$,fg as t0,gf as d$,gg as I1,hf as i$,hg as OJ,if as n$,jf as o$,kf as B9,kg as LK,le as MY,lf as l1,me as Sz,mf as R4,mg as xJ,nf as DY,ng as U4,of as c0,og as U6,pf as WK,pg as b6,qe as C7,qf as k8,qg as hz,rf as Y8,rg as w8,sf as KK,sg as jK,te as Y$,uf as UK,ug as vz,vf as a0,vg as yz,wf as u4,xf as K1,xg as FK,yf as i8,yg as gz,zf as e1,zg as w7}from"./index-x00sxt2w.js";import{Hg as XK,Mg as e3}from"./index-49ncs7dr.js";import{Rg as U5,Sg as H5,Tg as B5,Ug as TW,Vg as QK,Wg as f6,Xg as RW,Yg as CW}from"./index-xkngfyvc.js";import{gh as c7,lh as E4,nh as X5}from"./index-wjp3q15r.js";import{rh as Z9,th as U0}from"./index-td4g5dc9.js";import{Hh as V5,Jh as CK}from"./index-j700j6at.js";import{Lh as cJ}from"./index-q2czrasr.js";import{randomUUID as e7}from"node:crypto";import{statSync as GF}from"node:fs";import Y3 from"node:os";var BJ={hosts:"OpenCode 1, OpenCode 2 and Pi",project:"user-only"},q6={...BJ,overrides:{host:!0}},v6={...BJ,overrides:{host:!0,isolatedHosts:["pi"]}},c4={hosts:"OpenCode 1 only",project:"user-only"},m3=(Y,J)=>Y.flatMap((X)=>J.map(($)=>({source:X,path:$}))),E6=(...Y)=>m3(["opencode-store","pi-store"],Y),i0=(...Y)=>m3(["opencode-store"],Y),T0=f3({plugin:"openai-auth",settings:{routing_mode:{...q6,value:e1(["ordered","main-first","fallback-first","sticky-balanced"]),default:"main-first",legacy:E6(["routing","mode"])},max_same_account_wait:{...q6,value:e1(["off","15m","cache"]),default:"15m",legacy:E6(["routing","maxSameAccountWait"])},wait_for_reset:{...q6,value:a0(),default:!1,legacy:[]},fallback_on:{...q6,hosts:"OpenCode 1 and Pi; not read by OpenCode 2",value:p4(u4()),default:[401,403,429],legacy:E6(["fallbackOn"])},refresh_enabled:{...c4,hosts:"OpenCode 1 legacy fallback refresh only",value:a0(),default:!0,legacy:i0(["refresh","enabled"])},refresh_before_expiry_minutes:{...q6,value:K1(),default:240,legacy:E6(["refresh","refreshBeforeExpiryMinutes"])},quota_enabled:{...q6,value:a0(),default:!0,legacy:E6(["quota","enabled"])},quota_check_interval_minutes:{...c4,hosts:"OpenCode 1 legacy quota freshness and polling only",value:K1({min:1}),default:5,legacy:i0(["quota","checkIntervalMinutes"])},quota_minimum_remaining:{...q6,value:p4(n8({window:e1(["primary","secondary"]),floor:K1()})),default:[],legacy:E6(["quota","minimumRemaining","primary"],["quota","minimumRemaining","5h"],["quota","minimumRemaining","secondary"],["quota","minimumRemaining","1w"])},quota_fail_closed_on_unknown:{...q6,value:a0(),default:!1,legacy:E6(["quota","failClosedOnUnknownQuota"])},cost_zeroing:{...c4,value:a0(),default:!0,legacy:i0(["costZeroing","enabled"])},killswitch_enabled:{...q6,value:a0(),default:!1,legacy:E6(["killswitch","enabled"])},killswitch_default_primary:{...q6,value:K1(),default:5,legacy:E6(["killswitch","defaults","primary"],["killswitch","main","primary"],["killswitch","main","5h"])},killswitch_default_secondary:{...q6,value:K1(),default:10,legacy:E6(["killswitch","defaults","secondary"],["killswitch","main","secondary"],["killswitch","main","1w"])},killswitch_account_floors:{...BJ,value:p4(n8({account:i8(),host:e1(["opencode","pi","both"]),primary:K1(),secondary:K1()})),default:[],legacy:E6(["killswitch","accounts"])},cache_keep_enabled:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","enabled"],["cachekeep","enabled"])},cache_keep_subagents:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","subagents"],["cachekeep","subagents"])},cache_keep_sustain:{...v6,value:a0(),default:!1,legacy:i0(["cacheKeep","sustain"],["cachekeep","sustain"])},cache_keep_window:{...v6,value:p4(n8({start_hour:u4({min:0,max:23}),end_hour:u4({min:0,max:23})})),default:[],legacy:i0(["cacheKeep","startHour"],["cacheKeep","endHour"],["cachekeep","startHour"],["cachekeep","endHour"])},log_level:{...v6,value:e1(["error","warn","info","debug","trace","default"]),default:"default",legacy:i0(["logging","level"])},request_dumps:{...v6,value:a0(),default:!1,legacy:i0(["dump"],["dump","enabled"])},dump_dir:{...v6,value:i8(),default:"",legacy:i0(["dumpDir"])},dump_max_bytes:{...v6,value:u4({min:0,max:Number.MAX_SAFE_INTEGER}),default:536870912,legacy:i0(["dumpMaxBytes"])},web_sockets:{...c4,value:a0(),default:!1,legacy:i0(["webSockets"])},raw_web_socket:{...c4,value:a0(),default:!1,legacy:i0(["rawWebSocket"])},responses_lite:{...v6,value:a0(),default:!1,legacy:i0(["responsesLite"])},codex_api_endpoint:{...v6,value:i8(),default:"https://chatgpt.com/backend-api/codex/responses",legacy:i0(["codexApiEndpoint"])}}});import{chmod as RU,mkdir as CU}from"node:fs/promises";import{join as wU}from"node:path";import{existsSync as p3,readFileSync as ZU}from"node:fs";import{readFileSync as VU}from"node:fs";var c3="Settings moved to ";function NU(Y){let J=Y.split(/\r?\n/,1)[0]??"";if(!J.startsWith(c3)||!J.endsWith("."))return;return J.slice(c3.length,-1)}function LU(Y){try{return NU(VU(`${Y}.MOVED_READPLEASE`,"utf8"))}catch{return}}function u3(Y,J){let X=LU(Y);return X!==void 0&&n6(X)===n6(J)}function jU(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function FU(Y,J){let X=Y;for(let[$,Q]of J.entries()){if(!jU(X)||!Object.hasOwn(X,Q))return!1;if($===J.length-1)return!0;X=X[Q]}return!1}function _U(Y,J){return Object.values(T0.settings).some((X)=>X.legacy.some(($)=>$.source===`${J}-store`&&FU(Y,$.path)))}function DU(Y){try{return _U(JSON.parse(ZU(Y.configPath,"utf8")),Y.host)}catch{return!1}}function o8(Y){let J=p3(Y.target),X=Y.sources.some((K)=>u3(K.configPath,Y.target)),$=Y.sources.filter((K)=>p3(K.configPath)),Q=$.length>0,G=X&&!J,z=J&&!X&&$.some(DU);return{kind:J?"target-exists":X?"target-removed":Q?"move-needed":"no-source",completed:J||X,targetExists:J,noteNamesTarget:X,sourcePresent:Q,preExistingFile:z,removedFile:G}}function r8(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function l3(Y){try{let J=Number(Y);return Number.isFinite(J)?Math.min(100,Math.max(0,J)):0}catch{return 0}}function VJ(Y,J){let X=U1(Y,J);return{primary:l3(X.primary),secondary:l3(X.secondary)}}function d3(Y,J,X,$){if(!r8(Y))return;for(let Q of["primary","secondary","5h","1w"])if(Y[Q]===null)$.push({source:X,key:`${J}.${Q}`,reason:"invalid"})}function i3(Y){let J={entries:[],unmapped:[]},X=[],$=[];Y.forEach((z,K)=>{if(!z.present)return;if(z.host!=="opencode"&&z.host!=="pi")throw Error("Unsupported killswitch floors source host");let U=z.host,H=r8(z.value)?z.value:{},V=r8(H.killswitch)?H.killswitch:void 0,F={killswitch:H.killswitch},Z=V?.schema===s8,N=Z?VJ({killswitch:{...V,accounts:void 0}}):VJ(F);if(X.push({source:K,floors:N}),!Z)d3(V?.main,"killswitch.main",K,J.unmapped);if(!r8(V?.accounts))return;for(let j of Object.keys(V.accounts)){let P=`killswitch.accounts.${j}`;if(!Z&&j==="main"){J.unmapped.push({source:K,key:P,reason:"shadowed"});continue}if(!Z)d3(V.accounts[j],P,K,J.unmapped);$.push({account:j,host:U,...VJ(F,j==="main"?void 0:j)})}});for(let[z,K]of[["primary",5],["secondary",10]]){if(X.every(({floors:U})=>U[z]===K))continue;for(let{source:U,floors:H}of X)J.entries.push({source:U,setting:`killswitch_default_${z}`,value:H[z]})}let Q=[];for(let z of $){let K=z.account.startsWith("vault:")?Q.find((U)=>U.account===z.account&&U.host!==z.host&&U.primary===z.primary&&U.secondary===z.secondary):void 0;if(K)K.host="both";else Q.push(z)}let G=X[0];if(G&&Q.length>0)J.entries.push({source:G.source,setting:"killswitch_account_floors",value:Q});return J}function H1(Y){if(Y===null||typeof Y!=="object"||Array.isArray(Y))return!1;let J=Object.getPrototypeOf(Y);return J===Object.prototype||J===null}function n3(Y){let J;try{J=JSON.parse(Y)}catch{throw Error("Settings source is not JSON")}if(!H1(J))throw Error("Settings source is not an object");return J}function Y4(Y,J){let X=Y;for(let $ of J){if(!H1(X)||!Object.hasOwn(X,$))return;X=X[$]}return X}function l4(Y,J,X=!1){switch(Y.kind){case"boolean":return typeof J==="boolean";case"string":return typeof J==="string";case"integer":case"number":return typeof J==="number"&&Number.isFinite(J)&&(Y.kind!=="integer"||Number.isInteger(J))&&(Y.min===void 0||J>=Y.min)&&(Y.max===void 0||J<=Y.max);case"oneOf":return typeof J==="string"&&Y.values.includes(J);case"list":return Array.isArray(J)&&Array.from(J).every(($)=>l4(Y.item,$,!0));case"object":return H1(J)&&Object.entries(J).every(([$,Q])=>{let G=Y.fields[$];return Object.hasOwn(Y.fields,$)&&G!==void 0&&l4(G,Q,X)})&&(!X||Object.keys(Y.fields).every(($)=>Object.hasOwn(J,$)));case"record":return H1(J)&&Object.values(J).every(($)=>l4(Y.value,$,!0))}}class t8 extends Error{setting;key;constructor(Y,J){super(`Cannot move setting ${Y}${J?` (${J})`:""}`);this.setting=Y;this.key=J;this.name="CannotMoveSettingError"}}function a8(Y,J){throw new t8(Y,J)}function o3(Y,J,X){try{let $=Number(Y);if(Number.isFinite($))return $}catch{}return a8(J,X)}function OU(Y,J){let X=[];for(let[$,Q]of[["primary","5h"],["secondary","1w"]]){let G=["quota","minimumRemaining"],z=Y4(Y,[...G,$]),K=Y4(Y,[...G,Q]);for(let[H,V]of[[$,z],[Q,K]])if(V===null)J([...G,H].join("."),"invalid");if(z!=null&&K!=null)J([...G,Q].join("."),"shadowed");let U=z??K;if(U==null)continue;X.push({window:$,floor:o3(U,"quota_minimum_remaining",[...G,$].join("."))})}return X}function PU(Y,J,X){let $=Y4(Y,[J,"startHour"]),Q=Y4(Y,[J,"endHour"]);if($===void 0&&Q===void 0)return[];let G,z;try{G=Number($),z=Number(Q)}catch{G=Number.NaN,z=Number.NaN}if(Number.isInteger(G)&&G>=0&&G<=23&&Number.isInteger(z)&&z>=0&&z<=23&&G!==z)return[{start_hour:G,end_hour:z}];if($!==void 0)X(`${J}.startHour`,"invalid");if(Q!==void 0)X(`${J}.endHour`,"invalid");return[]}function qU(Y,J,X){let $=T0.settings[Y],Q=$.default;if(Y==="quota_minimum_remaining")return OU(J,X);let G=H1(J.cacheKeep)?"cacheKeep":"cachekeep";if(Y==="cache_keep_window")return PU(J,G,X);let z=$.legacy[0];if(!z)return a8(Y);let K=z.path;if(Y.startsWith("cache_keep_"))K=[G,...K.slice(1)];if(Y==="request_dumps")K=typeof J.dump==="boolean"?["dump"]:["dump","enabled"];let U=Y4(J,K),H=K.join(".");if(U===void 0)return Q;if(Y==="max_same_account_wait"){if(U===0)return"off";if(U===15)return"15m";if(U==="max")return"cache"}else if(Y==="fallback_on"){if(Array.isArray(U)){let V=U.filter((F)=>Number.isInteger(F));if(V.length!==U.length)X(H,"invalid");return V.length?V:Q}}else if(Y==="refresh_before_expiry_minutes"||Y==="quota_check_interval_minutes"){if(U!=null){let V=o3(U,Y,H);return Y==="quota_check_interval_minutes"?Math.max(1,V):V}}else if(Y==="quota_fail_closed_on_unknown"){if(U!=null)return Boolean(U)}else if(Y==="dump_dir"||Y==="codex_api_endpoint"){if(typeof U==="string"&&U.trim())return U.trim()}else if(l4($.value,U))return U;return X(H,"invalid"),Q}var EU=new Set(["version","accounts","main","commonAuthPool","commonAuthLimits","openaiAuthPool","mainAccountId","reset","claustrum"]),AU=new Set(["refresh.mainLastRefreshError","refresh.mainRefreshLeaseId","refresh.mainRefreshLeaseUntil","refresh.mainRefreshLeaseTokenHash","quota.mainQuota","quota.mainQuotaCheckedAt","quota.mainQuotaToken","quota.mainLastQuotaApiError"]);function MU(Y,J,X){let $=new Set;for(let G of Object.values(T0.settings))for(let z of G.legacy){let K=z.path.join(".");if($.add(K),J==="pi"&&!G.legacy.some((U)=>U.source==="pi-store")&&Y4(Y,z.path)!==void 0){if(K==="dump.enabled"&&Object.hasOwn(Y,"dump"))continue;X(K,"other-host")}}let Q=(G,z="")=>{for(let[K,U]of Object.entries(G)){let H=z?`${z}.${K}`:K;if(!z&&EU.has(K)||AU.has(H)||H==="killswitch.schema")continue;if($.has(H))continue;if([...$].some((V)=>V.startsWith(`${H}.`)))if(H1(U))Q(U,H);else X(H,"invalid");else X(H,"retired")}};if(Q(Y),J==="opencode"&&H1(Y.cacheKeep)&&Y.cachekeep!==void 0)X("cachekeep","shadowed")}function r3(Y){let J={entries:[],unmapped:[]},X=Y.flatMap((Q,G)=>{if(!Q.present)return[];if(Q.host!=="opencode"&&Q.host!=="pi")throw Error("Unsupported settings source host");if(!H1(Q.value))throw Error("Settings source is not an object");let z=(K,U)=>{if(!J.unmapped.some((H)=>H.source===G&&H.key===K&&H.reason===U))J.unmapped.push({source:G,key:K,reason:U})};return MU(Q.value,Q.host,z),[{source:G,host:Q.host,store:Q.value,report:z}]});for(let Q of Object.keys(T0.settings)){if(Q.startsWith("killswitch_default_")||Q==="killswitch_account_floors")continue;let G=T0.settings[Q],z=X.filter((K)=>G.legacy.some((U)=>U.source===`${K.host}-store`)).map((K)=>({source:K.source,value:qU(Q,K.store,K.report)}));if(z.every((K)=>JSON.stringify(K.value)===JSON.stringify(G.default)))continue;for(let K of z)J.entries.push({...K,setting:Q})}let $=i3(Y);J.entries.push(...$.entries),J.unmapped.push(...$.unmapped);for(let Q of J.entries){if(!Object.hasOwn(T0.settings,Q.setting))a8(Q.setting);if(!l4(T0.settings[Q.setting].value,Q.value))a8(Q.setting)}return J}class NJ extends Error{host;path;code;constructor(Y,J,X){super(`Settings source ${Y} ${J}: ${X}`);this.host=Y;this.path=J;this.code=X}}function a3(Y){let J=Y?.code;return typeof J==="string"&&/^[A-Z][A-Z0-9_]*$/.test(J)?J:"SETTINGS_MOVE_FAILED"}function TU(Y,J){if(Y instanceof NJ)return{kind:"cause",host:Y.host,path:Y.path,code:Y.code};if(Y instanceof t8)return{kind:"setting",setting:Y.setting};let X=Y?.path,$=J.find((G)=>G.path===X),Q=a3(Y);if($)return{kind:"cause",host:$.host,path:$.path,code:Q};return{kind:"cause",code:Q}}async function t3({install:Y,fence:J,log:X}){if(Y.separate||Y.sources.length===0)return;let $=[...Y.sources].sort((G,z)=>Number(G.host==="pi")-Number(z.host==="pi")).map((G)=>({host:G.host,path:G.configPath,locks:[{path:G.configPath,name:"save"},{path:G.statePath,name:"save"}],read(z){try{return n3(z)}catch(K){throw new NJ(G.host,G.configPath,K instanceof Error&&K.message==="Settings source is not JSON"?"SOURCE_NOT_JSON":"SOURCE_NOT_OBJECT")}}})),Q=await s3({definition:T0,target:Y.target,separateInstall:!1,sources:$,map:r3,fence:J,log:{warn(){},info(){}}});for(let G of Q.unmapped)X.warn(`Settings move: ${$[G.source]?.host??"unknown"} ${G.key}: ${G.reason}`);for(let G of Q.noteFailures){let z=$.find((K)=>`${K.path}.MOVED_READPLEASE`===G.path);X.warn(`Settings move note: ${z?.host??"unknown"} ${G.path}: ${a3(G.error)}`)}if(Q.outcome==="failed"){Q.failure=TU(Q.cause,$);let G=Q.failure;X.warn(G.kind==="setting"?`Settings move failed: cannot move setting ${G.setting}`:("host"in G)?`Settings move failed: ${G.host} ${G.path}: ${G.code}`:`Settings move failed: ${G.code}`)}return Q}class Y9 extends Error{folder;constructor(Y,J){let X=J instanceof Error?J.message:String(J);super(`Cannot record settings authority in ${Y}: ${X}`,{cause:J});this.folder=Y;this.name="SettingsAuthorityRefusal"}}var $$=Symbol.for("@cortexkit/openai-auth/settings-authority"),Q$=globalThis,e8=Q$[$$]??new Map;Q$[$$]=e8;function d4(Y){return e8.get(n6(Y))}function G$(Y){let J=n6(Y.install.configIdentity),X=e8.get(J);if(X)return X;let $=Promise.resolve().then(()=>SU(Y));return e8.set(J,$),$}async function SU({install:Y,stateHome:J,record:X,log:$,fenceOptions:Q}){let G={decision:Y.separate?"separate":"shared",install:Y,ranMove:!1},z=()=>{return J$(Y.configIdentity,G.decision),G};if(Y.separate){try{await X("separate")}catch{}return z()}let K=X$(J),U=()=>{return G.completion=o8(Y),G.completion},H=(V)=>V.completed||!V.sourcePresent;try{return await CU(K,{recursive:!0,mode:448}),await RU(K,448),await e3(wU(K,"settings-authority"),{name:"settings-authority",...Y$},async(V)=>{if(!H(U()))if(G.fence=await LJ({...Q,stateHome:J}),G.fence.open){G.ranMove=!0;try{G.move=await t3({install:Y,log:$,async fence(){let N=await LJ({...Q,stateHome:J});if(!N.open)G.fence=N;return N.open}})}catch(N){G.move={outcome:"failed",cause:N,unmapped:[],differing:[],noteFailures:[],postPublishFailures:[],failure:{kind:"cause",code:"SETTINGS_MOVE_FAILED"}}}let F=G.move?.outcome,Z=U();G.decision=F==="moved"||F==="done-already"||F==="aborted-target-appeared"||Z.completed?"shared":"legacy"}else G.decision="legacy";await V.assertOwned(),await X(G.decision)}),z()}catch(V){if(!H(U()))throw new Y9(K,V);return G.decision="shared",z()}}var B1=Object.freeze({file:(Y)=>`Settings file: ${Y}`,separate:"Settings stay in this install's account store.",legacyProcess:"Settings stay in the old account store because another process still uses it.",legacyBusy:"Settings stay in the old account store because the stores were busy.",legacySetting:(Y)=>`Settings stay in the old account store because ${Y} couldn't be moved.`,legacyFailed:(Y)=>`Settings stay in the old account store because the move failed: ${Y}.`,sharedMissing:"No settings file, so defaults are in use.",sharedMoved:"Settings were moved to the settings file in this process.",sharedFound:"Settings file found.",waitForResetOn:"wait_for_reset is on: when every account is at a usage limit with a known reset, the turn waits for the reset.",preExistingFile:(Y)=>`Settings come from ${Y}. Preferences in the old account store weren't copied, because this file already existed.`,removedFile:(Y)=>`The settings file ${Y} was removed, so defaults are in use. Old preferences aren't copied again.`,refused:(Y,J)=>`openai-auth didn't start. Process records folder: ${Y}. Cause: ${J}`,report:{"unknown-key":(Y)=>`Unknown settings key: ${Y}.`,"override-not-allowed":(Y)=>`Settings override not allowed: ${Y}.`,"user-only-in-project":(Y)=>`User-only setting found in a project file: ${Y}.`,"invalid-value":(Y)=>`Invalid settings value: ${Y}.`,"invalid-schema-version":(Y)=>`Invalid settings schema version: ${Y}.`,"newer-version-key-ignored":(Y)=>`Settings key from a newer version ignored: ${Y}.`,"duplicate-key":(Y)=>`Duplicate settings key: ${Y}.`,unparseable:(Y)=>`The settings file ${Y} can't be parsed.`,unreadable:(Y)=>`The settings file ${Y} can't be read.`},checks:{duplicateFloors:"Invalid killswitch_account_floors: duplicate account and host pair.",localBoth:"Invalid killswitch_account_floors: only vault accounts may use host both.",duplicateQuota:"Invalid quota_minimum_remaining: duplicate quota window.",warmWindow:"Invalid cache_keep_window: use at most one window with unequal hours."},refusal:{"settings-unparseable":"The settings file can't be read. Fix it or remove it, then try again.","settings-newer-version":"The settings file is from a newer openai-auth. Update openai-auth to change settings.","settings-invalid-value":"That value isn't allowed for this setting.","settings-busy":"The settings file is busy. Try again.","settings-unavailable":"Settings can't be saved for this install."}});function J9(Y){return B1.refusal[Y]}function IU(Y){let J=B1;if(Y.reason==="invalid-value"&&Y.keyPath.length===1)switch(Y.keyPath[0]){case"killswitch_account_floors":if(Y.detail==="Duplicate account and host pair")return J.checks.duplicateFloors;if(Y.detail==="Only vault accounts may use host both")return J.checks.localBoth;break;case"quota_minimum_remaining":if(Y.detail==="Duplicate quota window")return J.checks.duplicateQuota;break;case"cache_keep_window":if(Y.detail==="Use at most one window with unequal hours")return J.checks.warmWindow}let X=Y.reason==="unparseable"||Y.reason==="unreadable"?Y.file.path:Y.keyPath.length?Y.keyPath.join("."):Y.file.path;return J.report[Y.reason](X)}function bU(Y,J,X=!1){let $=B1;if(Y.decision==="separate")return $.separate;if(Y.decision==="shared"){if(!J?.targetExists)return $.sharedMissing;return Y.ranMove&&Y.move?.outcome==="moved"&&!X?$.sharedMoved:$.sharedFound}if(Y.move?.outcome==="busy")return $.legacyBusy;if(Y.move?.outcome==="fence-closed"||Y.fence?.open===!1)return $.legacyProcess;let Q=Y.move?.failure;if(Q?.kind==="setting")return $.legacySetting(Q.setting);let G=Q?.kind==="cause"?"path"in Q?`${Q.host} ${Q.path}: ${Q.code}`:Q.code:"SETTINGS_MOVE_FAILED";return $.legacyFailed(G)}var z$=Symbol.for("@cortexkit/openai-auth/settings-diagnostics"),W$=globalThis,i4=W$[z$]??{logged:new Set,sawTargetMissing:new Set};W$[z$]=i4;async function K$({configPath:Y,snapshot:J,log:X}){let $=d4(Y);if(!$)throw Error("Settings authority has not been decided");let Q;try{Q=await $}catch(U){if(U instanceof Y9||U instanceof Error&&U.name==="SettingsAuthorityRefusal"&&"folder"in U&&typeof U.folder==="string"){let H=U.cause;return{lines:[B1.refused(String(U.folder),H instanceof Error?H.message:String(H))]}}throw U}if(Q.decision==="separate")return{lines:[B1.separate]};let G=Q.decision==="shared"?o8(Q.install):Q.completion,z=n6(Q.install.target);if(Q.decision==="shared"&&!G?.targetExists)i4.sawTargetMissing.add(z);let K=[B1.file(Q.install.target),bU(Q,G,i4.sawTargetMissing.has(z))];if(Q.decision==="shared"&&G){for(let U of["preExistingFile","removedFile"]){if(!G[U])continue;let H=B1[U](Q.install.target);K.push(H);let V=`${U}:${n6(Q.install.target)}`;if(!i4.logged.has(V))i4.logged.add(V),X.warn(H)}if(await J?.refresh(),K.push(...J?.report().map(IU)??[]),J?.get("wait_for_reset"))K.push(B1.waitForResetOn)}return{lines:K}}var m0=(Y)=>Q0(Y)?Y:{},kU=["primary","secondary"];function U$(Y){let{routing:J,killswitch:X}=Y.view(),$=Object.fromEntries(Object.entries(X?.accounts??{}).map(([Q,G])=>[Q,Object.fromEntries(Object.entries(m0(G)).filter(([,z])=>z!==0))]));for(let{account:Q}of Y.get("killswitch_account_floors"))if(!Object.hasOwn($,Q))Object.defineProperty($,Q,{value:{},enumerable:!0,writable:!0,configurable:!0});return{routing:J,killswitch:{...X,accounts:$}}}function xU(Y){let J=new Map,X=(K,U)=>{let H=J.get(K)??new Set;H.add(U),J.set(K,H)},$=!1,Q=!0,G=(K,U=!1)=>{if(!Q)return;if(K[0]!=="killswitch"||K[1]!=="accounts")return;$=!0;let[,,H,V]=K;if(U&&H!==void 0&&(V==="primary"||V==="secondary"))X(H,V)},z=(K,U)=>new Proxy(K,{ownKeys(H){return G(U),Reflect.ownKeys(H)},get(H,V){let F=Reflect.get(H,V);return typeof V==="string"&&Q0(F)?z(F,[...U,V]):F},set(H,V,F){if(typeof V==="string")G([...U,V],!0);return Reflect.set(H,V,F)},deleteProperty(H,V){if(typeof V==="string")G([...U,V],!0);return Reflect.deleteProperty(H,V)}});return{value:z(Y,[]),windows:J,add:X,touched:()=>$,finish:()=>{Q=!1}}}function o4(Y){let{host:J,snapshot:X}=Y,$=Y.writer??J4(T0,{file:Y.file,log:Y.log,separateInstall:!1,createMissing:!0});return{async read(){return await X.refresh(),U$(X)},async update(Q){try{await X.refresh();let G=U$(X),z=xU(structuredClone(G)),K=await Q(z.value)??z.value;z.finish();let U=JSON.parse(JSON.stringify(K)),H=[],V=m0(U.routing),F=m0(G.routing);if(V.mode!==F.mode)H.push({setting:"routing_mode",value:V.mode});if(V.maxSameAccountWait!==F.maxSameAccountWait)H.push({setting:"max_same_account_wait",value:V.maxSameAccountWait===0?"off":V.maxSameAccountWait==="max"?"cache":"15m"});let Z=m0(U.killswitch);if(Z.enabled!==m0(G.killswitch).enabled)H.push({setting:"killswitch_enabled",value:Z.enabled});let N=m0(m0(G.killswitch).accounts),j=m0(Z.accounts);for(let v of new Set([...Object.keys(N),...Object.keys(j)])){let y=Object.hasOwn(N,v)&&!Object.hasOwn(j,v)&&!z.windows.has(v);for(let I of kU)if(y||!Object.is(m0(N[v])[I],m0(j[v])[I]))z.add(v,I)}let P=z.touched()||z.windows.size>0;if(P){if(X.report().some((v)=>v.keyPath[0]==="killswitch_account_floors"||v.reason==="unreadable"||v.reason==="unparseable"))throw new w1("settings-invalid-value",Y.file)}await $.update((v)=>{let y=[...H];if(P){let I=v.status==="ready"&&Object.hasOwn(v.document,"killswitch_account_floors")?v.document.killswitch_account_floors:T0.settings.killswitch_account_floors.default;if(!Array.isArray(I))throw new w1("settings-invalid-value",Y.file);let A=I;for(let[q,C]of z.windows){let m=q.startsWith("vault:"),r=(f)=>m0(f).account===q,l=m0(A.find((f)=>r(f)&&m0(f).host===J)??(m?A.find((f)=>r(f)&&m0(f).host==="both"):void 0));A=A.filter((f)=>!r(f)||!m&&m0(f).host!==J);let R0=m0(j[q]),B0=(f)=>{if(C.has(f))return R0[f];let V0=l[f];return V0===0?void 0:V0},z0=B0("primary"),A0=B0("secondary");if(z0!==void 0||A0!==void 0)A.push({account:q,host:m?"both":J,primary:z0??0,secondary:A0??0})}y.push({setting:"killswitch_account_floors",value:A})}return y},{host:J}),await X.refresh()}catch(G){if(G instanceof w1)throw new n4(G.code,J9(G.code));throw G}}}}import{readFile as tU}from"node:fs/promises";import{readFileSync as yU,statSync as gU}from"node:fs";import{homedir as fU,tmpdir as mU}from"node:os";import{join as Q9}from"node:path";var hU=["killswitch_enabled","killswitch_default_primary","killswitch_default_secondary","killswitch_account_floors","quota_minimum_remaining","cache_keep_window"];function H$(Y,J){return structuredClone(J&&Y==="killswitch_enabled"?!0:T0.settings[Y].default)}function vU(Y,J){let X=[],$=(U,H)=>{X.push({file:{kind:"user",path:J},keyPath:[U],reason:"invalid-value",detail:H})},Q=Y.killswitch_account_floors,G=Q.map(({account:U,host:H})=>JSON.stringify([U,H]));if(new Set(G).size!==G.length)$("killswitch_account_floors","Duplicate account and host pair");if(Q.some(({account:U,host:H})=>H==="both"&&!U.startsWith("vault:")))$("killswitch_account_floors","Only vault accounts may use host both");let z=Y.quota_minimum_remaining.map(({window:U})=>U);if(new Set(z).size!==z.length)$("quota_minimum_remaining","Duplicate quota window");let K=Y.cache_keep_window;if(K.length>1||K.some(({start_hour:U,end_hour:H})=>U===H))$("cache_keep_window","Use at most one window with unequal hours");return X}function B$(Y,J){let X=Y.killswitch_account_floors,$=Object.fromEntries([...X.filter((G)=>G.host==="both"),...X.filter((G)=>G.host===J)].map(({account:G,primary:z,secondary:K})=>[G,{primary:z,secondary:K}])),Q=Y.cache_keep_window[0];return{version:1,accounts:[],routing:{mode:Y.routing_mode,maxSameAccountWait:{off:0,"15m":15,cache:"max"}[Y.max_same_account_wait]},waitForReset:Y.wait_for_reset,fallbackOn:Y.fallback_on,refresh:{enabled:Y.refresh_enabled,refreshBeforeExpiryMinutes:Y.refresh_before_expiry_minutes},quota:{enabled:Y.quota_enabled,checkIntervalMinutes:Y.quota_check_interval_minutes,minimumRemaining:Object.fromEntries(Y.quota_minimum_remaining.map(({window:G,floor:z})=>[G,z])),failClosedOnUnknownQuota:Y.quota_fail_closed_on_unknown},costZeroing:{enabled:Y.cost_zeroing},killswitch:{schema:s8,enabled:Y.killswitch_enabled,defaults:{primary:Y.killswitch_default_primary,secondary:Y.killswitch_default_secondary},accounts:$},logging:{level:Y.log_level==="default"?void 0:Y.log_level},cachekeep:void 0,cacheKeep:{enabled:Y.cache_keep_enabled,subagents:Y.cache_keep_subagents,sustain:Y.cache_keep_sustain,startHour:Q?.start_hour,endHour:Q?.end_hour},dump:{enabled:Y.request_dumps},dumpDir:Y.dump_dir,dumpMaxBytes:Y.dump_max_bytes,webSockets:Y.web_sockets,rawWebSocket:Y.raw_web_socket,responsesLite:Y.responses_lite,codexApiEndpoint:Y.codex_api_endpoint}}function V$(Y,J){return{...J,...Y,accounts:J?.accounts??[],main:J?.main,refresh:{...Y.refresh,mainLastRefreshError:J?.refresh?.mainLastRefreshError,mainRefreshLeaseId:J?.refresh?.mainRefreshLeaseId,mainRefreshLeaseUntil:J?.refresh?.mainRefreshLeaseUntil,mainRefreshLeaseTokenHash:J?.refresh?.mainRefreshLeaseTokenHash},quota:{...Y.quota,mainQuota:J?.quota?.mainQuota,mainQuotaCheckedAt:J?.quota?.mainQuotaCheckedAt,mainQuotaToken:J?.quota?.mainQuotaToken,mainLastQuotaApiError:J?.quota?.mainLastQuotaApiError}}}function ZJ(Y,J){let X=Object.fromEntries(Object.keys(T0.settings).map(($)=>[$,H$($,!0)]));return V$(B$(X,Y),J)}async function N$(Y){let{handle:J,host:X,file:$}=Y,Q,G,z=[],K=!1,U=Promise.resolve(),H=new Set,V=async()=>{if(K)return;if(await J.read(),K)return;let N=Object.fromEntries(await Promise.all(Object.keys(T0.settings).map(async(A)=>[A,await J.get(A,{host:X})])));if(K)return;let j=J.report(),P=vU(N,$);z=[...j,...P];let v=j.some((A)=>A.file.path===$&&(A.reason==="unreadable"||A.reason==="unparseable")),y=(A)=>P.some((q)=>q.keyPath[0]===A)||j.some((q)=>{if(q.reason!=="invalid-value"||q.keyPath[0]!==A)return!1;if(A==="cache_keep_window")return X==="pi"===(q.keyPath[1]==="pi");return!0}),I=(A)=>{N[A]=Q?structuredClone(Q[A]):H$(A,v)};for(let A of hU)if(v||y(A))I(A);if(y("killswitch_account_floors"))N.killswitch_default_primary=Q?.killswitch_default_primary??N.killswitch_default_primary,N.killswitch_default_secondary=Q?.killswitch_default_secondary??N.killswitch_default_secondary;if(Q=N,G=B$(N,X),!K)for(let A of H)A()},F=()=>{return U=U.then(V,V),U},Z=J.watch(()=>{F()});try{await F()}catch(N){throw Z(),N}return{view(N){return V$(structuredClone(G),N)},get(N){return structuredClone(Q[N])},report(){return structuredClone(z)},refresh:F,onChange(N){return H.add(N),()=>{H.delete(N)}},dispose(){K=!0,Z(),H.clear()}}}var _$=U0("config"),L$=!1,cU="openai-auth.json",A6={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function uU(){let Y=process.env[A6.configDir]?.trim();if(Y)return Y;return Q9(process.env.XDG_CONFIG_HOME||Q9(fU(),".config"),"opencode")}function _6(){return process.env[A6.configFile]?.trim()||Q9(uU(),cU)}function D$(Y){try{let J=JSON.parse(yU(Y,"utf8"));return J!=null&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}var O$=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshots"),P$=Symbol.for("@cortexkit/openai-auth/opencode-retired-settings-snapshots"),q$=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshot-warnings"),X4=globalThis;X4[O$]??=new Map;X4[P$]??=new Map;X4[q$]??=new Set;var X9=X4[O$],jJ=X4[P$],Z$=X4[q$];function E$(Y,J){let X=a4(Y),$=X9.get(X)??new Set;if($.size===0)s4.delete(X);jJ.delete(X),X9.set(X,$),$.add(J);let Q=J.onChange(()=>{$.delete(J),$.add(J)}),G=!0;return()=>{if(!G)return;if(G=!1,Q(),$.delete(J),$.size===0)X9.delete(X),jJ.set(X,J),s4.delete(X)}}function A$(Y){let J=a4(Y),X=X9.get(J),$=jJ.get(J);for(let Q of X??[])$=Q;if(!$&&!Z$.has(J))Z$.add(J),_$.warn("Holding protection values strict until the shared settings file is read",{configPath:J});return $}function M6(Y,J=_6()){if(y6(J)!=="shared")return Y??{version:1,accounts:[]};return A$(J)?.view(Y)??ZJ("opencode",Y)}function M$(Y){if(y6(Y)!=="shared")return D$(Y);return A$(Y)?.view()??ZJ("opencode")}function r4(Y,J,X){let $=_J(process.env[Y]);if($!==void 0)return $;if(typeof J==="boolean")return J;return X}function pU(Y){let J=process.env[A6.dumpMaxBytes],X=J??Y;if(X===void 0)return $9;let $=J?.trim()?Number(J):X;if(typeof $==="number"&&Number.isSafeInteger($)&&$>=0)return $;if(!L$)L$=!0,_$.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:A6.dumpMaxBytes});return $9}function FJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var S1;function G9(Y=_6()){let J=_J(process.env[A6.dump]);if(J!==void 0)return J;if(y6(Y)==="shared")return r4(A6.dump,FJ(M$(Y)),!1);let X=Y,$;try{$=gU(X)}catch{}if(S1?.path===X&&S1.mtimeMs===$?.mtimeMs&&S1.ctimeMs===$?.ctimeMs&&S1.size===$?.size)return S1.enabled;let Q=r4(A6.dump,FJ(D$(X)),!1);return S1={path:X,mtimeMs:$?.mtimeMs,ctimeMs:$?.ctimeMs,size:$?.size,enabled:Q},Q}function lU(Y){let J=M$(Y);return{webSockets:r4(A6.webSockets,J.webSockets,!1),rawWebSocket:r4(A6.rawWebSocket,J.rawWebSocket,!1),responsesLite:j$(J.responsesLite),dump:r4(A6.dump,FJ(J),!1),dumpDir:process.env[A6.dumpDir]?.trim()||(typeof J.dumpDir==="string"&&J.dumpDir.trim()?J.dumpDir.trim():Q9(mU(),"opencode-openai-auth-dumps")),dumpMaxBytes:pU(J.dumpMaxBytes),codexApiEndpoint:F$(J.codexApiEndpoint)}}var s4=new Map;function T6(Y=_6()){let J=a4(Y),X=y6(Y)==="shared",$=s4.get(J);if(!$||$.shared!==X)$={shared:X,settings:lU(Y)},s4.set(J,$);return $.settings}function T$(Y=_6()){return s4.delete(a4(Y)),S1=void 0,T6(Y)}import{readFileSync as dU}from"node:fs";var iU="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function nU(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function z4(Y,J={}){return Q4({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:$4,...J})}function DJ(Y){try{let J=JSON.parse(dU(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return t4(J).migratedAt!==void 0}catch{return!1}}async function z9(Y,J){if(!DJ(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function W9(Y,J){if(Y===g6)return iU;if(t4(J.config).pending?.rowId===Y)return nU(Y);return}function oU(Y,J){return G4(Y,g6,J.legacyLocks).filter((X)=>X.name===e4)}function o6(Y,J={}){return oU(Y,J)}var W4="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class V1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function R$(Y){let J=Y.storage,X=I1(J);if(!J||!X||c0(X))return;let $=X,Q=Y.now(),G=(M6(J,Y.configPath).refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!$.access||!$.expires||$.expires-Q<=G)&&!r6($.lastRefreshError,$.refresh,Q))try{$=await Y.refreshAccount($,J)}catch(U){Y.warn?.("pool main row refresh failed",{error:U instanceof Error?U.message:String(U)})}let K=$.access?.trim();if(!K)return;if(typeof $.expires!=="number"||$.expires<=Y.now())return;return{account:$,token:K}}import{readFile as k$}from"node:fs/promises";function K9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function x$(Y){let J=await S$(Y.configPath),X=[];try{let Q=JSON.parse(await k$(Y.statePath,"utf8"));if(K9(Q)){let G=Q.accounts;if(K9(G))X=Object.keys(G)}}catch(Q){if(Q.code!=="ENOENT")throw Q}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((Q)=>!J.has(Q)):[]}}async function rU(Y){try{let J=JSON.parse(await k$(Y.configPath,"utf8"));return K9(J)&&K9(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var C$="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function h$(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&n0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>n0(X)&&X.accountId===Y.mainAccountId)}function sU(Y,J){let X=Y.lastRefreshError;return r6(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=w$}function aU(Y){let J=[],X=[],$=Y.now??Date.now(),Q=h$(Y.storage),G=!1;if(c0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${C$}`});else if(t0(Y.auth)){if(!I1(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),G=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),G=!0;else if(Q&&(!Y.auth.refresh||Q.refresh!==Y.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),G=!0;if(G&&Q){let U={type:"restore-main-credential"};X.push(U);let H=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(H)H.repair=U}let z=Y.storage?.accounts??[];if(z.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!z.some((U)=>U.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let U of z){if(!n0(U)||!c0(U))continue;J.push({code:"tombstoned-account",accountId:U.id,message:`Account ${U.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${C$}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let U of z){if(!n0(U))continue;if(!sU(U,$))continue;let H={type:"clear-refresh-backoff",accountId:U.id};X.push(H),J.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:H})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let U={type:"prune-orphan-state-ids",ids:K};X.push(U),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:U})}return{findings:J,repairs:X}}function v$(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(t0(await Y.readAuth()))return;let $=h$(await Y.loadAccounts(Y.paths));if(!$)return;await Y.setMainAuth({refresh:$.refresh,access:$.access??"",expires:$.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts(($)=>$,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts(($)=>{let Q=$.accounts.find((G)=>G.id===X.accountId&&n0(G));if(Q)Q.lastRefreshError=void 0;return $},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,$,Q,G]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),rU(Y.paths)]),z=aU({auth:Q.type==="missing"?void 0:Q,storage:X,orphanStateIds:$.orphanStateIds,retiredCustodyMode:G,now:Y.now()}),K=await Q4({provider:"openai",quota:$4,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(K.status==="ready")for(let U of K.rows){if(U.disabledReason!==I$)continue;z.findings.push({code:"slot-transfer-origin-unknown",accountId:U.id,message:`Account ${U.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${b$}`})}return z.findings.map((U)=>{let H=U.repair?J(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...H?{repair:H}:{}}})}}]}var eU=X5,y$="OpenAI accounts",YH="ChatGPT accounts in the vault",JH="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function XH(){let{redirectUri:Y}=await d$(),J=await u$(),X=c$(crypto.getRandomValues(new Uint8Array(32)).buffer),$=p$(Y,J,X),Q=i$(J,X);return{url:$,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let G=await Q;return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:b1(G)}}finally{l$(X)}}}}async function $H(Y){let{deviceData:J,url:X,instructions:$}=await n$(Y);return{url:X,instructions:$,method:"auto",async callback(){try{let Q=await o$(J,Y);return{type:"success",refresh:Q.refresh_token,access:Q.access_token,expires:Date.now()+(Q.expires_in??3600)*1000,accountId:b1(Q)}}catch{return{type:"failed"}}}}}function z5({client:Y,getAuth:J,getPaths:X=()=>x1(_6()),fetchImpl:$=fetch,packageVersion:Q=f6,dependencies:G,onMainSlotWritten:z,vault:K}){let U={authorizeBrowser:G?.authorizeBrowser??XH,authorizeHeadless:G?.authorizeHeadless??(()=>$H(Q)),beginAccountLogin:G?.beginAccountLogin??B9,loadAccounts:G?.loadAccounts??k1,mutateAccounts:G?.mutateAccounts??V9,readStoreIds:G?.readStoreIds??x$,openBrowser:G?.openBrowser??eU,now:G?.now??Date.now,openAccountPool:G?.openAccountPool??z4,migrationBlockers:G?.migrationBlockers??(async()=>{let q=await H4({currentVersion:Q});return q.open?[]:q.blockers.map((C)=>({pid:C.pid,version:C.version}))}),...G?.terminal?{terminal:G.terminal}:{},...G?.vaultWait?{vaultWait:G.vaultWait}:{}},H=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(K&&await K.authority()!=="local")return!0;if((await H()).type!=="missing")return!0;let q=X(),C=U.openAccountPool(q);if((await C.read()).status==="ready")return e$(C);return((await U.loadAccounts(q))?.accounts.length??0)>0},F=async(q)=>{if(await Q5(X().configPath,async()=>{if(K&&await K.authority()!=="local")return!1;if(t0(await H()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...q}}),!0}))await z?.().catch(()=>{})},Z=(q)=>({begin:async({headless:C,signal:m})=>{if(K&&await K.authority()!=="local")throw Error(K4);let r=await U.beginAccountLogin({version:Q,headless:C,...m?{signal:m}:{}});return{url:r.url,instructions:r.instructions,completion:r.completion.then(async(l)=>{if(K&&await K.authority()!=="local")throw Error(K4);let R0=await q.read(),B0=R0.status==="ready"?R0.rows.find((A0)=>A0.id===g6)?.identity:void 0;if(l.accountId&&B0&&l.accountId===B0)throw Error("that account is already the OpenCode main credential");return{id:l.id,credential:{type:"oauth",refresh:l.refresh,...l.access!==void 0?{access:l.access}:{},...l.expires!==void 0?{expires:l.expires}:{}},...l.accountId!==void 0?{identity:l.accountId}:{},...l.label!==void 0?{label:l.label}:{}}})}},openBrowser:(C)=>U.openBrowser(C)}),N=async(q)=>{if(K&&await K.authority()!=="local")throw Error(K4);let C=q.credential;if(C?.type!=="oauth"||!C.access)throw Error("no usable access token for a quota check");let m=await Y8({accessToken:C.access,fetchImpl:$,now:U.now,...q.identity?{accountId:q.identity}:{},accountKey:q.id});return U4(m,U.now(),!0)},j=(q)=>v$({paths:X(),migrated:q,readAuth:H,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:F,now:U.now}),P=(q,C)=>({title:y$,store:GJ(C,{rowLocks:(m)=>G4(q,m)}),...U.terminal?{terminal:U.terminal}:{},login:Z(C),protect:(m,r)=>W9(m,r),extraLocks:o6(q),pollQuota:N,doctor:j(!0),status:async()=>{if(K&&await K.authority()==="host")return[g$];let m=await K?.status();if(K&&await K.authority()!=="local"&&m)return[PJ(K.host,K.name,m.enrollment)];return[`Routing: ${(await U.loadAccounts(q))?.routing?.mode??"main-first"}`,...K?[PJ(K.host,K.name,(await K.status()).enrollment)]:[]]},...K&&!H9()?{extraActions:[v(K)]}:{}}),v=(q)=>{let C=q.enrolled();return{id:C?"vault-disconnect":"vault-connect",label:C?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(m)=>{let r=await q.authority();if(r==="host"){m.print(f$);return}if(C){if(r!=="local")await q.disconnect();m.print("Disconnected from the Claustrum vault.");return}if(r!=="local"){m.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}m.print(`Asking the Claustrum vault to enroll ${q.name}…`);let l,R0=await q.waitForApproval({...U.vaultWait,onPending:(B0)=>{let z0=B0.state==="pending"?B0.requestId??B0.retryCode??"":B0.state;if(z0===l)return;l=z0;for(let A0 of r$(q.name,B0))m.print(A0);m.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});m.print(s$(q,R0).text)}}},y=async()=>{let q=await U.migrationBlockers();return t$({title:y$,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...q.length>0?["These processes still hold the move back:",...q.map((C)=>` ${C.pid==="unknown"?"processes that could not be read":`pid ${C.pid}`}: version ${C.version}`)]:[]],actions:[a$({checks:j(!1)})],...U.terminal?{terminal:U.terminal}:{}})},I=async(q)=>{let C=X(),m=U.openAccountPool(C);if(K&&await K.authority()!=="local")return U9(P(C,m),K);if(await z9(C,m)===void 0)return y();let r=P(C,m);return K?U9(r,K):Y5(r)},A=(q)=>async()=>{if(K&&await K.authority()!=="local")throw Error(K4);let C=await q();if(C.method!=="auto")return C;return{...C,callback:async()=>{let m=await C.callback();if(K&&await K.authority()!=="local")return{type:"failed"};return m}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:J5({hasCredential:V,openMenu:I,login:A(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:A(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...K?.enrolled()?[{label:YH,type:"oauth",authorize:async()=>({url:"",instructions:JH,method:"auto",callback:async()=>{let q=await m$(K.paths,K.name);if(q!=="vault"&&q!=="host")return{type:"failed"};try{let C=JSON.parse(await tU(G5(),"utf8"));if(!C||typeof C!=="object"||Array.isArray(C)||Object.hasOwn(C,"openai"))return{type:"failed"}}catch(C){if(C.code!=="ENOENT")return{type:"failed"}}return{...$5,type:"success"}}})}]:[]]}var QH=new Set(["title","compaction","summary"]);function K5(Y,J,X){if(X!==null&&QH.has(X))return;W5(Y,J)}class EJ{#Y=new WeakMap;record(Y,{turnID:J,turnStartedAt:X}=Y){if(X!==void 0)this.#Y.set(Y,{turnID:J,turnStartedAt:X})}forAuxiliary(Y,J){let X=this.#Y.get(Y)??{turnID:(J?.uuid??h1)(),turnStartedAt:(J?.now??Date.now)()};return{threadID:Y.threadID,windowID:Y.windowID,...X,pinnedEffort:Y.pinnedEffort,effortUpdates:Y.effortUpdates?.map(($)=>({...$}))}}}var AJ={rpcRoot:"openai-auth",directoryPrefix:V5,registrationSessionId:"process"},N9=new Map;function SD(Y,J){if(J?.aborted)return Promise.resolve(!1);if(MJ(Y))return Promise.resolve(!0);return new Promise((X)=>{let $=(K)=>{if(clearTimeout(G),J?.removeEventListener("abort",Q),z.delete($),z.size===0)N9.delete(Y);X(K)},Q=()=>$(!1),G=setTimeout(()=>$(!1),2000),z=N9.get(Y)??new Set;N9.set(Y,z),z.add($),J?.addEventListener("abort",Q,{once:!0})})}function L9(Y,J){U5(AJ,Y,J)}function N5(Y=0,J){let X=H5(AJ,Y,J);if(J!==void 0)for(let $ of N9.get(J)??[])$(!0);return X}function MJ(Y){return B5(AJ,Y)}var N1=U0("commands");function v1(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function j5(Y){return Y.configPath??v1(Y).configPath}async function J8(Y){let J=Y.settingsSnapshot,X=j5(Y);if(!J||y6(X)!=="shared")return;let $=await d4(X);if($?.decision!=="shared")return;let Q=$.install.target;return{snapshot:J,file:Q,writer:J4(T0,{file:Q,log:N1,separateInstall:!1,createMissing:!0})}}async function CJ(Y,J,X){let $=await J8(Y);if(!$){await X();return}try{if(J.setting==="cache_keep_window"){if(await $.snapshot.refresh(),$.snapshot.report().some((Q)=>Q.reason==="invalid-value"&&Q.keyPath[0]===J.setting||Q.reason==="unreadable"||Q.reason==="unparseable"))throw new w1("settings-invalid-value",$.file)}await $.writer.update([J],{host:"opencode"}),await $.snapshot.refresh()}catch(Q){if(Q instanceof w1)throw new n4(Q.code,J9(Q.code));throw Q}}function TJ(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function GH(Y){let J=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!J)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let X=Number(J[1]),$=Number(J[2]);if(X>23||$>23||X===$)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:$}}var zH="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore enabling sustain with Magic Context, set a non-expiring `cache_ttl` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.";function WH(Y){let J=(X,$,Q)=>CJ(Y,{setting:X,value:$},()=>C1(Y.store(),o6(v1(Y)),(G)=>{let z={...G.cacheKeep??{}};Q(z),G.cacheKeep=z}));return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let $=await J8(Y);await $?.snapshot.refresh();let Q=j9($?$.snapshot.view():await Y.loadAccounts(v1(Y))),G=Q?.enabled===!0,z=Q?.subagents===!0,K=X.status(),U=K.window?TJ(K.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${K.tracked===0?"no sessions":`${K.tracked} session${K.tracked===1?"":"s"}`}`,`Timer ${K.running?"armed":"idle"} · subagents ${z?"on":"off"} · sustain ${K.sustain?"on":"off"}`,`Window ${U}`,...Y.cacheKeepNotice?[Y.cacheKeepNotice]:[],`TTL ${Math.round(K.ttlMs/1000)}s · lead ${Math.round(K.leadMs/1000)}s · idle cap ${Math.round(K.maxIdleWarmMs/60000)}min (subagents ${Math.round(K.maxSubagentIdleMs/60000)}min)`],items:K.targets.map((H)=>({id:H.sessionKey,label:H.sessionKey,group:"Sessions",detail:[H.accountId??"main",`expires in ${Math.ceil((H.cacheExpiresAt-K.generatedAt)/1000)}s`,...H.lastWarmedAt?[`last warm ${Math.ceil((K.generatedAt-H.lastWarmedAt)/1000)}s ago`]:[],...H.backoffUntil&&H.backoffUntil>K.generatedAt?[`backoff ${Math.ceil((H.backoffUntil-K.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:H})=>{let V=H.enabled===!0;if(await J("cache_keep_enabled",V,(F)=>{F.enabled=V}),Y.setCacheKeepEnabled?.(V),V)X.start();else{for(let F of X.status().targets)if(!F9(F.sessionKey,!1))X.remove(F.sessionKey);if(X.status().tracked===0)X.stop()}return N1.info(V?"cachekeep enabled":"cachekeep disabled"),V?`Keep-warm is on. TTL ${Math.round(K.ttlMs/1000)}s, idle cap ${Math.round(K.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:z?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!z}],run:async({values:H})=>{let V=H.subagents===!0;return await J("cache_keep_subagents",V,(F)=>{F.subagents=V}),Y.setCacheKeepSubagents?.(V),`Subagent warming is ${V?"on":"off"}.`}},{id:"sustain",label:K.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!K.sustain}],run:async({values:H})=>{let V=H.sustain===!0;return await J("cache_keep_sustain",V,(F)=>{F.sustain=V}),Y.setCacheKeepSustain?.(V),V?zH:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...K.window?{value:TJ(K.window)}:{}}],run:async({values:H})=>{let V=H.window;if(typeof V!=="string"||V.trim()==="")return await J("cache_keep_window",[],(j)=>{delete j.startHour,delete j.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let F=GH(V);if(!F.ok)return{ok:!1,text:`Invalid window: ${F.reason}`};let{startHour:Z,endHour:N}=F;return await J("cache_keep_window",[{start_hour:Z,end_hour:N}],(j)=>{j.startHour=Z,j.endHour=N}),Y.setCacheKeepWindow?.({startHour:Z,endHour:N}),`Warming limited to ${TJ(F)} local hours.`}}]}}}}var L5=["error","warn","info","debug","trace"];function KH(Y){return{title:"Diagnostics",build:async()=>{let J=j5(Y),X=d4(J)?await K$({configPath:J,snapshot:Y.settingsSnapshot,log:N1}):{lines:[]},$=await J8(Y),Q=T6(J),G=G9(J),K=($?$.snapshot.view():await Y.loadAccounts(v1(Y)).catch(()=>null))?.logging?.level,U=!K||K==="default"?"info":K,H=G?await Z5(Q.dumpDir):void 0,V=H===void 0?"size unavailable":RJ(H),F=Q.dumpMaxBytes===0?"no cap":`${RJ(Q.dumpMaxBytes)} cap`,Z=Y.layoutNotice?.();return{lines:[G?`Dumps on (${V} / ${F})`:"Dumps off",`Dump directory: ${Q.dumpDir}`,`Log level: ${U}`,...Z?[Z]:[],...X.lines],actions:[{id:"dump",label:G?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!G}],run:async({values:N})=>{let j=N.enabled===!0;await CJ(Y,{setting:"request_dumps",value:j},()=>C1(Y.store(),o6(v1(Y)),(v)=>{v.dump={...v.dump??{},enabled:j}}));let P=T$(J);return N1.info(j?"request dump enabled":"request dump disabled"),j?`Request dumps are on, written to ${P.dumpDir}.
|
|
2
2
|
|
|
3
3
|
Body dumps may contain prompt and session content. Turn this off after debugging.`:"Request dumps are off."}},{id:"logging",label:"Set the log level",knobs:[{kind:"choice",id:"level",label:"Level",choices:L5.map((N)=>({value:N,label:N})),value:L5.includes(U)?U:"info"}],run:async({values:N})=>{let j=String(N.level);return await CJ(Y,{setting:"log_level",value:j},()=>C1(Y.store(),o6(v1(Y)),(P)=>{P.logging={...P.logging??{},level:j}})),Z9(j),N1.info("log level changed",{level:j}),`Log level set to ${j}.`}}]}}}}async function UH(Y){let J=await Y.store().read(),X=J.status==="ready"?J.rows:[];return[...new Set(["main",...X.filter(($)=>$.enabled&&$.type==="oauth").map(($)=>$.id)])]}function F5(Y){let J=v1(Y),X=Y.configPath??J.configPath,$=o6(J),Q=Y.settings??(Y.settingsSnapshot&&y6(X)==="shared"?{read:async()=>{let K=await J8(Y);if(!K)throw Error("Shared settings are unavailable");return o4({...K,host:"opencode",log:N1}).read()},update:async(K)=>{let U=await J8(Y);if(!U)throw Error("Shared settings are unavailable");await o4({...U,host:"opencode",log:N1}).update(K)}}:void 0),G=Y.quotaManager&&Y.resolveResetTarget&&Y.refreshResetTargetQuota&&Y.fetchImpl&&Y.now&&Y.randomUUID?UJ({configPath:J.configPath,statePath:J.statePath,quotaManager:Y.quotaManager,loadAccounts:Y.loadAccounts,mutateAccounts:zJ(Y.store(),$,X),resolveResetTarget:Y.resolveResetTarget,refreshResetTargetQuota:Y.refreshResetTargetQuota,fetchImpl:Y.fetchImpl,now:Y.now,randomUUID:Y.randomUUID,accountKeys:()=>UH(Y)}):void 0,z=Y.beginAccountLogin;return HJ({store:Y.store(),configPath:X,...Q?{settings:Q}:{},...Y.readOnly?{readOnly:!0}:{},...Y.allowAction?{allowAction:Y.allowAction}:{},...Y.unavailableSections?{unavailableSections:Y.unavailableSections}:{},...Y.vault?{vault:Y.vault}:{},...Y.now?{now:Y.now}:{},extraLocks:$,rowLocks:(K)=>G4(J,K),migration:Y.migration,...z?{login:{begin:(K)=>z({...K,version:Y.packageVersion}),mainIdentity:async()=>{let K=await Y.store().read();if(K.status!=="ready")return;return K.rows.find((U)=>U.id==="main")?.identity}}}:{},protect:(K,U)=>W9(K,U),...Y.refreshAllQuota?{quotaCheck:async(K)=>{if(K.length===1){let V=Y.store();for(let F of K)await V.requestReading(F);await V.pullsSettled();return}let H=(await Y.refreshAllQuota?.()??[]).filter((V)=>!V.ok);if(H.length>0)throw new n4("quota-check-failed",H.map((V)=>V.permanent?`${V.account}: sign-in no longer accepted — remove and add this account again`:`${V.account}: fetch failed — check again to retry`).join(`
|
|
4
4
|
`))}}:{},cache:WH(Y),diagnostics:KH(Y),extras:[...G?[G]:[],WJ({...Y.getStickyRouting?{getPin:Y.getStickyRouting}:{},...Y.clearStickyRouting?{clearPin:Y.clearStickyRouting}:{}}),...Y.vault?[KJ({vault:Y.vault,changed:Y.afterWrite})]:[]],afterApply:async()=>{await Y.afterWrite?.(),await Y.refreshSidebar?.().catch(()=>{})}})}function _5(Y){return(J,X="info")=>{N1.info("menu notification",{sessionId:Y,kind:X}),L9({command:W1,notify:{message:J,kind:X}},Y)}}function D5(Y,J){return F5(Y).open({...J!==void 0?{sessionId:J}:{},notify:_5(J)})}function O5(Y,J){return F5(Y).apply(J,{...J.sessionId!==void 0?{sessionId:J.sessionId}:{},notify:_5(J.sessionId)})}function P5(Y){let J=[`## ${Y.title}`];for(let X of Y.sections){J.push("",`### ${X.title}`);for(let $ of X.lines)J.push($);for(let $ of X.items){let Q=$.detail??$.status;J.push(`- ${$.label}${Q?`: ${Q}`:""}`)}}return J.push("","Open the OpenCode TUI to change these settings."),J.join(`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Xc as X,Zc as V}from"./index-
|
|
1
|
+
import{Xc as X,Zc as V}from"./index-9kges8jy.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
|
|
2
2
|
`,{mode:W??384}),await $(B,W??384),await L(B,b)}catch(Y){throw await T(B,{force:!0}).catch(()=>{}),Y}return z.set(q,R(j.body)),!0},async all(){let j=await Q(b);if(!j||Object.keys(j).length===0)return{[x]:!0};return j}}}
|
|
3
3
|
export{_ as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$g as y,Zg as R,_g as T,ah as D}from"./index-drm4dk5y.js";import{Bh as I,vh as v}from"./index-4ktepxn1.js";import{Hh as t}from"./index-j700j6at.js";class O extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function S(f){return typeof f==="string"&&f.length>0}var g=new Map;function _(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),P=g.get(x);if(!P)P={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},g.set(x,P);return P}var m=100,l=3000;function Vf(f,x,P){if(f.requireSession===!0&&!S(P))throw new O("push");let V=_(f);if(V.queue.push({id:V.nextId++,type:"open-dialog",payload:x,sessionId:P}),V.queue.length>m)V.queue=V.queue.slice(-m)}function Bf(f,x=0,P){if(f.requireSession===!0&&!S(P))throw new O("drain");let V=_(f),J=Date.now();if(V.lastDrainAtAny=J,P!==void 0)V.lastDrainAtBySession.set(P,J);let K=f.sessionlessDrain==="broadcast-only",H=(B)=>P===void 0?!K||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===P;if(x>0)V.queue=V.queue.filter((B)=>{if(B.id>x)return!0;if(P===void 0)return!K||B.sessionId!==void 0;return B.sessionId!==P});return V.queue.filter((B)=>B.id>x&&H(B))}function Ff(f,x){let P=Date.now(),V=_(f),J=x!==void 0?V.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?V.lastDrainAtAny:0;return J>0&&P-J<l}import{randomBytes as a,timingSafeEqual as o}from"node:crypto";import{unlink as r}from"node:fs/promises";import{createServer as s}from"node:http";import{join as e}from"node:path";import{lstat as c}from"node:fs/promises";import{basename as d,dirname as i,resolve as k}from"node:path";var j=globalThis,w=Symbol.for("common-auth.rpc.startup-sweep");j[w]??={};var U=j[w],n=Date.now;async function q(f,x,P,V){let J=n();if(U.lastSweepAt!==void 0&&J-U.lastSweepAt<60000){let K=k(x);if(i(K)===k(f)&&P(d(K))&&(await c(K).catch((H)=>{if(H.code!=="ENOENT")throw H;return}))?.isDirectory())await D(K,V);return}U.lastSweepAt=J,await y(f,x,P,V)}class b 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 u=1e6;class E extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function ff(f){return new Promise((x,P)=>{let V=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),P(new E(B))},J=Number(f.headers["content-length"]);if(Number.isFinite(J)&&J>u){V(!0);return}let K=[],H=0;f.on("data",(B)=>{if(H+=B.length,H>u){V();return}K.push(B)}),f.on("end",()=>x(Buffer.concat(K).toString("utf8"))),f.on("error",P)})}class h extends Error{}async function xf(f,x){let P,V=new Promise((J,K)=>{P=setTimeout(()=>K(new h("apply deadline exceeded")),x),P.unref?.()});f.catch(()=>{});try{return await Promise.race([f,V])}finally{clearTimeout(P)}}function Pf(f,x){if(!f?.startsWith("Bearer "))return!1;let P=Buffer.from(f.slice(7)),V=Buffer.from(x);return P.length===V.length&&o(P,V)}async function Wf(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(){}},P=a(32).toString("hex"),V=f.timeoutMs??90000,J=f.receiptTimeoutMs??2000,K=!1,H=new Set,B=s((z,G)=>{z.setTimeout(V,()=>{z.socket.destroy()}),M(z,G)});B.on("connection",(z)=>{H.add(z),z.once("close",()=>H.delete(z))}),B.requestTimeout=J,B.headersTimeout=J;async function M(z,G){let F=(X,W,C={})=>{if(G.headersSent||G.writableEnded||G.destroyed)return;G.writeHead(X,{"content-type":"application/json",...C}),G.end(JSON.stringify(W))};try{let X=new URL(z.url??"/","http://127.0.0.1").pathname;if(z.method==="GET"&&X==="/health")return F(200,{ok:!0});if(z.method!=="POST"||!X.startsWith("/rpc/"))return F(404,{error:"not found"});if(!Pf(z.headers.authorization,P))return F(401,{error:"unauthorized"});let W=X.slice(5),C;try{C=await ff(z)}catch(Y){if(!(Y instanceof E))throw Y;let Z=z.socket;if(G.once("finish",()=>{Z.end();let $=setTimeout(()=>Z.destroy(),2000);if($.unref(),z.once("end",()=>Z.destroy()),Z.once("close",()=>clearTimeout($)),z.complete)Z.destroy()}),!Y.declaredOversize&&!z.complete){if(G.headersSent||G.writableEnded||G.destroyed)return;let $=JSON.stringify({error:"body too large"});G.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength($),connection:"close"}),G.write($),z.once("end",()=>G.end());return}return F(413,{error:"body too large"},{connection:"close"})}let Q;try{Q=JSON.parse(C||"{}")}catch{return F(400,{error:"invalid json"})}if(W==="pending-notifications"){let Y;try{if(f.parsePending)Y=f.parsePending(Q);else{if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error("invalid params");let L=Q;if(f.requireSession===!0&&!S(L.sessionId))return F(400,{error:"session required"});if("lastReceivedId"in L&&(typeof L.lastReceivedId!=="number"||!Number.isSafeInteger(L.lastReceivedId)||L.lastReceivedId<0)||"sessionId"in L&&typeof L.sessionId!=="string")throw Error("invalid params");Y={lastReceivedId:Number(L.lastReceivedId??0),sessionId:typeof L.sessionId==="string"?L.sessionId:void 0}}}catch(L){if(L instanceof b)throw L;return F(400,{error:"invalid params"})}let{lastReceivedId:Z,sessionId:$}=Y;if(f.requireSession===!0&&!S($))return F(400,{error:"session required"});if($===void 0&&!K)K=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let N;if(f.drainAsync)try{N=await f.drainAsync(Z,$)}catch(L){return x.warn("rpc notification drain failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)}),F(500,{error:"drain failed"})}else N=f.drain?.(Z,$);return F(200,{messages:N})}if(W==="apply"){let Y=Promise.resolve(f.apply(Q)),Z=f.applyDeadlineMs===void 0?await Y:await xf(Y,f.applyDeadlineMs);return F(200,Z)}return F(404,{error:"unknown method"})}catch(X){if(X instanceof b)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),F(X.status,{error:X.message});if(X instanceof h)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),F(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),F(500,{error:"internal error"})}}let A=await new Promise((z,G)=>{B.on("error",G),B.listen(0,"127.0.0.1",()=>{let F=B.address();if(F&&typeof F==="object")z(F.port);else G(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await q(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(z){x.warn("rpc state sweep failed",{pid:process.pid,error:z instanceof Error?z.message:String(z)})}try{await T(f.dir,{port:A,token:P,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:A})}catch(z){throw await new Promise((G)=>B.close(()=>G())),z}return{port:A,token:P,async stop(){await new Promise((F)=>{B.closeAllConnections?.(),B.close(()=>F());for(let X of H)X.destroy()});let z=e(f.dir,`port-${process.pid}.json`),G=await I(z).then((F)=>JSON.parse(F)).catch((F)=>{if(F instanceof v&&F.code!=="ENOENT")throw F;return});if(G?.port===A&&G.token===P)await r(z).catch(()=>{})}}}async function Mf(f,x,P){let V=globalThis,J=Symbol.for(f),K=V[J]??{servers:new Map,pending:new Map};V[J]=K;let{servers:H,pending:B}=K,M=B.get(x)??Promise.resolve(),A,z=M.catch(()=>{}).then(async()=>{let F=H.get(x);if(F){if(await F.stop(),H.get(x)===F)H.delete(x)}A=await P(),H.set(x,A)});B.set(x,z);try{await z}finally{if(B.get(x)===z)B.delete(x)}let G=A;if(!G)throw Error("RPC server failed to start");return{server:G,release:async()=>{if(H.get(x)!==G)return;if(await G.stop(),H.get(x)===G)H.delete(x)}}}var p="1.23.
|
|
1
|
+
import{$g as y,Zg as R,_g as T,ah as D}from"./index-drm4dk5y.js";import{Bh as I,vh as v}from"./index-4ktepxn1.js";import{Hh as t}from"./index-j700j6at.js";class O extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function S(f){return typeof f==="string"&&f.length>0}var g=new Map;function _(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),P=g.get(x);if(!P)P={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},g.set(x,P);return P}var m=100,l=3000;function Vf(f,x,P){if(f.requireSession===!0&&!S(P))throw new O("push");let V=_(f);if(V.queue.push({id:V.nextId++,type:"open-dialog",payload:x,sessionId:P}),V.queue.length>m)V.queue=V.queue.slice(-m)}function Bf(f,x=0,P){if(f.requireSession===!0&&!S(P))throw new O("drain");let V=_(f),J=Date.now();if(V.lastDrainAtAny=J,P!==void 0)V.lastDrainAtBySession.set(P,J);let K=f.sessionlessDrain==="broadcast-only",H=(B)=>P===void 0?!K||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===P;if(x>0)V.queue=V.queue.filter((B)=>{if(B.id>x)return!0;if(P===void 0)return!K||B.sessionId!==void 0;return B.sessionId!==P});return V.queue.filter((B)=>B.id>x&&H(B))}function Ff(f,x){let P=Date.now(),V=_(f),J=x!==void 0?V.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?V.lastDrainAtAny:0;return J>0&&P-J<l}import{randomBytes as a,timingSafeEqual as o}from"node:crypto";import{unlink as r}from"node:fs/promises";import{createServer as s}from"node:http";import{join as e}from"node:path";import{lstat as c}from"node:fs/promises";import{basename as d,dirname as i,resolve as k}from"node:path";var j=globalThis,w=Symbol.for("common-auth.rpc.startup-sweep");j[w]??={};var U=j[w],n=Date.now;async function q(f,x,P,V){let J=n();if(U.lastSweepAt!==void 0&&J-U.lastSweepAt<60000){let K=k(x);if(i(K)===k(f)&&P(d(K))&&(await c(K).catch((H)=>{if(H.code!=="ENOENT")throw H;return}))?.isDirectory())await D(K,V);return}U.lastSweepAt=J,await y(f,x,P,V)}class b 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 u=1e6;class E extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function ff(f){return new Promise((x,P)=>{let V=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),P(new E(B))},J=Number(f.headers["content-length"]);if(Number.isFinite(J)&&J>u){V(!0);return}let K=[],H=0;f.on("data",(B)=>{if(H+=B.length,H>u){V();return}K.push(B)}),f.on("end",()=>x(Buffer.concat(K).toString("utf8"))),f.on("error",P)})}class h extends Error{}async function xf(f,x){let P,V=new Promise((J,K)=>{P=setTimeout(()=>K(new h("apply deadline exceeded")),x),P.unref?.()});f.catch(()=>{});try{return await Promise.race([f,V])}finally{clearTimeout(P)}}function Pf(f,x){if(!f?.startsWith("Bearer "))return!1;let P=Buffer.from(f.slice(7)),V=Buffer.from(x);return P.length===V.length&&o(P,V)}async function Wf(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(){}},P=a(32).toString("hex"),V=f.timeoutMs??90000,J=f.receiptTimeoutMs??2000,K=!1,H=new Set,B=s((z,G)=>{z.setTimeout(V,()=>{z.socket.destroy()}),M(z,G)});B.on("connection",(z)=>{H.add(z),z.once("close",()=>H.delete(z))}),B.requestTimeout=J,B.headersTimeout=J;async function M(z,G){let F=(X,W,C={})=>{if(G.headersSent||G.writableEnded||G.destroyed)return;G.writeHead(X,{"content-type":"application/json",...C}),G.end(JSON.stringify(W))};try{let X=new URL(z.url??"/","http://127.0.0.1").pathname;if(z.method==="GET"&&X==="/health")return F(200,{ok:!0});if(z.method!=="POST"||!X.startsWith("/rpc/"))return F(404,{error:"not found"});if(!Pf(z.headers.authorization,P))return F(401,{error:"unauthorized"});let W=X.slice(5),C;try{C=await ff(z)}catch(Y){if(!(Y instanceof E))throw Y;let Z=z.socket;if(G.once("finish",()=>{Z.end();let $=setTimeout(()=>Z.destroy(),2000);if($.unref(),z.once("end",()=>Z.destroy()),Z.once("close",()=>clearTimeout($)),z.complete)Z.destroy()}),!Y.declaredOversize&&!z.complete){if(G.headersSent||G.writableEnded||G.destroyed)return;let $=JSON.stringify({error:"body too large"});G.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength($),connection:"close"}),G.write($),z.once("end",()=>G.end());return}return F(413,{error:"body too large"},{connection:"close"})}let Q;try{Q=JSON.parse(C||"{}")}catch{return F(400,{error:"invalid json"})}if(W==="pending-notifications"){let Y;try{if(f.parsePending)Y=f.parsePending(Q);else{if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error("invalid params");let L=Q;if(f.requireSession===!0&&!S(L.sessionId))return F(400,{error:"session required"});if("lastReceivedId"in L&&(typeof L.lastReceivedId!=="number"||!Number.isSafeInteger(L.lastReceivedId)||L.lastReceivedId<0)||"sessionId"in L&&typeof L.sessionId!=="string")throw Error("invalid params");Y={lastReceivedId:Number(L.lastReceivedId??0),sessionId:typeof L.sessionId==="string"?L.sessionId:void 0}}}catch(L){if(L instanceof b)throw L;return F(400,{error:"invalid params"})}let{lastReceivedId:Z,sessionId:$}=Y;if(f.requireSession===!0&&!S($))return F(400,{error:"session required"});if($===void 0&&!K)K=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let N;if(f.drainAsync)try{N=await f.drainAsync(Z,$)}catch(L){return x.warn("rpc notification drain failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)}),F(500,{error:"drain failed"})}else N=f.drain?.(Z,$);return F(200,{messages:N})}if(W==="apply"){let Y=Promise.resolve(f.apply(Q)),Z=f.applyDeadlineMs===void 0?await Y:await xf(Y,f.applyDeadlineMs);return F(200,Z)}return F(404,{error:"unknown method"})}catch(X){if(X instanceof b)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),F(X.status,{error:X.message});if(X instanceof h)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),F(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),F(500,{error:"internal error"})}}let A=await new Promise((z,G)=>{B.on("error",G),B.listen(0,"127.0.0.1",()=>{let F=B.address();if(F&&typeof F==="object")z(F.port);else G(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await q(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(z){x.warn("rpc state sweep failed",{pid:process.pid,error:z instanceof Error?z.message:String(z)})}try{await T(f.dir,{port:A,token:P,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:A})}catch(z){throw await new Promise((G)=>B.close(()=>G())),z}return{port:A,token:P,async stop(){await new Promise((F)=>{B.closeAllConnections?.(),B.close(()=>F());for(let X of H)X.destroy()});let z=e(f.dir,`port-${process.pid}.json`),G=await I(z).then((F)=>JSON.parse(F)).catch((F)=>{if(F instanceof v&&F.code!=="ENOENT")throw F;return});if(G?.port===A&&G.token===P)await r(z).catch(()=>{})}}}async function Mf(f,x,P){let V=globalThis,J=Symbol.for(f),K=V[J]??{servers:new Map,pending:new Map};V[J]=K;let{servers:H,pending:B}=K,M=B.get(x)??Promise.resolve(),A,z=M.catch(()=>{}).then(async()=>{let F=H.get(x);if(F){if(await F.stop(),H.get(x)===F)H.delete(x)}A=await P(),H.set(x,A)});B.set(x,z);try{await z}finally{if(B.get(x)===z)B.delete(x)}let G=A;if(!G)throw Error("RPC server failed to start");return{server:G,release:async()=>{if(H.get(x)!==G)return;if(await G.stop(),H.get(x)===G)H.delete(x)}}}var p="1.23.3";function wf(f,x,P){let V={...x,version:p};return T(f,V,P)}var qf=R(t);
|
|
2
2
|
export{Vf as Rg,Bf as Sg,Ff as Tg,Wf as Ug,Mf as Vg,p as Wg,wf as Xg,qf as Yg};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as D,H as l,I as m,J as n,K as o,L as p,O as q,P as r,Q as s,R as t,S as u,T as v,U as w,V as x,W as y,X as z,Y as A,Z as B,_ as C,aa as E,ba as F}from"./index-
|
|
1
|
+
import{$ as D,H as l,I as m,J as n,K as o,L as p,O as q,P as r,Q as s,R as t,S as u,T as v,U as w,V as x,W as y,X as z,Y as A,Z as B,_ as C,aa as E,ba as F}from"./index-ekt6aq17.js";import{$a as c,Eb as e,Fb as f,Gb as g,Hb as h,Ib as i,Wb as j,Xb as k,ab as d}from"./index-9kges8jy.js";import"./index-nd2ks7er.js";import{bf as a,cf as b}from"./index-x00sxt2w.js";import"./index-49ncs7dr.js";import"./index-xkngfyvc.js";import"./index-drm4dk5y.js";import"./index-wjp3q15r.js";import"./index-td4g5dc9.js";import"./index-4ktepxn1.js";import"./index-j700j6at.js";import"./index-q2czrasr.js";export{d as rewriteResponsesLiteBody,u as resolveSidebarSessionId,n as poolResetTarget,a as parseJwtClaims,r as mergePushedQuotaMetadata,w as getMainRefreshLockName,q as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,F as default,o as createResetTargetResolver,i as codexOAuthModelVariantSource,g as codexOAuthModelListed,h as codexOAuthModelLimit,t as buildSidebarState,s as buildSidebarMachineState,p as buildResetRedemptionDeps,A as __resetBootQuotaSeedForTest,B as __menuContextForTest,z as __bootQuotaSeedPromiseForTest,m as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,C as POOL_MIGRATION_ENABLED,E as OpenAIAuthPlugin,x as MAIN_REFRESH_LOCK_TTL_MS,y as MAIN_REFRESH_LEASE_TTL_MS,v as EMPTY_BEARER_MESSAGE,f as DISALLOWED_MODELS,D as CodexAuthPlugin,j as CODEX_VERSION,k as CODEX_USER_AGENT,l as AuthPersistError,e as ALLOWED_MODELS};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Xg as b,Yg as c}from"../index-
|
|
1
|
+
import{Xg as b,Yg as c}from"../index-xkngfyvc.js";import{bh as a}from"../index-drm4dk5y.js";import"../index-4ktepxn1.js";import"../index-j700j6at.js";import"../index-q2czrasr.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
|