@cortexkit/opencode-openai-auth 1.20.2 → 1.20.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/{codex-request-Dvj28zFK.d.ts → codex-request-D0oxrTkl.d.ts} +19 -1
- package/dist/{index-0mf78d7s.js → index-66eejhpe.js} +1 -1
- package/dist/{index-38xyx9nd.js → index-6a1t612m.js} +1 -1
- package/dist/{index-a1zh72v8.js → index-8ap9gr0h.js} +1 -1
- package/dist/{index-ah9yt0zm.js → index-a7eep73q.js} +1 -1
- package/dist/{index-8ge0as5s.js → index-ahbghz6c.js} +1 -1
- package/dist/{index-xcsz00nr.js → index-eb631m0m.js} +1 -1
- package/dist/{index-jky7c65x.js → index-gxa94644.js} +1 -1
- package/dist/index-kakqxnt5.js +101 -0
- package/dist/{index-z4tfv40j.js → index-t66h86ed.js} +1 -1
- package/dist/{index-rbc7cfbv.js → index-vjb3rsqh.js} +3 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +4 -4
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +145 -8
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +32 -0
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +10 -0
- package/src/tui-compiled/raw/shared/c97089ed4243981c-host.js +8 -0
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +145 -8
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +32 -0
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +10 -0
- package/src/tui-compiled/runtime/shared/c97089ed4243981c-host.js +8 -0
- package/dist/index-x3q449sn.js +0 -101
- /package/dist/{index-c4h4t3wg.js → index-tn1ve0gx.js} +0 -0
package/dist/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as q2}from"./index-
|
|
2
|
+
import{c as q2}from"./index-6a1t612m.js";import{Aa as s,Ba as H0,Ca as a,Da as $2,Jc as D2,Na as t0,Oa as l,Pa as F,Qa as u,dc as G2,vc as j2,za as F0}from"./index-vjb3rsqh.js";import{Je as W2,ae as g,be as e,de as y0,fe as r0,ge as n,he as A,ie as n0,je as i,ke as C0,le as f0}from"./index-kakqxnt5.js";import"./index-t66h86ed.js";import"./index-gxa94644.js";import"./index-8ap9gr0h.js";import{Eg as x0,Gg as U0,Jg as X2}from"./index-66eejhpe.js";import{Lg as R0,Pg as A0}from"./index-eb631m0m.js";import"./index-tn1ve0gx.js";import"./index-qtaqp1bf.js";import"./index-t15pb3n2.js";import{spawn as B2}from"node:child_process";var N=4096,V2=1048576;class O0{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=N){if(z.length>N||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-N),this.start=0,this.length=N;return}let J=Math.max(0,this.length+z.length-N);if(J>0)this.truncated=!0;this.start=(this.start+J)%N,this.length-=J;let Z=(this.start+this.length)%N,$=Math.min(z.length,N-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,N-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var w={run(z,J,Z={}){return new Promise(($)=>{let K=performance.now(),Q=Z.timeoutMs??15000,W=new O0,G=[],V=0,X=!1,q=!1,b=!1,x;try{x=B2(z,[...J],{env:Z.env??process.env,windowsHide:!0,windowsVerbatimArguments:Z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{$({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let Y=Q>0?setTimeout(()=>{b=!0,x.kill("SIGTERM")},Q):void 0;x.stdout?.on("data",(j)=>{let U=V2-V,O=Math.min(U,j.length);if(O>0)G.push(j.subarray(0,O)),V+=O;if(j.length>U)X=!0,x.kill("SIGTERM")}),x.stderr?.on("data",(j)=>W.push(j));let H=!1,D=(j,U)=>{if(H)return;if(H=!0,Y)clearTimeout(Y);$({exitCode:q?1:X?1:j??1,stdout:Buffer.concat(G,V).toString("utf8"),stderr:W.toString(),stderrTruncated:W.didTruncate,...q?{spawnError:!0}:{},signal:U??null,timedOut:b,durationMs:performance.now()-K})};x.once("error",()=>{if(q=!0,x.pid===void 0)D(null,null)}),x.once("close",(j,U)=>D(j,U))})}};function o(z,J,Z,$,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((W)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(W)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:K,timeoutMs:Q})}function I0(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function h(z,J,Z,$){let K=J.requestedGrants??$;if(!K)return;let Q=K.map((G)=>({grant:G,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${I0(`enrolled:${J.approvedName}`)} --selector-kind ${G.selector.exact===void 0?"category":"exact"} --selector ${I0(G.selector.exact??G.selector.category)} --operation ${G.operation}`}})),W={grants:Q,...J.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:J.requestedGrantsStatus}};if(J.requestedGrantsStatus==="dropped")return{...W,state:"older-vault"};try{if(!z.listScoped)return{...W,state:"unconfirmed"};let{token:G}=await C0(Z),V=await z.listScoped(G),X=Q.map((q)=>({...q,reachableLogins:V.rows.filter((b)=>b.operations.includes(q.grant.operation)&&(q.grant.selector.exact!==void 0?b.id===q.grant.selector.exact:b.categories.includes(q.grant.selector.category))).length}));return{...W,state:X.every((q)=>q.reachableLogins>0)?"reachable":X.some((q)=>q.reachableLogins>0)?"partial":"no-logins",grants:X.map((q)=>{if(q.reachableLogins===0)return q;let{grantCommand:b,...x}=q;return x})}}catch{return{...W,state:"unconfirmed"}}}function m(z,J="setup"){if(J==="plugin"&&z.requestedGrantsStatus!=="sent")return[];let Z=[],$=z.grants.some((K)=>K.grantCommand)?"run:":"check ck auth status for the approved name before granting access.";if(z.state==="older-vault")Z.push(`Approved. This vault is too old to grant access with the approval; ${$}`);else if(z.state==="no-logins")Z.push(`Approved, but no logins are reachable yet; ${$}`);else if(z.state==="partial")Z.push(`Approved, but some requested access has no reachable logins yet; ${$}`);else if(z.state==="unconfirmed")Z.push(`Approved, but access could not be confirmed; ${z.grants.some((K)=>K.grantCommand)?"check ck auth status or run:":$}`);for(let{grant:K,reachableLogins:Q,grantCommand:W}of z.grants){if(Q!==void 0&&Q>0){let G=K.selector.exact===void 0?`the vault's ${JSON.stringify(K.selector.category)} accounts`:`credential ${JSON.stringify(K.selector.exact)}`;Z.push(`Confirmed ${K.operation} access to ${G} (${Q} reachable ${Q===1?"login":"logins"}).`)}if(W)Z.push(` ${W}`)}return Z}var x2="Pi install failed; run pi install after checking your npm connection.";function U2(z){let J=Buffer.from(z,"utf8");if(J.length<=N)return z;let Z=J.length-N;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function F2(z){let J=z.indexOf(`
|
|
3
3
|
`);return J<0?"":z.slice(J+1)}class r extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(x2);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?F2(z.stderrTail):z.stderrTail,Z=R0(J);this.stderrTail=U2(typeof Z==="string"?Z:"")}}var H2={opencode:"OpenCode",pi:"Pi"},M2={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function N0({host:z,outcome:J,access:Z},$="setup"){let K=Z?m(Z,$):[];return`${H2[z]}: ${M2[J]}${K.length?` — ${K.join(`
|
|
4
4
|
`)}`:""}`}var O2=new WeakMap;function k0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;O2.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as k2,constants as _2,existsSync as T2,readFileSync as P2,realpathSync as A2,statSync as L2}from"node:fs";import{mkdtemp as w2,rm as S2}from"node:fs/promises";import{tmpdir as v2}from"node:os";import{join as E2}from"node:path";import{parse as y2}from"jsonc-parser";import{homedir as I2}from"node:os";import{posix as C2,win32 as R2}from"node:path";import{fileURLToPath as N2}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?R2:C2,K=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??I2(),Q=z.cwd??process.cwd(),W=(q)=>$.resolve(Q,q),G=J.OPENCODE_CONFIG_DIR?.trim(),V=J.XDG_CONFIG_HOME?.trim(),X=J.PI_CODING_AGENT_DIR?.trim()||$.join(K,".pi","agent");if(X==="~")X=K;else if(/^~[/\\]/.test(X))X=$.join(K,X.slice(2));if(X.startsWith("file://"))X=N2(X);return{env:J,platform:Z,path:$,home:K,cwd:Q,opencode:G?W(G):V?$.join(W(V),"opencode"):$.join(K,".config","opencode"),pi:W(X)}}function K0(z,J){try{return L2(z)[J]()}catch{return!1}}var S={exists:T2,isFile:(z)=>K0(z,"isFile"),isDirectory:(z)=>K0(z,"isDirectory"),isExecutable(z){try{return k2(z,_2.X_OK),K0(z,"isFile")}catch{return!1}},readText:(z)=>P2(z,"utf8"),realpath:A2};function P(z,J={}){let{env:Z,platform:$,path:K,cwd:Q}=k(J),W=J.fs??S,G=Object.entries(Z).find(([X])=>$==="win32"?X.toUpperCase()==="PATH":X==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let X of G.split($==="win32"?";":":")){let q=X.trim().replace(/^"|"$/g,"");if(!q)continue;for(let b of V){let x=K.resolve(Q,q,z+b);if($==="win32"?W.isFile(x):W.isExecutable(x))return x}}return null}function _0(z={}){let{platform:J,home:Z,env:$,path:K}=k(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",K.join(Z,"Applications","OpenCode.app"),K.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.LOCALAPPDATA||K.join(Z,"AppData","Local");return[K.join(Q,"Programs","opencode"),K.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",K.join(Z,".local","share","applications","opencode.desktop")]}function Q0(z,J){let Z=J.fs??S,{path:$}=k(J);try{let K=Z.readText(z);if(K.length>65536)return z;let Q=[...K.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...K.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let W=Q.at(-1)?.[1];if(W){let G=$.join($.dirname(z),...W.split(/[/\\]+/));if(Z.isFile(G))return Z.realpath(G)}return Z.realpath(z)}catch{return z}}function f2(z,J){let Z=J.fs??S,{path:$}=k(J),K=$.dirname(Q0(z,J));for(;;){try{let W=JSON.parse(Z.readText($.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(W.name))return"2";if(W.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(W.version??"")?"2":"1"}catch{}let Q=$.dirname(K);if(Q===K)return null;K=Q}}function T0(z={}){let J=P("opencode",z),Z=P("opencode2",z),$=J&&Z&&Q0(J,z)===Q0(Z,z),K=z.fs??S,{path:Q,opencode:W}=k(z),G="1";for(let X of["jsonc","json"]){let q=Q.join(W,`opencode.${X}`);if(!K.exists(q))continue;try{if(Object.hasOwn(y2(K.readText(q))??{},"plugins"))G="2"}catch{}break}let V=J?f2(J,z)??($?"2":G):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??G}async function W0(z,J={}){let Z=J.fs??S,{env:$,platform:K,opencode:Q,pi:W}=k(J),G=J.runner??w,V=P("opencode",J)??P("opencode2",J),X=P("pi",J),q=P("ck",J),b=async(D)=>{if(!D)return null;let j;try{j=await w2(E2(v2(),"common-auth-setup-version-"));let U={...$,HOME:j,USERPROFILE:j,XDG_CONFIG_HOME:j,XDG_DATA_HOME:j,XDG_STATE_HOME:j,XDG_CACHE_HOME:j,OPENCODE_CONFIG_DIR:j,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:j},O=await o(G,K,D,["--version"],U,2000);return O.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(O.stdout)?.[0]??null:null}catch{return null}finally{if(j)await S2(j,{recursive:!0,force:!0}).catch(()=>{})}},x=!1;if(q&&Z.exists(z.vault.connectionFile))try{(await(J.connect??n)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),x=!0}catch{x=!1}let[Y,H]=await Promise.all([b(V),b(X)]);return{opencode:{installed:Z.isDirectory(Q)||_0(J).some((D)=>Z.exists(D))||V!==null,executable:V,version:Y,directory:Q,generation:T0(J)},pi:{installed:X!==null||Z.isDirectory(W),executable:X,version:H,directory:W},claustrum:{available:x,executable:q}}}import{setTimeout as r2}from"node:timers/promises";import{writeEnrollmentTokenFile as n2}from"@cortexkit/claustrum-client";import{statSync as g2}from"node:fs";import{win32 as t}from"node:path";var h2=45000,m2=A0("setup-process-fence"),d2=90000;function p2(z){try{return g2(z).isFile()}catch{return!1}}function d(z,J){return Object.entries(z).find(([Z])=>Z.toUpperCase()===J.toUpperCase())?.[1]}var X0=new Set(["opencode","litecode","opencode2","pi"]),L0=new Set(["node","bun"]),c2=[...X0,...L0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),u2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${c2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,l2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function i2(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function P0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var a2=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--title","--input-type","--preload","--cwd","-c","--config","--tsconfig-override","-d","--define","-l","--main-fields"]),s2=new Set(["-e","--eval","-p","--print"]);function o2(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(s2.has($))return;if($.startsWith("-")){if(!$.includes("=")&&a2.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function w0(z){let[J,...Z]=i2(z);if(J===void 0)return null;let $=P0(J);if(X0.has($))return $;if(!L0.has($))return null;let K=o2($,Z);if(K===void 0)return null;let Q=P0(K);if(X0.has(Q))return Q;return l2.test(K)?"pi":null}class R extends Error{code="process-inspection-failed";step;program;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.program=z.program,this.exitCode=z.exitCode,this.signal=z.signal,this.timedOut=z.timedOut,this.durationMs=z.durationMs}get refusalText(){let z=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${z} after ${Math.round(this.durationMs)} ms.`}}class y extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:w0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
|
|
5
5
|
${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
|
|
@@ -10,5 +10,5 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);thi
|
|
|
10
10
|
`:`
|
|
11
11
|
`}},W=z,G=K[J],V=Array.isArray(G)?[...G]:[],X=V.flatMap((x,Y)=>Y0(x)===Z?[Y]:[]),q=`${Z}@${$}`;if(!X.length)W=q0(W,l0(W,G===void 0?[J]:[J,V.length],G===void 0?[q]:q,Q));else{let x=X[0],Y=V[x],H=Array.isArray(Y)?[q,...Y.slice(1)]:Y&&typeof Y==="object"?{...Y,package:q}:q;if(JSON.stringify(Y)!==JSON.stringify(H))W=q0(W,l0(W,[J,x],H,Q));for(let D of X.slice(1).reverse())W=i0(W,J,D)}let b=J==="plugin"?"plugins":"plugin";if(Array.isArray(K[b])){let x=K[b];for(let Y=x.length-1;Y>=0;Y--)if(Y0(x[Y])===Z)W=i0(W,b,Y)}return W}function D0(z,J,Z={}){let $=Z.fs??S,{path:K,opencode:Q}=k(Z),W=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((V)=>{let X=K.join(Q,`${V}.jsonc`),q=K.join(Q,`${V}.json`),b=$.exists(X)?X:$.exists(q)?q:X,x=$.exists(b),Y=x?$.readText(b):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
|
|
12
12
|
`,H=s0(Y,W),D=[],j=[];for(let O of["plugin","plugins"]){if(!Array.isArray(H[O]))continue;for(let B of H[O]){let I=a0(B);if(I===null)continue;if(F1(I,b,Z)===z.packages.opencode)D.push(JSON.stringify(B));else if(Y0(B)===z.packages.opencode)j.push(JSON.stringify(B))}}if(D.length>0)return{path:b,content:Y,changed:!1,existingLocalEntries:D,existingNpmEntries:j};let U=o0(Y,W,z.packages.opencode,z.version);return{path:b,content:U,changed:!x||U!==Y}})}async function b0(z,J){let Z=typeof J==="function"?new f(J):J;for(let $ of z){if(!$.changed)continue;await u0($.path,$.content,{beforeRename:Z?()=>Z.check({reuse:!0}):void 0,rename:Z?(K,Q)=>Z.step(()=>q1(K,Q)):void 0,wait:Z?(K)=>Z.step(()=>Y1(K)):void 0})}}async function B0(z,J,Z={}){let{platform:$,env:K}=k(Z),Q=await o(Z.runner??w,$,J,["install",`npm:${z.packages.pi}@${z.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new r({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var e0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function H1(z){for(let J of Object.values(z.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(J))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(z.version))throw Error("Setup requires a concrete package version.");for(let J of Object.values(z.vault.hosts)){if(!/^[a-z0-9][a-z0-9-]*$/.test(J.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.");if(J.requestedGrants!==void 0&&!r0(J.requestedGrants))throw Error("invalid Claustrum enrollment requested grants");if(J.grantFallback!==void 0&&J.grantFallback!=="setup"&&J.grantFallback!=="plugin")throw Error("invalid Claustrum enrollment grant fallback")}}async function M1(z,J,Z,$){let K=[];for(let Q of J){let W=Z.get(Q)??"not-enrolled",G=$.get(Q);if(W==="unknown"){let{name:V,paths:X}=z.vault.hosts[Q],q=await i(A(X),V).catch(()=>"unreadable");if(q==="vault"||q==="host")W="enrolled";else if(q==="local")W="not-enrolled";if(W==="enrolled"){let b=await n0(A(X),V).catch(()=>{return});if(b?.state==="approved")G=await h({},b,A(X).tokenPath,z.vault.hosts[Q].requestedGrants)}}K.push({host:Q,outcome:W,...G&&{access:G}})}return K}async function V0(z,J=[],Z={}){let $=p0(J);if(e())throw Error(g);H1(z);let K=Z.terminal??t0(),Q=await W0(z,Z);F(K,`${z.displayName} setup`);for(let[B,I]of[["OpenCode",Q.opencode],["Pi",Q.pi]])F(K,`${B}: ${I.installed?`found (version ${I.version??"unknown"})`:"not found"} — ${I.directory}`);F(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let W=Q.pi.installed&&!Q.pi.executable;if(W)F(K,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let G=["opencode","pi"].filter((B)=>Q[B].installed&&!(B==="pi"&&W));if($.hosts.some((B)=>!G.includes(B)))throw Error(d0);let V=$.yes||$.dryRun&&!l(K);if(!V&&!l(K))throw Error("Setup requires a TTY or --yes.");let X=$.hosts.length?G.filter((B)=>$.hosts.includes(B)):V?G:await c0(K,G)??[],q=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(X.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(V||!l(K))throw Error(e0);let B=await u(K,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(B===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};q=B}if(!X.length)return F(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:X,dryRun:$.dryRun,mode:"local",detection:Q};let{env:b,platform:x}=k(Z),Y=Z.fence??p(Z.runner??w,{platform:x,isFile:Z.fs?.isFile.bind(Z.fs),onProgress:(B)=>F(K,B)}),D=new f(async()=>{try{await c(Y,b)}catch(B){if(B instanceof R)F(K,B.refusalText);throw B}},Z.now);if(F(K,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let B=Y.previewRunningHosts?await Y.previewRunningHosts(b):{hosts:await Y.listRunningHosts(b),uncheckedRuntimes:0},I=B.hosts;if(B.uncheckedRuntimes>0)F(K,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let T=new Set(new y(I).activeHosts.map((C)=>C.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let C of T)F(K,`${C} is running; setup will ask you to quit it.`)}catch(B){if(F(K,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),B instanceof R)F(K,B.refusalText)}else await D.check();if(($.claustrum||$.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let j=$.claustrum||$.enrollOnly;if(!j&&!$.login&&!$.noClaustrum&&!V&&Q.claustrum.available&&l(K)){let B=await D.step(()=>u(K,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"}));if(B===null)return F(K,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};j=B===!0}let U=j?"claustrum":"local",O=!$.enrollOnly&&X.includes("opencode")?D0(z,q,Z):[];for(let B of O){for(let T of B.existingLocalEntries??[])F(K,`OpenCode: already registered from ${T} in ${B.path}.`);let I=[...B.existingLocalEntries??[],...B.existingNpmEntries??[]];if(I.length>1)F(K,`Warning: ${z.displayName} may load twice in ${B.path}: ${I.join(", ")}. Entries were left unchanged.`)}if($.dryRun){F(K,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let B of X){if(z.beforeSignIn)F(K,`Would run beforeSignIn(${B}, ${U}).`);if(j){let I=A(z.vault.hosts[B].paths);F(K,`Would Connect ${B}: write ${I.statePath} and ${I.tokenPath}; wait for ck auth enroll approve.`)}else F(K,`Would sign in locally for ${B}.`);if(!$.enrollOnly&&z.beforeRegister)F(K,`Would run beforeRegister(${B}, ${U}).`)}for(let B of O)F(K,`${B.changed?"Would write":"Unchanged"} ${B.path}:
|
|
13
|
-
${B.content}`);if(!$.enrollOnly&&X.includes("pi"))F(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let B of X)F(K,`Would migrate ${B} using the plugin callback (provider-specific writes).`)}else{let B={opencodeGeneration:q,mode:U,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},I=new Map,T=new Map;try{for(let C of X){if(z.beforeSignIn)await D.check({reuse:!0}),await D.step(()=>z.beforeSignIn?.(C,B));if(j){I.set(C,"unknown");try{let M=await m0(z,C,Z,K,D);if(M)T.set(C,M)}catch(M){if(M instanceof _)I.set(C,"not-enrolled");throw M}I.set(C,"enrolled")}else await D.check({reuse:!0}),await D.step(()=>z.signInLocal(C,B));if($.enrollOnly)continue;if(z.beforeRegister)await D.check({reuse:!0}),await D.step(()=>z.beforeRegister?.(C,U,B));if(C==="opencode")await b0(O,D);else await D.check({reuse:!0}),await D.step(()=>B0(z,Q.pi.executable,Z));if(z.migrate)await D.check({reuse:!0}),await D.step(()=>z.migrate?.(C,B))}}catch(C){if(I.size===0)throw C;try{let M=await M1(z,X,I,T);k0(C,M);for(let L of M)F(K,N0(L,z.vault.hosts[L.host].grantFallback))}catch{}throw C}}if(F(K,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${U}).`),$.enrollOnly)F(K,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(K,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(K,`Next: ${X.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:X,dryRun:$.dryRun,mode:U,detection:Q}}var v={name:"@cortexkit/opencode-openai-auth",version:"1.20.
|
|
13
|
+
${B.content}`);if(!$.enrollOnly&&X.includes("pi"))F(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let B of X)F(K,`Would migrate ${B} using the plugin callback (provider-specific writes).`)}else{let B={opencodeGeneration:q,mode:U,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},I=new Map,T=new Map;try{for(let C of X){if(z.beforeSignIn)await D.check({reuse:!0}),await D.step(()=>z.beforeSignIn?.(C,B));if(j){I.set(C,"unknown");try{let M=await m0(z,C,Z,K,D);if(M)T.set(C,M)}catch(M){if(M instanceof _)I.set(C,"not-enrolled");throw M}I.set(C,"enrolled")}else await D.check({reuse:!0}),await D.step(()=>z.signInLocal(C,B));if($.enrollOnly)continue;if(z.beforeRegister)await D.check({reuse:!0}),await D.step(()=>z.beforeRegister?.(C,U,B));if(C==="opencode")await b0(O,D);else await D.check({reuse:!0}),await D.step(()=>B0(z,Q.pi.executable,Z));if(z.migrate)await D.check({reuse:!0}),await D.step(()=>z.migrate?.(C,B))}}catch(C){if(I.size===0)throw C;try{let M=await M1(z,X,I,T);k0(C,M);for(let L of M)F(K,N0(L,z.vault.hosts[L.host].grantFallback))}catch{}throw C}}if(F(K,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${U}).`),$.enrollOnly)F(K,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(K,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(K,`Next: ${X.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:X,dryRun:$.dryRun,mode:U,detection:Q}}var v={name:"@cortexkit/opencode-openai-auth",version:"1.20.3",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.56.3","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.3.0","@opencode/plugin":"2.3.0"},dependencies:{"@cortexkit/claustrum-client":"^0.20.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.9.0","@opentui/solid":">=0.9.0",ai:"^7.0.173","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as k1}from"node:path";import{resolveClaustrumConnectionPath as _1}from"@cortexkit/claustrum-client";var z2={name:"@cortexkit/pi-openai-auth",version:"1.20.3",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.56.3","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.20.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","jsonc-parser":"^3.3.1"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as J0}from"node:fs";import{homedir as Z0}from"node:os";import{join as $0,resolve as J2}from"node:path";import{fileURLToPath as C1}from"node:url";var Z2=new Set;function R1(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return $0(Z0(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return Z0();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return $0(Z0(),z.slice(2));return z.startsWith("file://")?C1(z):z}function K2(z=R1()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=$0(z,x0),$=$0(Z0(),".pi","agent",x0),K=(W)=>{let G=U0(W),V=$2(a(G),"pi");return J0(W)||J0(G)||J0(V.tokenPath)||J0(V.statePath)};if(J2(Z)===J2($)||K(Z)||!K($))return Z;let Q=`${Z}\x00${$}`;if(!Z2.has(Q))Z2.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${$} (${Z} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return $}function N1(z=K2()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||U0(z)}function Q2(z=K2()){return{configPath:z,statePath:N1(z)}}function Y2(z={}){let J=z.print??console.log,Z=z.fence??(z.createFence??p)(void 0,{onProgress:J}),$={opencode:{stateDir:a(G2().statePath),host:"opencode"},pi:{stateDir:a(Q2().statePath),host:"pi"}},K=async(Q)=>{let W=await i(A($[Q]),s(Q));if(W==="host")throw Error(g);if(W!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:v.name,pi:z2.name},version:v.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:_1(),hosts:{opencode:{name:s("opencode"),displayName:H0("opencode"),requestedGrants:F0,paths:$.opencode},pi:{name:s("pi"),displayName:H0("pi"),requestedGrants:F0,paths:$.pi}}},async beforeRegister(Q,W){if(await i(A($[Q]),s(Q))==="host")throw Error(g);if(W==="claustrum"){if(Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,W){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(W.opencodeGeneration!=="1"){let j=k1(P("opencode2",z.io)??P("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${j} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(W.opencodeGeneration==="2")return;if(j2(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let G=q2(),V={path:{id:"openai"}};if(await G.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??W2,q=new AbortController,b=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),x={version:v.version,signal:q.signal},Y,H=!b;try{Y=await X({...x,headless:b})}catch(j){if(b)throw j;H=!1,J("Browser callback unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}if(H){if(!(z.openBrowser??X2)(Y.url))q.abort(),await Y.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}J(`${Y.url}
|
|
14
14
|
${Y.instructions}`);let D=await Y.completion;await c(Z),await K(Q),await G.set({...V,body:{type:"oauth",access:D.access,refresh:D.refresh,expires:D.expires,...D.accountId?{accountId:D.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await D2({version:v.version}),await V0(Y2(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
|
|
@@ -833,8 +833,12 @@ interface ScopedUsageSource {
|
|
|
833
833
|
enrollmentToken?: string;
|
|
834
834
|
}): Promise<void>;
|
|
835
835
|
}
|
|
836
|
-
type ScopedRow = Omit<ScopedInventoryRow, 'authMethod'> & {
|
|
836
|
+
type ScopedRow = Omit<ScopedInventoryRow, 'authMethod' | 'condition'> & {
|
|
837
837
|
readonly authMethod?: string;
|
|
838
|
+
readonly condition?: {
|
|
839
|
+
readonly reason: string;
|
|
840
|
+
readonly sinceMs: number;
|
|
841
|
+
};
|
|
838
842
|
};
|
|
839
843
|
type ScopedInventory = Omit<Awaited<ReturnType<ClaustrumClient['listScoped']>>, 'rows'> & {
|
|
840
844
|
readonly rows: readonly ScopedRow[];
|
|
@@ -842,9 +846,23 @@ type ScopedInventory = Omit<Awaited<ReturnType<ClaustrumClient['listScoped']>>,
|
|
|
842
846
|
/**
|
|
843
847
|
* claustrum-client adds watchScoped in 0.12.0 and reportUsageScoped in 0.14.0.
|
|
844
848
|
* Older clients keep polling and simply do not send reply quota readings.
|
|
849
|
+
* The optional login condition methods match 0.21.0 without requiring it.
|
|
845
850
|
*/
|
|
846
851
|
type ClaustrumScopedClient = Pick<ClaustrumClient, 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
|
|
847
852
|
listScoped(enrollmentToken?: string): Promise<ScopedInventory>;
|
|
853
|
+
reportCondition?(input: {
|
|
854
|
+
credentialId: string;
|
|
855
|
+
recordVersion: number;
|
|
856
|
+
reason: string;
|
|
857
|
+
providerStatus: number;
|
|
858
|
+
actionUrl?: string;
|
|
859
|
+
enrollmentToken?: string;
|
|
860
|
+
}): Promise<void>;
|
|
861
|
+
clearCondition?(input: {
|
|
862
|
+
credentialId: string;
|
|
863
|
+
recordVersion: number;
|
|
864
|
+
enrollmentToken?: string;
|
|
865
|
+
}): Promise<boolean>;
|
|
848
866
|
insula?: InsulaUsageTransport;
|
|
849
867
|
} & ScopedWatchSource & ScopedUsageSource;
|
|
850
868
|
/** The two credential types a plugin's family can hold; routing differs by type. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Kg as G,Mg as H}from"./index-
|
|
1
|
+
import{Kg as G,Mg as H}from"./index-eb631m0m.js";function Q(x){return x==="chatgptaccountid"||x==="email"||x==="orgname"||x==="organizationname"}var S=G({extraSecretKeys:Q}),I=S.redact,N=S.redactStrings;function O(x){H({...x,extraSecretKeys:Q})}function C(x){if(x instanceof Error)return x.message;if(typeof x==="string")return x;try{return JSON.stringify(x)}catch{return String(x)}}function v(x){return"notify"in x}import{basename as X,dirname as Y,join as Z}from"node:path";var $="openai-auth.json",b="openai-auth-state.json";function p(x){return X(x)===$?Z(Y(x),b):`${x}.state.json`}import{spawn as j}from"node:child_process";function z(x,J=process.platform,q=j){try{if(J==="win32"){let U=`Start-Process '${x.replaceAll("'","''")}'`,V=Buffer.from(U,"utf16le").toString("base64"),T=q("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",V],{stdio:"ignore",windowsHide:!0});return T.on("error",()=>{}),T.unref(),T.pid!==void 0}let u=q(J==="darwin"?"open":"xdg-open",[x],{stdio:"ignore"});return u.on("error",()=>{}),u.unref(),u.pid!==void 0}catch{return!1}}export{N as Cg,O as Dg,$ as Eg,b as Fg,p as Gg,C as Hg,v as Ig,z as Jg};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{uc as X,wc as V}from"./index-
|
|
1
|
+
import{uc as X,wc as V}from"./index-vjb3rsqh.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,4 +1,4 @@
|
|
|
1
|
-
import{$g as c,Qg as _,Rg as U,Vg as g,Wg as p,Xg as E}from"./index-
|
|
1
|
+
import{$g as c,Qg as _,Rg as U,Vg as g,Wg as p,Xg as E}from"./index-tn1ve0gx.js";import{createHash as Oz,randomUUID as y}from"node:crypto";import{chmod as zz,mkdir as Gz,open as Jz,readdir as F,rename as Kz,rmdir as Nz,stat as T,unlink as I}from"node:fs/promises";import{uptime as Qz}from"node:os";import{join as A,resolve as b}from"node:path";function S(z){return(z.now??Date.now)()-(z.uptime??Qz)()*1000-300000}function x(z,J,Q){let X=z.startedAt===void 0?J?.mtimeMs:z.startedAt;return typeof X==="number"&&Number.isFinite(X)&&X<Q}async function Vz(z,J,Q,X){if(!Q)return;await X?.(z);try{let K=await E(z),G=await T(z);if(K===J&&G.dev===Q.dev&&G.ino===Q.ino&&G.mtimeMs===Q.mtimeMs&&G.size===Q.size)await I(z).catch(()=>{})}catch(K){if(K instanceof U&&K.code!=="ENOENT")throw K}}function a(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function k(z){if(!a(z))return!1;try{return process.kill(z,0),!0}catch(J){return J.code==="EPERM"}}function Ez(z){return(J)=>Wz(J,z)}function Wz(z,J){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(J)&&/^[0-9a-f]{16}$/.test(z.slice(J.length))}function Xz(z){let J=/^port-(\d+)\.json$/.exec(z);return J?Number(J[1]):void 0}function s(z,J){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:Q,port:X,token:K}=z;return a(Q)&&Xz(J)===Q&&typeof X==="number"&&Number.isInteger(X)&&X>=1&&X<=65535&&typeof K==="string"&&K.length>0}async function l(z,J){J?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await I(z).catch(()=>{})}async function Lz(z,J,Q={}){let X=async()=>{let K=A(z,`port-${J.pid}.json`);if(_)return await p(z,Q.secureDir??!1),await Q.beforeWrite?.(),await c(K,JSON.stringify({...J,startedAt:Date.now()}),{stagePath:`${K}.${(Q.stageName??y)()}.tmp`}),K;if(await Gz(z,{recursive:!0,mode:Q.secureDir?448:void 0}),Q.secureDir)await zz(z,448);await Q.beforeWrite?.();let G={...J,startedAt:Date.now()},Y=`${K}.${(Q.stageName??y)()}.tmp`,V,N=!1;try{V=await Jz(Y,"wx",384),N=!0,await V.writeFile(JSON.stringify(G),"utf8"),await V.chmod(384),await V.close(),V=void 0,await Kz(Y,K),N=!1}finally{if(await V?.close().catch(()=>{}),N)await I(Y).catch(()=>{})}return K};for(let K=1;;K+=1)try{return await X()}catch(G){if(G.code!=="ENOENT"||K===5)throw G;await new Promise((Y)=>setTimeout(Y,25))}}async function Iz(z,J,Q,X,K={}){let G=S(K),Y;try{Y=await F(z,{withFileTypes:!0})}catch(N){if(N.code==="ENOENT")return;throw N}let V=b(J);for(let N of Y){if(!N.isDirectory()||!Q(N.name))continue;let W=A(z,N.name);if(!await Yz(W,X,K,G))continue;if(b(W)!==V)await Nz(W).catch(()=>{})}}async function Yz(z,J,Q={},X=S(Q)){let K;try{K=await F(z)}catch(G){if(G.code==="ENOENT")return!1;throw G}for(let G of K){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;let Y=A(z,G),V=await T(Y).catch(()=>{return}),N;try{N=await E(Y)}catch($){if($ instanceof U&&$.code!=="ENOENT")throw $;continue}if(N===void 0)continue;let W;try{W=JSON.parse(N)}catch{await l(Y,J);continue}if(!s(W,G)){await l(Y,J);continue}let Z=W;if(!k(Z.pid))await I(Y).catch(()=>{});else if(x(Z,V,X))await Vz(Y,N,V,Q.beforeRemove)}return!0}async function d(z,J,Q={}){let X=S(Q);if(!k(J.pid))return null;let K=A(b(z),`port-${J.pid}.json`);try{if(_)await g(K,"file");let G=await T(K);if(x(J,G,X))return null;return`${K}:${G.dev}:${G.ino}:${G.mtimeMs}:${G.size}`}catch(G){if(G instanceof U&&G.code!=="ENOENT")throw G;return null}}async function n(z,J,Q={}){let X=S(Q),K;try{if(_)await g(z,"directory");K=await F(z)}catch(W){if(W instanceof U&&W.code!=="ENOENT")throw W;return null}let G=[];for(let W of K){if(!W.startsWith("port-")||!W.endsWith(".json"))continue;try{let Z=JSON.parse(await E(A(z,W)));if(s(Z,W))if(k(Z.pid)){let $=Z.startedAt===void 0?await T(A(z,W)).catch(()=>{return}):void 0;if(!x(Z,$,X))G.push(Z)}else await I(A(z,W)).catch(()=>{})}catch(Z){if(Z instanceof U&&Z.code!=="ENOENT")throw Z}}if(G.length===0)return null;let Y=J!==void 0&&J>=1?G.filter((W)=>W.pid===J):[];if(Q.exactPid===!0&&Y.length===0)return null;let V=Y.length>0?Y:G,N=(W)=>typeof W.startedAt==="number"&&Number.isFinite(W.startedAt)?W.startedAt:-1/0;return V.sort((W,Z)=>N(Z)-N(W))[0]??null}import{open as Zz}from"node:fs/promises";import{connect as $z}from"node:net";import{join as Hz,resolve as t}from"node:path";var e=2000,q=new Map,B=new Map;async function qz(z,J){let Q=Hz(t(z),`port-${J.pid}.json`);if(_){let K=JSON.parse(await E(Q));if(K.pid!==J.pid||K.port!==J.port||K.token!==J.token)return null;return null}let X;try{X=await Zz(Q,"r");let K=await X.stat(),G=JSON.parse(await X.readFile("utf8"));if(G.pid!==J.pid||G.port!==J.port||G.token!==J.token)return null;return`${Q}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch{return null}finally{await X?.close().catch(()=>{})}}async function i(z,J,Q,X){let K=q.get(z);if(!_&&K&&await d(J,K.entry)===K.identity)return K;q.delete(z);let G=B.get(z);if(G)return G;let Y=(async()=>{let V=await(X.discover??n)(J,Q,X);if(!V)return null;let N=await qz(J,V);if(!N)return{entry:V,identity:""};let W={entry:V,identity:N};return q.set(z,W),W})();B.set(z,Y);try{return await Y}finally{if(B.get(z)===Y)B.delete(z)}}async function o(z,J,Q,X=e){return new Promise((K)=>{let G,Y=!1,V=!1,N=(Z,$=!1)=>{if(Y)return;Y=!0,clearTimeout(W),G?.destroy(),K({value:Z,stale:$})},W=setTimeout(()=>N(null),X);try{let Z=JSON.stringify(Q);G=$z({host:"127.0.0.1",port:z.port}),G.on("connect",()=>{V=!0,G?.write(`POST /rpc/${J} HTTP/1.0\r
|
|
2
2
|
Host: 127.0.0.1:${z.port}\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
Content-Type: application/json\r
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$a as DJ,$b as q7,Ab as $Q,Bb as QQ,Ca as UU,Cb as GQ,Cc as PU,Db as q4,Ea as i5,Eb as D5,Ec as qU,Fa as n5,Fb as y9,Fc as EU,Ga as eY,Gb as f9,Gc as yU,Ha as YJ,Hc as NQ,Ia as DQ,Ic as fU,Ja as L$,Jc as gU,Ka as SJ,Kc as OQ,La as Z$,Ma as F$,Qb as O5,Ra as D$,Rb as x9,Sa as O$,Sb as _5,Ta as _$,Tb as P5,Ua as P$,Va as UQ,Vb as LU,Wa as F4,Xa as E9,Xb as n1,Ya as K1,Za as FJ,Zb as E4,_a as k1,ab as OJ,ac as MJ,bb as _J,bc as O4,cb as PJ,cc as FU,db as qJ,dc as m1,eb as o$,fb as u$,fc as E$,gb as I9,gc as a7,hb as KU,hc as t7,ib as NU,ic as A$,jb as W3,jc as DU,kb as B3,kc as M2,lc as OU,mb as JQ,mc as z8,nb as XQ,nc as JJ,ob as D3,oc as c9,pb as O3,pc as u9,qa as N4,qb as jU,qc as j4,ra as J8,rb as g9,rc as v5,sa as aH,sc as W8,ta as E0,tb as H3,tc as T2,ua as l5,ub as A4,uc as M$,va as y5,vb as S5,wb as b5,xa as n,xb as k5,xc as _U,ya as FQ,yb as x5,yc as d1,zb as h5}from"./index-rbc7cfbv.js";import{$c as TU,Oc as C3,Qc as q5,Sc as i0,Tc as AU,Wc as MU,_c as TQ,ad as RU,bd as CU,gd as XJ,hd as $J,id as IU,jd as wU,md as SU,nd as bU,od as kU,qd as m9,rd as _8,sd as xU,td as hU,ud as Y4,vd as vU}from"./index-8ge0as5s.js";import{$d as Q$,$e as Q7,Ae as K0,Af as WU,Be as N0,Bf as w5,Ce as f1,Cf as d5,Dd as J1,De as U$,Df as u0,Ee as V$,Ef as J0,Fd as K4,Fe as B$,Ff as y1,Ge as K$,Gf as wJ,He as N$,Ie as j$,Je as M9,Jf as HU,Ke as Y1,Kf as D4,Ld as T4,Le as g4,Lf as j0,Md as p5,Me as _H,Mf as I0,Ne as u6,Nf as o5,Oe as JU,Of as A8,Pe as s8,Pf as VU,Qd as j3,Qe as H8,Re as XU,Rf as r5,Sf as s5,Td as _7,Te as $U,Ue as V0,Uf as BU,Ve as s4,Vf as a5,We as N1,Wf as L3,Xe as H9,Xf as t5,Ye as W4,Yf as e5,Ze as a4,Zf as YQ,_d as F5,_e as U9,_f as R3,ae as G$,af as h1,be as A9,bf as U4,cf as Z7,df as a0,ef as Q8,ff as KQ,gf as c0,hf as P7,if as a6,je as z$,jf as K9,kf as QU,nf as s7,of as g1,pf as GU,qf as T9,re as r7,sf as Z3,te as O8,tf as a8,ue as eH,uf as F3,ve as e0,vf as o1,we as A2,wf as k9,xe as YU,xf as j1,ye as W$,yf as n0,ze as H$,zf as zU}from"./index-x3q449sn.js";import{dg as h9,ig as O7}from"./index-z4tfv40j.js";import{ng as e$,og as Y5,pg as J5,qg as fQ,rg as tH,sg as p0,tg as gQ,ug as mQ}from"./index-jky7c65x.js";import{Hg as y4,Jg as q$}from"./index-0mf78d7s.js";import{Kg as v$,Ng as b9,Pg as $6}from"./index-xcsz00nr.js";import{$g as h$,Qg as l0,Rg as V8,Vg as b$,Wg as k$,Xg as vJ,Yg as x$}from"./index-c4h4t3wg.js";import{bh as X5,dh as ZU}from"./index-qtaqp1bf.js";import{fh as f3}from"./index-t15pb3n2.js";import{randomUUID as lH}from"node:crypto";import{statSync as pD}from"node:fs";import _2 from"node:os";import{isDeepStrictEqual as PV}from"node:util";var G7={hosts:"OpenCode 1, OpenCode 2 and Pi",project:"user-only"},g0={...G7,overrides:{host:!0}},m0={hosts:"OpenCode 1 and OpenCode 2",project:"user-only"},r4={hosts:"OpenCode 1 only",project:"user-only"},z7=(Y,J)=>Y.flatMap((X)=>J.map(($)=>({source:X,path:$}))),M0=(...Y)=>z7(["opencode-store","pi-store"],Y),s6=(...Y)=>z7(["opencode-store"],Y),T6=Q7({plugin:"openai-auth",settings:{routing_mode:{...g0,value:W4(["ordered","main-first","fallback-first","sticky-balanced"]),default:"main-first",legacy:M0(["routing","mode"])},max_same_account_wait:{...g0,value:W4(["off","15m","cache"]),default:"15m",legacy:M0(["routing","maxSameAccountWait"])},fallback_on:{...g0,hosts:"OpenCode 1 and Pi; not read by OpenCode 2",value:a4(s4()),default:[401,403,429],legacy:M0(["fallbackOn"])},refresh_enabled:{...r4,hosts:"OpenCode 1 legacy fallback refresh only",value:V0(),default:!0,legacy:s6(["refresh","enabled"])},refresh_before_expiry_minutes:{...g0,value:N1(),default:240,legacy:M0(["refresh","refreshBeforeExpiryMinutes"])},quota_enabled:{...g0,value:V0(),default:!0,legacy:M0(["quota","enabled"])},quota_check_interval_minutes:{...r4,hosts:"OpenCode 1 legacy quota freshness and polling only",value:N1({min:1}),default:5,legacy:s6(["quota","checkIntervalMinutes"])},quota_minimum_remaining:{...g0,value:a4(U9({window:W4(["primary","secondary"]),floor:N1()})),default:[],legacy:M0(["quota","minimumRemaining","primary"],["quota","minimumRemaining","5h"],["quota","minimumRemaining","secondary"],["quota","minimumRemaining","1w"])},quota_fail_closed_on_unknown:{...g0,value:V0(),default:!1,legacy:M0(["quota","failClosedOnUnknownQuota"])},cost_zeroing:{...r4,value:V0(),default:!0,legacy:s6(["costZeroing","enabled"])},killswitch_enabled:{...g0,value:V0(),default:!1,legacy:M0(["killswitch","enabled"])},killswitch_default_primary:{...g0,value:N1(),default:5,legacy:M0(["killswitch","defaults","primary"],["killswitch","main","primary"],["killswitch","main","5h"])},killswitch_default_secondary:{...g0,value:N1(),default:10,legacy:M0(["killswitch","defaults","secondary"],["killswitch","main","secondary"],["killswitch","main","1w"])},killswitch_account_floors:{...G7,value:a4(U9({account:H9(),host:W4(["opencode","pi","both"]),primary:N1(),secondary:N1()})),default:[],legacy:M0(["killswitch","accounts"])},cache_keep_enabled:{...m0,value:V0(),default:!1,legacy:s6(["cacheKeep","enabled"],["cachekeep","enabled"])},cache_keep_subagents:{...m0,value:V0(),default:!1,legacy:s6(["cacheKeep","subagents"],["cachekeep","subagents"])},cache_keep_sustain:{...m0,value:V0(),default:!1,legacy:s6(["cacheKeep","sustain"],["cachekeep","sustain"])},cache_keep_window:{...m0,value:a4(U9({start_hour:s4({min:0,max:23}),end_hour:s4({min:0,max:23})})),default:[],legacy:s6(["cacheKeep","startHour"],["cacheKeep","endHour"],["cachekeep","startHour"],["cachekeep","endHour"])},log_level:{...m0,value:W4(["error","warn","info","debug","trace","default"]),default:"default",legacy:s6(["logging","level"])},request_dumps:{...m0,value:V0(),default:!1,legacy:s6(["dump"],["dump","enabled"])},dump_dir:{...m0,value:H9(),default:"",legacy:s6(["dumpDir"])},dump_max_bytes:{...m0,value:s4({min:0,max:Number.MAX_SAFE_INTEGER}),default:536870912,legacy:s6(["dumpMaxBytes"])},web_sockets:{...r4,value:V0(),default:!1,legacy:s6(["webSockets"])},raw_web_socket:{...r4,value:V0(),default:!1,legacy:s6(["rawWebSocket"])},responses_lite:{...m0,value:V0(),default:!1,legacy:s6(["responsesLite"])},codex_api_endpoint:{...m0,value:H9(),default:"https://chatgpt.com/backend-api/codex/responses",legacy:s6(["codexApiEndpoint"])}}});import{chmod as LV,mkdir as ZV}from"node:fs/promises";import{join as FV}from"node:path";import{existsSync as U7,readFileSync as $V}from"node:fs";import{readFileSync as YV}from"node:fs";var W7="Settings moved to ";function JV(Y){let J=Y.split(/\r?\n/,1)[0]??"";if(!J.startsWith(W7)||!J.endsWith("."))return;return J.slice(W7.length,-1)}function XV(Y){try{return JV(YV(`${Y}.MOVED_READPLEASE`,"utf8"))}catch{return}}function H7(Y,J){let X=XV(Y);return X!==void 0&&a0(X)===a0(J)}function QV(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function GV(Y,J){let X=Y;for(let[$,Q]of J.entries()){if(!QV(X)||!Object.hasOwn(X,Q))return!1;if($===J.length-1)return!0;X=X[Q]}return!1}function zV(Y,J){return Object.values(T6.settings).some((X)=>X.legacy.some(($)=>$.source===`${J}-store`&&GV(Y,$.path)))}function WV(Y){try{return zV(JSON.parse($V(Y.configPath,"utf8")),Y.host)}catch{return!1}}function V9(Y){let J=U7(Y.target),X=Y.sources.some((H)=>H7(H.configPath,Y.target)),$=Y.sources.filter((H)=>U7(H.configPath)),Q=$.length>0,G=X&&!J,z=J&&!X&&$.some(WV);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 B9(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function V7(Y){try{let J=Number(Y);return Number.isFinite(J)?Math.min(100,Math.max(0,J)):0}catch{return 0}}function EJ(Y,J){let X=j1(Y,J);return{primary:V7(X.primary),secondary:V7(X.secondary)}}function B7(Y,J,X,$){if(!B9(Y))return;for(let Q of["primary","secondary","5h","1w"])if(Y[Q]===null)$.push({source:X,key:`${J}.${Q}`,reason:"invalid"})}function K7(Y){let J={entries:[],unmapped:[]},X=[],$=[];Y.forEach((z,H)=>{if(!z.present)return;if(z.host!=="opencode"&&z.host!=="pi")throw Error("Unsupported killswitch floors source host");let U=z.host,V=B9(z.value)?z.value:{},B=B9(V.killswitch)?V.killswitch:void 0,F={killswitch:V.killswitch},j=B?.schema===K9,N=j?EJ({killswitch:{...B,accounts:void 0}}):EJ(F);if(X.push({source:H,floors:N}),!j)B7(B?.main,"killswitch.main",H,J.unmapped);if(!B9(B?.accounts))return;for(let Z of Object.keys(B.accounts)){let P=`killswitch.accounts.${Z}`;if(!j&&Z==="main"){J.unmapped.push({source:H,key:P,reason:"shadowed"});continue}if(!j)B7(B.accounts[Z],P,H,J.unmapped);$.push({account:Z,host:U,...EJ(F,Z==="main"?void 0:Z)})}});for(let[z,H]of[["primary",5],["secondary",10]]){if(X.every(({floors:U})=>U[z]===H))continue;for(let{source:U,floors:V}of X)J.entries.push({source:U,setting:`killswitch_default_${z}`,value:V[z]})}let Q=[];for(let z of $){let H=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(H)H.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 L1(Y){if(Y===null||typeof Y!=="object"||Array.isArray(Y))return!1;let J=Object.getPrototypeOf(Y);return J===Object.prototype||J===null}function N7(Y){let J;try{J=JSON.parse(Y)}catch{throw Error("Settings source is not JSON")}if(!L1(J))throw Error("Settings source is not an object");return J}function H4(Y,J){let X=Y;for(let $ of J){if(!L1(X)||!Object.hasOwn(X,$))return;X=X[$]}return X}function t4(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(($)=>t4(Y.item,$,!0));case"object":return L1(J)&&Object.entries(J).every(([$,Q])=>{let G=Y.fields[$];return Object.hasOwn(Y.fields,$)&&G!==void 0&&t4(G,Q,X)})&&(!X||Object.keys(Y.fields).every(($)=>Object.hasOwn(J,$)));case"record":return L1(J)&&Object.values(J).every(($)=>t4(Y.value,$,!0))}}class j9 extends Error{setting;key;constructor(Y,J){super(`Cannot move setting ${Y}${J?` (${J})`:""}`);this.setting=Y;this.key=J;this.name="CannotMoveSettingError"}}function N9(Y,J){throw new j9(Y,J)}function j7(Y,J,X){try{let $=Number(Y);if(Number.isFinite($))return $}catch{}return N9(J,X)}function HV(Y,J){let X=[];for(let[$,Q]of[["primary","5h"],["secondary","1w"]]){let G=["quota","minimumRemaining"],z=H4(Y,[...G,$]),H=H4(Y,[...G,Q]);for(let[V,B]of[[$,z],[Q,H]])if(B===null)J([...G,V].join("."),"invalid");if(z!=null&&H!=null)J([...G,Q].join("."),"shadowed");let U=z??H;if(U==null)continue;X.push({window:$,floor:j7(U,"quota_minimum_remaining",[...G,$].join("."))})}return X}function UV(Y,J,X){let $=H4(Y,[J,"startHour"]),Q=H4(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 VV(Y,J,X){let $=T6.settings[Y],Q=$.default;if(Y==="quota_minimum_remaining")return HV(J,X);let G=L1(J.cacheKeep)?"cacheKeep":"cachekeep";if(Y==="cache_keep_window")return UV(J,G,X);let z=$.legacy[0];if(!z)return N9(Y);let H=z.path;if(Y.startsWith("cache_keep_"))H=[G,...H.slice(1)];if(Y==="request_dumps")H=typeof J.dump==="boolean"?["dump"]:["dump","enabled"];let U=H4(J,H),V=H.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 B=U.filter((F)=>Number.isInteger(F));if(B.length!==U.length)X(V,"invalid");return B.length?B:Q}}else if(Y==="refresh_before_expiry_minutes"||Y==="quota_check_interval_minutes"){if(U!=null){let B=j7(U,Y,V);return Y==="quota_check_interval_minutes"?Math.max(1,B):B}}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(t4($.value,U))return U;return X(V,"invalid"),Q}var BV=new Set(["version","accounts","main","commonAuthPool","commonAuthLimits","openaiAuthPool","mainAccountId","reset","claustrum"]),KV=new Set(["refresh.mainLastRefreshError","refresh.mainRefreshLeaseId","refresh.mainRefreshLeaseUntil","refresh.mainRefreshLeaseTokenHash","quota.mainQuota","quota.mainQuotaCheckedAt","quota.mainQuotaToken","quota.mainLastQuotaApiError"]);function NV(Y,J,X){let $=new Set;for(let G of Object.values(T6.settings))for(let z of G.legacy){let H=z.path.join(".");if($.add(H),J==="pi"&&!G.legacy.some((U)=>U.source==="pi-store")&&H4(Y,z.path)!==void 0){if(H==="dump.enabled"&&Object.hasOwn(Y,"dump"))continue;X(H,"other-host")}}let Q=(G,z="")=>{for(let[H,U]of Object.entries(G)){let V=z?`${z}.${H}`:H;if(!z&&BV.has(H)||KV.has(V)||V==="killswitch.schema")continue;if($.has(V))continue;if([...$].some((B)=>B.startsWith(`${V}.`)))if(L1(U))Q(U,V);else X(V,"invalid");else X(V,"retired")}};if(Q(Y),J==="opencode"&&L1(Y.cacheKeep)&&Y.cachekeep!==void 0)X("cachekeep","shadowed")}function L7(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(!L1(Q.value))throw Error("Settings source is not an object");let z=(H,U)=>{if(!J.unmapped.some((V)=>V.source===G&&V.key===H&&V.reason===U))J.unmapped.push({source:G,key:H,reason:U})};return NV(Q.value,Q.host,z),[{source:G,host:Q.host,store:Q.value,report:z}]});for(let Q of Object.keys(T6.settings)){if(Q.startsWith("killswitch_default_")||Q==="killswitch_account_floors")continue;let G=T6.settings[Q],z=X.filter((H)=>G.legacy.some((U)=>U.source===`${H.host}-store`)).map((H)=>({source:H.source,value:VV(Q,H.store,H.report)}));if(z.every((H)=>JSON.stringify(H.value)===JSON.stringify(G.default)))continue;for(let H of z)J.entries.push({...H,setting:Q})}let $=K7(Y);J.entries.push(...$.entries),J.unmapped.push(...$.unmapped);for(let Q of J.entries){if(!Object.hasOwn(T6.settings,Q.setting))N9(Q.setting);if(!t4(T6.settings[Q.setting].value,Q.value))N9(Q.setting)}return J}class AJ 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 F7(Y){let J=Y?.code;return typeof J==="string"&&/^[A-Z][A-Z0-9_]*$/.test(J)?J:"SETTINGS_MOVE_FAILED"}function jV(Y,J){if(Y instanceof AJ)return{kind:"cause",host:Y.host,path:Y.path,code:Y.code};if(Y instanceof j9)return{kind:"setting",setting:Y.setting};let X=Y?.path,$=J.find((G)=>G.path===X),Q=F7(Y);if($)return{kind:"cause",host:$.host,path:$.path,code:Q};return{kind:"cause",code:Q}}async function D7({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 N7(z)}catch(H){throw new AJ(G.host,G.configPath,H instanceof Error&&H.message==="Settings source is not JSON"?"SOURCE_NOT_JSON":"SOURCE_NOT_OBJECT")}}})),Q=await Z7({definition:T6,target:Y.target,separateInstall:!1,sources:$,map:L7,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((H)=>`${H.path}.MOVED_READPLEASE`===G.path);X.warn(`Settings move note: ${z?.host??"unknown"} ${G.path}: ${F7(G.error)}`)}if(Q.outcome==="failed"){Q.failure=jV(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 Z9 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 E7=Symbol.for("@cortexkit/openai-auth/settings-authority"),A7=globalThis,L9=A7[E7]??new Map;A7[E7]=L9;function e4(Y){return L9.get(a0(Y))}function M7(Y){let J=a0(Y.install.configIdentity),X=L9.get(J);if(X)return X;let $=Promise.resolve().then(()=>DV(Y));return L9.set(J,$),$}async function DV({install:Y,stateHome:J,record:X,log:$,fenceOptions:Q}){let G={decision:Y.separate?"separate":"shared",install:Y,ranMove:!1},z=()=>{return P7(Y.configIdentity,G.decision),G};if(Y.separate){try{await X("separate")}catch{}return z()}let H=q7(J),U=()=>{return G.completion=V9(Y),G.completion},V=(B)=>B.completed||!B.sourcePresent;try{return await ZV(H,{recursive:!0,mode:448}),await LV(H,448),await O7(FV(H,"settings-authority"),{name:"settings-authority",..._7},async(B)=>{if(!V(U()))if(G.fence=await MJ({...Q,stateHome:J}),G.fence.open){G.ranMove=!0;try{G.move=await D7({install:Y,log:$,async fence(){let N=await MJ({...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,j=U();G.decision=F==="moved"||F==="done-already"||F==="aborted-target-appeared"||j.completed?"shared":"legacy"}else G.decision="legacy";await B.assertOwned(),await X(G.decision)}),z()}catch(B){if(!V(U()))throw new Z9(H,B);return G.decision="shared",z()}}var x1=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.",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 F9(Y){return x1.refusal[Y]}function OV(Y){let J=x1;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 _V(Y,J,X=!1){let $=x1;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 T7=Symbol.for("@cortexkit/openai-auth/settings-diagnostics"),R7=globalThis,Y8=R7[T7]??{logged:new Set,sawTargetMissing:new Set};R7[T7]=Y8;async function C7({configPath:Y,snapshot:J,log:X}){let $=e4(Y);if(!$)throw Error("Settings authority has not been decided");let Q;try{Q=await $}catch(U){if(U instanceof Z9||U instanceof Error&&U.name==="SettingsAuthorityRefusal"&&"folder"in U&&typeof U.folder==="string"){let V=U.cause;return{lines:[x1.refused(String(U.folder),V instanceof Error?V.message:String(V))]}}throw U}if(Q.decision==="separate")return{lines:[x1.separate]};let G=Q.decision==="shared"?V9(Q.install):Q.completion,z=a0(Q.install.target);if(Q.decision==="shared"&&!G?.targetExists)Y8.sawTargetMissing.add(z);let H=[x1.file(Q.install.target),_V(Q,G,Y8.sawTargetMissing.has(z))];if(Q.decision==="shared"&&G){for(let U of["preExistingFile","removedFile"]){if(!G[U])continue;let V=x1[U](Q.install.target);H.push(V);let B=`${U}:${a0(Q.install.target)}`;if(!Y8.logged.has(B))Y8.logged.add(B),X.warn(V)}await J?.refresh(),H.push(...J?.report().map(OV)??[])}return{lines:H}}var T0=(Y)=>n(Y)?Y:{};function I7(Y){let{routing:J,killswitch:X}=Y.view(),$=Object.fromEntries(Object.entries(X?.accounts??{}).map(([Q,G])=>[Q,Object.fromEntries(Object.entries(T0(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 qV(Y){let J=new Set,X=!1,$=!0,Q=(z)=>{if(!$)return;if(z[0]!=="killswitch"||z[1]!=="accounts")return;if(X=!0,z[2]!==void 0)J.add(z[2])},G=(z,H)=>new Proxy(z,{ownKeys(U){return Q(H),Reflect.ownKeys(U)},get(U,V){let B=Reflect.get(U,V);return typeof V==="string"&&n(B)?G(B,[...H,V]):B},set(U,V,B){if(typeof V==="string")Q([...H,V]);return Reflect.set(U,V,B)},deleteProperty(U,V){if(typeof V==="string")Q([...H,V]);return Reflect.deleteProperty(U,V)}});return{value:G(Y,[]),accounts:J,touched:()=>X,finish:()=>{$=!1}}}function X8(Y){let{host:J,snapshot:X}=Y,$=Y.writer??U4(T6,{file:Y.file,log:Y.log,separateInstall:!1,createMissing:!0});return{async read(){return await X.refresh(),I7(X)},async update(Q){try{await X.refresh();let G=I7(X),z=qV(structuredClone(G)),H=await Q(z.value)??z.value;z.finish();let U=JSON.parse(JSON.stringify(H)),V=[],B=T0(U.routing),F=T0(G.routing);if(B.mode!==F.mode)V.push({setting:"routing_mode",value:B.mode});if(B.maxSameAccountWait!==F.maxSameAccountWait)V.push({setting:"max_same_account_wait",value:B.maxSameAccountWait===0?"off":B.maxSameAccountWait==="max"?"cache":"15m"});let j=T0(U.killswitch);if(j.enabled!==T0(G.killswitch).enabled)V.push({setting:"killswitch_enabled",value:j.enabled});let N=T0(T0(G.killswitch).accounts),Z=T0(j.accounts);for(let A of new Set([...Object.keys(N),...Object.keys(Z)]))if(!PV(N[A],Z[A]))z.accounts.add(A);let P=z.touched()||z.accounts.size>0;if(P){if(X.report().some((A)=>A.keyPath[0]==="killswitch_account_floors"||A.reason==="unreadable"||A.reason==="unparseable"))throw new h1("settings-invalid-value",Y.file)}await $.update((A)=>{let x=[...V];if(P){let q=A.status==="ready"&&Object.hasOwn(A.document,"killswitch_account_floors")?A.document.killswitch_account_floors:T6.settings.killswitch_account_floors.default;if(!Array.isArray(q))throw new h1("settings-invalid-value",Y.file);let C=q;for(let E of z.accounts){C=C.filter((f)=>T0(f).account!==E||!E.startsWith("vault:")&&T0(f).host!==J);let I=T0(Z[E]);if(Object.keys(I).length>0)C.push({account:E,host:E.startsWith("vault:")?"both":J,primary:I.primary??0,secondary:I.secondary??0})}x.push({setting:"killswitch_account_floors",value:C})}return x},{host:J}),await X.refresh()}catch(G){if(G instanceof h1)throw new J8(G.code,F9(G.code));throw G}}}}import{readFile as cV}from"node:fs/promises";import{readFileSync as MV,statSync as TV}from"node:fs";import{homedir as RV,tmpdir as CV}from"node:os";import{join as O9}from"node:path";var EV=["killswitch_enabled","killswitch_default_primary","killswitch_default_secondary","killswitch_account_floors","quota_minimum_remaining","cache_keep_window"];function w7(Y,J){return structuredClone(J&&Y==="killswitch_enabled"?!0:T6.settings[Y].default)}function AV(Y,J){let X=[],$=(U,V)=>{X.push({file:{kind:"user",path:J},keyPath:[U],reason:"invalid-value",detail:V})},Q=Y.killswitch_account_floors,G=Q.map(({account:U,host:V})=>JSON.stringify([U,V]));if(new Set(G).size!==G.length)$("killswitch_account_floors","Duplicate account and host pair");if(Q.some(({account:U,host:V})=>V==="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 H=Y.cache_keep_window;if(H.length>1||H.some(({start_hour:U,end_hour:V})=>U===V))$("cache_keep_window","Use at most one window with unequal hours");return X}function S7(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:H})=>[G,{primary:z,secondary:H}])),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]},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:K9,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 b7(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 TJ(Y,J){let X=Object.fromEntries(Object.keys(T6.settings).map(($)=>[$,w7($,!0)]));return b7(S7(X,Y),J)}async function k7(Y){let{handle:J,host:X,file:$}=Y,Q,G,z=[],H=!1,U=Promise.resolve(),V=new Set,B=async()=>{if(H)return;if(await J.read(),H)return;let N=Object.fromEntries(await Promise.all(Object.keys(T6.settings).map(async(q)=>[q,await J.get(q,{host:X})])));if(H)return;let Z=J.report();z=[...Z,...AV(N,$)];let P=Z.some((q)=>q.file.path===$&&(q.reason==="unreadable"||q.reason==="unparseable")),A=(q)=>z.some((C)=>C.reason==="invalid-value"&&C.keyPath[0]===q),x=(q)=>{N[q]=Q?structuredClone(Q[q]):w7(q,P)};for(let q of EV)if(P||A(q))x(q);if(A("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=S7(N,X),!H)for(let q of V)q()},F=()=>{return U=U.then(B,B),U},j=J.watch(()=>{F()});try{await F()}catch(N){throw j(),N}return{view(N){return b7(structuredClone(G),N)},get(N){return structuredClone(Q[N])},report(){return structuredClone(z)},refresh:F,onChange(N){return V.add(N),()=>{V.delete(N)}},dispose(){H=!0,j(),V.clear()}}}var IV="https://chatgpt.com/backend-api/codex/responses",x7=536870912,y7=$6("config"),h7=!1,wV="openai-auth.json",B0={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function SV(){let Y=process.env[B0.configDir]?.trim();if(Y)return Y;return O9(process.env.XDG_CONFIG_HOME||O9(RV(),".config"),"opencode")}function q0(){return process.env[B0.configFile]?.trim()||O9(SV(),wV)}function f7(Y){try{let J=JSON.parse(MV(Y,"utf8"));return J!=null&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}var g7=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshots"),m7=Symbol.for("@cortexkit/openai-auth/opencode-retired-settings-snapshots"),c7=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshot-warnings"),B4=globalThis;B4[g7]??=new Map;B4[m7]??=new Map;B4[c7]??=new Set;var D9=B4[g7],RJ=B4[m7],v7=B4[c7];function u7(Y,J){let X=Q8(Y),$=D9.get(X)??new Set;if($.size===0)$8.delete(X);RJ.delete(X),D9.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)D9.delete(X),RJ.set(X,J),$8.delete(X)}}function p7(Y){let J=Q8(Y),X=D9.get(J),$=RJ.get(J);for(let Q of X??[])$=Q;if(!$&&!v7.has(J))v7.add(J),y7.warn("Holding protection values strict until the shared settings file is read",{configPath:J});return $}function R0(Y,J=q0()){if(c0(J)!=="shared")return Y??{version:1,accounts:[]};return p7(J)?.view(Y)??TJ("opencode",Y)}function l7(Y){if(c0(Y)!=="shared")return f7(Y);return p7(Y)?.view()??TJ("opencode")}function d7(Y){let J=process.env[Y];if(J===void 0)return;let X=J.trim().toLowerCase();if(X==="1"||X==="true"||X==="yes"||X==="on")return!0;if(X===""||X==="0"||X==="false"||X==="no"||X==="off")return!1;return}function V4(Y,J,X){let $=d7(Y);if($!==void 0)return $;if(typeof J==="boolean")return J;return X}function bV(Y){let J=process.env[B0.dumpMaxBytes],X=J??Y;if(X===void 0)return x7;let $=J?.trim()?Number(J):X;if(typeof $==="number"&&Number.isSafeInteger($)&&$>=0)return $;if(!h7)h7=!0,y7.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:B0.dumpMaxBytes});return x7}function CJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var v1;function G8(Y=q0()){let J=d7(B0.dump);if(J!==void 0)return J;if(c0(Y)==="shared")return V4(B0.dump,CJ(l7(Y)),!1);let X=Y,$;try{$=TV(X)}catch{}if(v1?.path===X&&v1.mtimeMs===$?.mtimeMs&&v1.ctimeMs===$?.ctimeMs&&v1.size===$?.size)return v1.enabled;let Q=V4(B0.dump,CJ(f7(X)),!1);return v1={path:X,mtimeMs:$?.mtimeMs,ctimeMs:$?.ctimeMs,size:$?.size,enabled:Q},Q}function kV(Y){let J=l7(Y);return{webSockets:V4(B0.webSockets,J.webSockets,!1),rawWebSocket:V4(B0.rawWebSocket,J.rawWebSocket,!1),responsesLite:V4(B0.responsesLite,J.responsesLite,!1),dump:V4(B0.dump,CJ(J),!1),dumpDir:process.env[B0.dumpDir]?.trim()||(typeof J.dumpDir==="string"&&J.dumpDir.trim()?J.dumpDir.trim():O9(CV(),"opencode-openai-auth-dumps")),dumpMaxBytes:bV(J.dumpMaxBytes),codexApiEndpoint:process.env[B0.codexApiEndpoint]?.trim()||(typeof J.codexApiEndpoint==="string"&&J.codexApiEndpoint.trim()?J.codexApiEndpoint.trim():IV)}}var $8=new Map;function C0(Y=q0()){let J=Q8(Y),X=c0(Y)==="shared",$=$8.get(J);if(!$||$.shared!==X)$={shared:X,settings:kV(Y)},$8.set(J,$);return $.settings}function i7(Y=q0()){return $8.delete(Q8(Y)),v1=void 0,C0(Y)}import{readFileSync as xV}from"node:fs";var hV="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 vV(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 L4(Y,J={}){return N4({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:K4,...J})}function IJ(Y){try{let J=JSON.parse(xV(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return z8(J).migratedAt!==void 0}catch{return!1}}async function _9(Y,J){if(!IJ(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function P9(Y,J){if(Y===u0)return hV;if(z8(J.config).pending?.rowId===Y)return vV(Y);return}function yV(Y,J){return j4(Y,u0,J.legacyLocks).filter((X)=>X.name===W8)}function t0(Y,J={}){return yV(Y,J)}var Z4="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 Z1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function n7(Y){let J=Y.storage,X=y1(J);if(!J||!X||u6(X))return;let $=X,Q=Y.now(),G=(R0(J,Y.configPath).refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!$.access||!$.expires||$.expires-Q<=G)&&!e0($.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 H=$.access?.trim();if(!H)return;if(typeof $.expires!=="number"||$.expires<=Y.now())return;return{account:$,token:H}}import{readFile as e7}from"node:fs/promises";function q9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function Y$(Y){let J=await s7(Y.configPath),X=[];try{let Q=JSON.parse(await e7(Y.statePath,"utf8"));if(q9(Q)){let G=Q.accounts;if(q9(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 fV(Y){try{let J=JSON.parse(await e7(Y.configPath,"utf8"));return q9(J)&&q9(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var o7="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 J$(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&a6(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>a6(X)&&X.accountId===Y.mainAccountId)}function gV(Y,J){let X=Y.lastRefreshError;return e0(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=r7}function mV(Y){let J=[],X=[],$=Y.now??Date.now(),Q=J$(Y.storage),G=!1;if(u6(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. ${o7}`});else if(J0(Y.auth)){if(!y1(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 V=J.find((B)=>B.code==="auth-slot-missing"||B.code==="auth-slot-not-oauth"||B.code==="main-refresh-not-in-store");if(V)V.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(!a6(U)||!u6(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. ${o7}`})}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(!a6(U))continue;if(!gV(U,$))continue;let V={type:"clear-refresh-backoff",accountId:U.id};X.push(V),J.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:V})}let H=[...Y.orphanStateIds??[]];if(H.length>0){let U={type:"prune-orphan-state-ids",ids:H};X.push(U),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${H.join(", ")}.`,repair:U})}return{findings:J,repairs:X}}function X$(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(J0(await Y.readAuth()))return;let $=J$(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&&a6(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(),fV(Y.paths)]),z=mV({auth:Q.type==="missing"?void 0:Q,storage:X,orphanStateIds:$.orphanStateIds,retiredCustodyMode:G,now:Y.now()}),H=await N4({provider:"openai",quota:K4,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(H.status==="ready")for(let U of H.rows){if(U.disabledReason!==a7)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. ${t7}`})}return z.findings.map((U)=>{let V=U.repair?J(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...V?{repair:V}:{}}})}}]}var uV=q$,$$="OpenAI accounts",pV="ChatGPT accounts in the vault",lV="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 dV(){let{redirectUri:Y}=await B$(),J=await H$(),X=W$(crypto.getRandomValues(new Uint8Array(32)).buffer),$=U$(Y,J,X),Q=K$(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:f1(G)}}finally{V$(X)}}}}async function iV(Y){let{deviceData:J,url:X,instructions:$}=await N$(Y);return{url:X,instructions:$,method:"auto",async callback(){try{let Q=await j$(J,Y);return{type:"success",refresh:Q.refresh_token,access:Q.access_token,expires:Date.now()+(Q.expires_in??3600)*1000,accountId:f1(Q)}}catch{return{type:"failed"}}}}}function T$({client:Y,getAuth:J,getPaths:X=()=>m1(q0()),fetchImpl:$=fetch,packageVersion:Q=p0,dependencies:G,onMainSlotWritten:z,vault:H}){let U={authorizeBrowser:G?.authorizeBrowser??dV,authorizeHeadless:G?.authorizeHeadless??(()=>iV(Q)),beginAccountLogin:G?.beginAccountLogin??M9,loadAccounts:G?.loadAccounts??g1,mutateAccounts:G?.mutateAccounts??T9,readStoreIds:G?.readStoreIds??Y$,openBrowser:G?.openBrowser??uV,now:G?.now??Date.now,openAccountPool:G?.openAccountPool??L4,migrationBlockers:G?.migrationBlockers??(async()=>{let E=await O4({currentVersion:Q});return E.open?[]:E.blockers.map((I)=>({pid:I.pid,version:I.version}))}),...G?.terminal?{terminal:G.terminal}:{},...G?.vaultWait?{vaultWait:G.vaultWait}:{}},V=async()=>await J?.().catch(()=>{return})??{type:"missing"},B=async()=>{if(H&&await H.authority()!=="local")return!0;if((await V()).type!=="missing")return!0;let E=X(),I=U.openAccountPool(E);if((await I.read()).status==="ready")return O$(I);return((await U.loadAccounts(E))?.accounts.length??0)>0},F=async(E)=>{if(await A$(X().configPath,async()=>{if(H&&await H.authority()!=="local")return!1;if(J0(await V()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...E}}),!0}))await z?.().catch(()=>{})},j=(E)=>({begin:async({headless:I,signal:f})=>{if(H&&await H.authority()!=="local")throw Error(F4);let M=await U.beginAccountLogin({version:Q,headless:I,...f?{signal:f}:{}});return{url:M.url,instructions:M.instructions,completion:M.completion.then(async(k)=>{if(H&&await H.authority()!=="local")throw Error(F4);let l=await E.read(),p=l.status==="ready"?l.rows.find((Q6)=>Q6.id===u0)?.identity:void 0;if(k.accountId&&p&&k.accountId===p)throw Error("that account is already the OpenCode main credential");return{id:k.id,credential:{type:"oauth",refresh:k.refresh,...k.access!==void 0?{access:k.access}:{},...k.expires!==void 0?{expires:k.expires}:{}},...k.accountId!==void 0?{identity:k.accountId}:{},...k.label!==void 0?{label:k.label}:{}}})}},openBrowser:(I)=>U.openBrowser(I)}),N=async(E)=>{if(H&&await H.authority()!=="local")throw Error(F4);let I=E.credential;if(I?.type!=="oauth"||!I.access)throw Error("no usable access token for a quota check");let f=await H8({accessToken:I.access,fetchImpl:$,now:U.now,...E.identity?{accountId:E.identity}:{},accountKey:E.id});return D4(f,U.now(),!0)},Z=(E)=>X$({paths:X(),migrated:E,readAuth:V,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:F,now:U.now}),P=(E,I)=>({title:$$,store:FJ(I,{rowLocks:(f)=>j4(E,f)}),...U.terminal?{terminal:U.terminal}:{},login:j(I),protect:(f,M)=>P9(f,M),extraLocks:t0(E),pollQuota:N,doctor:Z(!0),status:async()=>{if(H&&await H.authority()==="host")return[Q$];let f=await H?.status();if(H&&await H.authority()!=="local"&&f)return[SJ(H.host,H.name,f.enrollment)];return[`Routing: ${(await U.loadAccounts(E))?.routing?.mode??"main-first"}`,...H?[SJ(H.host,H.name,(await H.status()).enrollment)]:[]]},...H&&!A9()?{extraActions:[A(H)]}:{}}),A=(E)=>{let I=E.enrolled();return{id:I?"vault-disconnect":"vault-connect",label:I?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(f)=>{let M=await E.authority();if(M==="host"){f.print(G$);return}if(I){if(M!=="local")await E.disconnect();f.print("Disconnected from the Claustrum vault.");return}if(M!=="local"){f.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}f.print(`Asking the Claustrum vault to enroll ${E.name}…`);let k,l=await E.waitForApproval({...U.vaultWait,onPending:(p)=>{let H6=p.state==="pending"?p.requestId??p.retryCode??"":p.state;if(H6===k)return;k=H6;for(let Q6 of L$(E.name,p))f.print(Q6);f.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});f.print(Z$(E,l).text)}}},x=async()=>{let E=await U.migrationBlockers();return D$({title:$$,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.",...E.length>0?["These processes still hold the move back:",...E.map((I)=>` ${I.pid==="unknown"?"processes that could not be read":`pid ${I.pid}`}: version ${I.version}`)]:[]],actions:[F$({checks:Z(!1)})],...U.terminal?{terminal:U.terminal}:{}})},q=async(E)=>{let I=X(),f=U.openAccountPool(I);if(H&&await H.authority()!=="local")return E9(P(I,f),H);if(await _9(I,f)===void 0)return x();let M=P(I,f);return H?E9(M,H):_$(M)},C=(E)=>async()=>{if(H&&await H.authority()!=="local")throw Error(F4);let I=await E();if(I.method!=="auto")return I;return{...I,callback:async()=>{let f=await I.callback();if(H&&await H.authority()!=="local")return{type:"failed"};return f}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:P$({hasCredential:B,openMenu:q,login:C(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:C(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...H?.enrolled()?[{label:pV,type:"oauth",authorize:async()=>({url:"",instructions:lV,method:"auto",callback:async()=>{let E=await z$(H.paths,H.name);if(E!=="vault"&&E!=="host")return{type:"failed"};try{let I=JSON.parse(await cV(M$(),"utf8"));if(!I||typeof I!=="object"||Array.isArray(I)||Object.hasOwn(I,"openai"))return{type:"failed"}}catch(I){if(I.code!=="ENOENT")return{type:"failed"}}return{...E$,type:"success"}}})}]:[]]}import{createHash as MB}from"node:crypto";var bJ=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function c1(Y){let J={};for(let X of bJ)if(X in Y)J[X]=Y[X];for(let X of Object.keys(Y))if(!(X in J))J[X]=Y[X];return J}import{createHash as BB}from"node:crypto";import{createHash as nV,randomBytes as R$}from"node:crypto";import{chmod as oV,lstat as C$,mkdir as rV,open as sV,readdir as y$,rename as aV,unlink as yJ,writeFile as tV}from"node:fs/promises";import{join as R9,resolve as kJ}from"node:path";var eV=100,xJ="session-unknown",YB=300000,JB=60000,XB=600000,$B=/\.(body|meta|request|response)\.json$/,QB=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,GB=/\.[a-f0-9]{24}\.partial$/;function f$(Y){let J=Y.replace($B,"");if(J===Y||!QB.test(J))return;return J}function zB(Y){let J=Y.replace(GB,"");return J!==Y&&f$(J)!==void 0}async function I$(Y){let{dir:J,maxBytes:X}=Y,$=Y.now??Date.now(),Q=Y.minAgeMs??JB,G=Y.partialStaleMs??XB,z={removed:0,freedBytes:0};if(!(X>0))return z;try{if(l0)await b$(J,"directory");if((await C$(J)).isSymbolicLink())return z;let H=new Set((Y.protectedPaths??[]).map((A)=>kJ(A))),U=await y$(J,{withFileTypes:!0}),V=[];await Promise.all(U.map(async(A)=>{if(!A.isFile())return;let x=zB(A.name),q=x?void 0:f$(A.name);if(!x&&q===void 0)return;let C=R9(J,A.name);try{let E=await C$(C);if(!E.isFile())return;V.push({path:C,size:E.size,mtimeMs:E.mtimeMs,group:q})}catch{}}));let B=V.reduce((A,x)=>A+x.size,0),F=0,j=0,N=async(A)=>{try{await yJ(A.path),B-=A.size,j+=A.size,F+=1}catch{}};for(let A of V){if(A.group!==void 0)continue;if(H.has(kJ(A.path)))continue;if($-A.mtimeMs<G)continue;await N(A)}let Z=new Map;for(let A of V){if(A.group===void 0)continue;let x=Z.get(A.group)??{files:[],newest:0};x.files.push(A),x.newest=Math.max(x.newest,A.mtimeMs),Z.set(A.group,x)}let P=[...Z.entries()].sort(([A,x],[q,C])=>x.newest-C.newest||A.localeCompare(q));for(let[,A]of P){if(B<=X)break;if($-A.newest<Q)continue;if(A.files.some((x)=>H.has(kJ(x.path))))continue;for(let x of A.files)await N(x)}if(F>0)Y.logger?.debug("removed old dump files",{removed:F,freedBytes:j});return{removed:F,freedBytes:j}}catch(H){if(H instanceof V8&&H.code==="ERR_PRIVATE_FILES_SECURITY")throw H;return z}}async function WB(Y,J,X){if(l0)return h$(Y,J,{stagePath:`${Y}.${X?X():R$(12).toString("hex")}.partial`});for(let $=0;;$+=1){let Q=`${Y}.${X?X():R$(12).toString("hex")}.partial`,G=!1,z;try{z=await sV(Q,"wx",384),G=!0,await z.writeFile(J,"utf8"),await z.chmod(384),await z.close(),z=void 0,await aV(Q,Y);return}catch(H){if(await z?.close().catch(()=>{}),G)await yJ(Q).catch(()=>{});if(H.code==="EEXIST"&&$===0)continue;throw H}}}function hJ(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function U8(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function w$(Y){return nV("sha256").update(Y).digest("hex")}function HB(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function S$(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function UB(Y,J){if(Y===void 0)return null;if(Y===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:J.length};let X=0;while(X<Y.length&&X<J.length&&Y[X]===J[X])X++;let $=Y.length-1,Q=J.length-1;while($>=X&&Q>=X&&Y[$]===J[Q])$--,Q--;return{changed:!0,firstByte:X,lastPreviousByte:$,lastCurrentByte:Q,changedPreviousBytes:$-X+1,changedCurrentBytes:Q-X+1,previousBytes:Y.length,currentBytes:J.length}}var VB=0;function g$(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,$=Y.now??Date.now,Q=Y.logger,G=new Set((Y.secretKeys??[]).map(HB)),z=v$({extraSecretKeys:(M)=>G.has(M),extraValuePatterns:[...Y.secretPatterns??[]]}),H=new Set(Y.schemaKeys??["tools"]),U=new Map,V=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function B(M){let k=z.redact({[M]:null})[M];return k===null?void 0:k}function F(M){if(Array.isArray(M))return M.map(F);if(S$(M)){let k={};for(let[l,p]of Object.entries(M)){let H6=B(l);if(H.has(l))k[l]=z.redactStrings(p);else if(H6!==void 0)k[l]=H6;else k[l]=F(p)}return k}return z.redactStrings(M)}function j(M){let k;try{k=JSON.parse(M)}catch{return{text:z.redactStrings(M),parsed:void 0}}let l=F(k),p=JSON.stringify(l);return{text:JSON.stringify(k)===p?M:p,parsed:S$(l)?l:void 0}}async function N(M,k,l,p){let H6=`-${U8(k,xJ)}-${U8(l,"channel")}`,Q6;try{Q6=await y$(M)}catch{return}let u=Q6.filter((R)=>R.endsWith(".meta.json")&&R.includes(H6)).sort().reverse();for(let R of u)try{if(JSON.parse(await vJ(R9(M,R),l0))?.baselineKey!==p)continue;return await vJ(R9(M,R.replace(/\.meta\.json$/,".body.json")),l0)}catch(L6){if(L6 instanceof V8&&(l0||L6.code==="ERR_PRIVATE_FILES_SECURITY"))throw L6}return}function Z(M,k){if(!U.has(M))while(U.size>=eV){let l=U.keys().next().value;if(l===void 0)break;U.delete(l)}U.set(M,k)}async function P(M){if(!J)return;let k=++VB,l=M.session?.trim()||xJ,p=V(),H6=new Date($()).toISOString(),Q6=[H6.replace(/[:.]/g,"-"),String(X),String(k).padStart(6,"0"),U8(l,xJ),U8(M.channel,"channel"),...M.phase?[U8(M.phase,"phase")]:[]].join("-"),u=R9(p,Q6),R={body:`${u}.body.json`,metadata:`${u}.meta.json`,request:`${u}.request.json`},L6=w$(`${M.channel}\x00${l}`);try{if(l0)await k$(p);else await rV(p,{recursive:!0,mode:448}),await oV(p,448);let q6=U.get(L6),d=q6===void 0?void 0:"memory";if(q6===void 0){if(q6=await N(p,l,M.channel,L6),q6!==void 0)d="disk"}let y6=j(M.bodyText),w6={id:Q6,createdAt:H6,pid:X,session:hJ(l),channel:M.channel,...M.phase?{phase:M.phase}:{},accountId:M.accountId,status:M.status,error:M.error===void 0?void 0:z.redactStrings(M.error),baselineKey:L6,bodyBytes:Buffer.byteLength(M.bodyText,"utf8"),bodyHash:w$(M.bodyText),diff:UB(q6,y6.text),baselineSource:d,body:y6.parsed?{parseable:!0,...Y.summarize?.(y6.parsed)}:{parseable:!1},...M.meta?{extra:F(M.meta)}:{},files:R},m=F({url:M.url,method:M.method,accountId:M.accountId,headers:M.headers===void 0?void 0:Object.fromEntries(new Headers(M.headers).entries())}),U6=(_6,Y6)=>l0?x$(_6,Y6):tV(_6,Y6,{encoding:"utf8",mode:384,flag:"wx"}),c=[[R.body,y6.text],[R.metadata,`${JSON.stringify(w6,null,2)}
|
|
1
|
+
import{$a as DJ,$b as q7,Ab as $Q,Bb as QQ,Ca as UU,Cb as GQ,Cc as PU,Db as q4,Ea as i5,Eb as D5,Ec as qU,Fa as n5,Fb as y9,Fc as EU,Ga as eY,Gb as f9,Gc as yU,Ha as YJ,Hc as NQ,Ia as DQ,Ic as fU,Ja as L$,Jc as gU,Ka as SJ,Kc as OQ,La as Z$,Ma as F$,Qb as O5,Ra as D$,Rb as x9,Sa as O$,Sb as _5,Ta as _$,Tb as P5,Ua as P$,Va as UQ,Vb as LU,Wa as F4,Xa as E9,Xb as n1,Ya as K1,Za as FJ,Zb as E4,_a as k1,ab as OJ,ac as MJ,bb as _J,bc as O4,cb as PJ,cc as FU,db as qJ,dc as m1,eb as o$,fb as u$,fc as E$,gb as I9,gc as a7,hb as KU,hc as t7,ib as NU,ic as A$,jb as W3,jc as DU,kb as B3,kc as M2,lc as OU,mb as JQ,mc as z8,nb as XQ,nc as JJ,ob as D3,oc as c9,pb as O3,pc as u9,qa as N4,qb as jU,qc as j4,ra as J8,rb as g9,rc as v5,sa as aH,sc as W8,ta as E0,tb as H3,tc as T2,ua as l5,ub as A4,uc as M$,va as y5,vb as S5,wb as b5,xa as n,xb as k5,xc as _U,ya as FQ,yb as x5,yc as d1,zb as h5}from"./index-vjb3rsqh.js";import{$c as TU,Oc as C3,Qc as q5,Sc as i0,Tc as AU,Wc as MU,_c as TQ,ad as RU,bd as CU,gd as XJ,hd as $J,id as IU,jd as wU,md as SU,nd as bU,od as kU,qd as m9,rd as _8,sd as xU,td as hU,ud as Y4,vd as vU}from"./index-ahbghz6c.js";import{$d as Q$,$e as Q7,Ae as K0,Af as WU,Be as N0,Bf as w5,Ce as f1,Cf as d5,Dd as J1,De as U$,Df as u0,Ee as V$,Ef as J0,Fd as K4,Fe as B$,Ff as y1,Ge as K$,Gf as wJ,He as N$,Ie as j$,Je as M9,Jf as HU,Ke as Y1,Kf as D4,Ld as T4,Le as g4,Lf as j0,Md as p5,Me as _H,Mf as I0,Ne as u6,Nf as o5,Oe as JU,Of as A8,Pe as s8,Pf as VU,Qd as j3,Qe as H8,Re as XU,Rf as r5,Sf as s5,Td as _7,Te as $U,Ue as V0,Uf as BU,Ve as s4,Vf as a5,We as N1,Wf as L3,Xe as H9,Xf as t5,Ye as W4,Yf as e5,Ze as a4,Zf as YQ,_d as F5,_e as U9,_f as R3,ae as G$,af as h1,be as A9,bf as U4,cf as Z7,df as a0,ef as Q8,ff as KQ,gf as c0,hf as P7,if as a6,je as z$,jf as K9,kf as QU,nf as s7,of as g1,pf as GU,qf as T9,re as r7,sf as Z3,te as O8,tf as a8,ue as eH,uf as F3,ve as e0,vf as o1,we as A2,wf as k9,xe as YU,xf as j1,ye as W$,yf as n0,ze as H$,zf as zU}from"./index-kakqxnt5.js";import{dg as h9,ig as O7}from"./index-t66h86ed.js";import{ng as e$,og as Y5,pg as J5,qg as fQ,rg as tH,sg as p0,tg as gQ,ug as mQ}from"./index-gxa94644.js";import{Hg as y4,Jg as q$}from"./index-66eejhpe.js";import{Kg as v$,Ng as b9,Pg as $6}from"./index-eb631m0m.js";import{$g as h$,Qg as l0,Rg as V8,Vg as b$,Wg as k$,Xg as vJ,Yg as x$}from"./index-tn1ve0gx.js";import{bh as X5,dh as ZU}from"./index-qtaqp1bf.js";import{fh as f3}from"./index-t15pb3n2.js";import{randomUUID as lH}from"node:crypto";import{statSync as pD}from"node:fs";import _2 from"node:os";import{isDeepStrictEqual as PV}from"node:util";var G7={hosts:"OpenCode 1, OpenCode 2 and Pi",project:"user-only"},g0={...G7,overrides:{host:!0}},m0={hosts:"OpenCode 1 and OpenCode 2",project:"user-only"},r4={hosts:"OpenCode 1 only",project:"user-only"},z7=(Y,J)=>Y.flatMap((X)=>J.map(($)=>({source:X,path:$}))),M0=(...Y)=>z7(["opencode-store","pi-store"],Y),s6=(...Y)=>z7(["opencode-store"],Y),T6=Q7({plugin:"openai-auth",settings:{routing_mode:{...g0,value:W4(["ordered","main-first","fallback-first","sticky-balanced"]),default:"main-first",legacy:M0(["routing","mode"])},max_same_account_wait:{...g0,value:W4(["off","15m","cache"]),default:"15m",legacy:M0(["routing","maxSameAccountWait"])},fallback_on:{...g0,hosts:"OpenCode 1 and Pi; not read by OpenCode 2",value:a4(s4()),default:[401,403,429],legacy:M0(["fallbackOn"])},refresh_enabled:{...r4,hosts:"OpenCode 1 legacy fallback refresh only",value:V0(),default:!0,legacy:s6(["refresh","enabled"])},refresh_before_expiry_minutes:{...g0,value:N1(),default:240,legacy:M0(["refresh","refreshBeforeExpiryMinutes"])},quota_enabled:{...g0,value:V0(),default:!0,legacy:M0(["quota","enabled"])},quota_check_interval_minutes:{...r4,hosts:"OpenCode 1 legacy quota freshness and polling only",value:N1({min:1}),default:5,legacy:s6(["quota","checkIntervalMinutes"])},quota_minimum_remaining:{...g0,value:a4(U9({window:W4(["primary","secondary"]),floor:N1()})),default:[],legacy:M0(["quota","minimumRemaining","primary"],["quota","minimumRemaining","5h"],["quota","minimumRemaining","secondary"],["quota","minimumRemaining","1w"])},quota_fail_closed_on_unknown:{...g0,value:V0(),default:!1,legacy:M0(["quota","failClosedOnUnknownQuota"])},cost_zeroing:{...r4,value:V0(),default:!0,legacy:s6(["costZeroing","enabled"])},killswitch_enabled:{...g0,value:V0(),default:!1,legacy:M0(["killswitch","enabled"])},killswitch_default_primary:{...g0,value:N1(),default:5,legacy:M0(["killswitch","defaults","primary"],["killswitch","main","primary"],["killswitch","main","5h"])},killswitch_default_secondary:{...g0,value:N1(),default:10,legacy:M0(["killswitch","defaults","secondary"],["killswitch","main","secondary"],["killswitch","main","1w"])},killswitch_account_floors:{...G7,value:a4(U9({account:H9(),host:W4(["opencode","pi","both"]),primary:N1(),secondary:N1()})),default:[],legacy:M0(["killswitch","accounts"])},cache_keep_enabled:{...m0,value:V0(),default:!1,legacy:s6(["cacheKeep","enabled"],["cachekeep","enabled"])},cache_keep_subagents:{...m0,value:V0(),default:!1,legacy:s6(["cacheKeep","subagents"],["cachekeep","subagents"])},cache_keep_sustain:{...m0,value:V0(),default:!1,legacy:s6(["cacheKeep","sustain"],["cachekeep","sustain"])},cache_keep_window:{...m0,value:a4(U9({start_hour:s4({min:0,max:23}),end_hour:s4({min:0,max:23})})),default:[],legacy:s6(["cacheKeep","startHour"],["cacheKeep","endHour"],["cachekeep","startHour"],["cachekeep","endHour"])},log_level:{...m0,value:W4(["error","warn","info","debug","trace","default"]),default:"default",legacy:s6(["logging","level"])},request_dumps:{...m0,value:V0(),default:!1,legacy:s6(["dump"],["dump","enabled"])},dump_dir:{...m0,value:H9(),default:"",legacy:s6(["dumpDir"])},dump_max_bytes:{...m0,value:s4({min:0,max:Number.MAX_SAFE_INTEGER}),default:536870912,legacy:s6(["dumpMaxBytes"])},web_sockets:{...r4,value:V0(),default:!1,legacy:s6(["webSockets"])},raw_web_socket:{...r4,value:V0(),default:!1,legacy:s6(["rawWebSocket"])},responses_lite:{...m0,value:V0(),default:!1,legacy:s6(["responsesLite"])},codex_api_endpoint:{...m0,value:H9(),default:"https://chatgpt.com/backend-api/codex/responses",legacy:s6(["codexApiEndpoint"])}}});import{chmod as LV,mkdir as ZV}from"node:fs/promises";import{join as FV}from"node:path";import{existsSync as U7,readFileSync as $V}from"node:fs";import{readFileSync as YV}from"node:fs";var W7="Settings moved to ";function JV(Y){let J=Y.split(/\r?\n/,1)[0]??"";if(!J.startsWith(W7)||!J.endsWith("."))return;return J.slice(W7.length,-1)}function XV(Y){try{return JV(YV(`${Y}.MOVED_READPLEASE`,"utf8"))}catch{return}}function H7(Y,J){let X=XV(Y);return X!==void 0&&a0(X)===a0(J)}function QV(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function GV(Y,J){let X=Y;for(let[$,Q]of J.entries()){if(!QV(X)||!Object.hasOwn(X,Q))return!1;if($===J.length-1)return!0;X=X[Q]}return!1}function zV(Y,J){return Object.values(T6.settings).some((X)=>X.legacy.some(($)=>$.source===`${J}-store`&&GV(Y,$.path)))}function WV(Y){try{return zV(JSON.parse($V(Y.configPath,"utf8")),Y.host)}catch{return!1}}function V9(Y){let J=U7(Y.target),X=Y.sources.some((H)=>H7(H.configPath,Y.target)),$=Y.sources.filter((H)=>U7(H.configPath)),Q=$.length>0,G=X&&!J,z=J&&!X&&$.some(WV);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 B9(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function V7(Y){try{let J=Number(Y);return Number.isFinite(J)?Math.min(100,Math.max(0,J)):0}catch{return 0}}function EJ(Y,J){let X=j1(Y,J);return{primary:V7(X.primary),secondary:V7(X.secondary)}}function B7(Y,J,X,$){if(!B9(Y))return;for(let Q of["primary","secondary","5h","1w"])if(Y[Q]===null)$.push({source:X,key:`${J}.${Q}`,reason:"invalid"})}function K7(Y){let J={entries:[],unmapped:[]},X=[],$=[];Y.forEach((z,H)=>{if(!z.present)return;if(z.host!=="opencode"&&z.host!=="pi")throw Error("Unsupported killswitch floors source host");let U=z.host,V=B9(z.value)?z.value:{},B=B9(V.killswitch)?V.killswitch:void 0,F={killswitch:V.killswitch},j=B?.schema===K9,N=j?EJ({killswitch:{...B,accounts:void 0}}):EJ(F);if(X.push({source:H,floors:N}),!j)B7(B?.main,"killswitch.main",H,J.unmapped);if(!B9(B?.accounts))return;for(let Z of Object.keys(B.accounts)){let P=`killswitch.accounts.${Z}`;if(!j&&Z==="main"){J.unmapped.push({source:H,key:P,reason:"shadowed"});continue}if(!j)B7(B.accounts[Z],P,H,J.unmapped);$.push({account:Z,host:U,...EJ(F,Z==="main"?void 0:Z)})}});for(let[z,H]of[["primary",5],["secondary",10]]){if(X.every(({floors:U})=>U[z]===H))continue;for(let{source:U,floors:V}of X)J.entries.push({source:U,setting:`killswitch_default_${z}`,value:V[z]})}let Q=[];for(let z of $){let H=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(H)H.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 L1(Y){if(Y===null||typeof Y!=="object"||Array.isArray(Y))return!1;let J=Object.getPrototypeOf(Y);return J===Object.prototype||J===null}function N7(Y){let J;try{J=JSON.parse(Y)}catch{throw Error("Settings source is not JSON")}if(!L1(J))throw Error("Settings source is not an object");return J}function H4(Y,J){let X=Y;for(let $ of J){if(!L1(X)||!Object.hasOwn(X,$))return;X=X[$]}return X}function t4(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(($)=>t4(Y.item,$,!0));case"object":return L1(J)&&Object.entries(J).every(([$,Q])=>{let G=Y.fields[$];return Object.hasOwn(Y.fields,$)&&G!==void 0&&t4(G,Q,X)})&&(!X||Object.keys(Y.fields).every(($)=>Object.hasOwn(J,$)));case"record":return L1(J)&&Object.values(J).every(($)=>t4(Y.value,$,!0))}}class j9 extends Error{setting;key;constructor(Y,J){super(`Cannot move setting ${Y}${J?` (${J})`:""}`);this.setting=Y;this.key=J;this.name="CannotMoveSettingError"}}function N9(Y,J){throw new j9(Y,J)}function j7(Y,J,X){try{let $=Number(Y);if(Number.isFinite($))return $}catch{}return N9(J,X)}function HV(Y,J){let X=[];for(let[$,Q]of[["primary","5h"],["secondary","1w"]]){let G=["quota","minimumRemaining"],z=H4(Y,[...G,$]),H=H4(Y,[...G,Q]);for(let[V,B]of[[$,z],[Q,H]])if(B===null)J([...G,V].join("."),"invalid");if(z!=null&&H!=null)J([...G,Q].join("."),"shadowed");let U=z??H;if(U==null)continue;X.push({window:$,floor:j7(U,"quota_minimum_remaining",[...G,$].join("."))})}return X}function UV(Y,J,X){let $=H4(Y,[J,"startHour"]),Q=H4(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 VV(Y,J,X){let $=T6.settings[Y],Q=$.default;if(Y==="quota_minimum_remaining")return HV(J,X);let G=L1(J.cacheKeep)?"cacheKeep":"cachekeep";if(Y==="cache_keep_window")return UV(J,G,X);let z=$.legacy[0];if(!z)return N9(Y);let H=z.path;if(Y.startsWith("cache_keep_"))H=[G,...H.slice(1)];if(Y==="request_dumps")H=typeof J.dump==="boolean"?["dump"]:["dump","enabled"];let U=H4(J,H),V=H.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 B=U.filter((F)=>Number.isInteger(F));if(B.length!==U.length)X(V,"invalid");return B.length?B:Q}}else if(Y==="refresh_before_expiry_minutes"||Y==="quota_check_interval_minutes"){if(U!=null){let B=j7(U,Y,V);return Y==="quota_check_interval_minutes"?Math.max(1,B):B}}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(t4($.value,U))return U;return X(V,"invalid"),Q}var BV=new Set(["version","accounts","main","commonAuthPool","commonAuthLimits","openaiAuthPool","mainAccountId","reset","claustrum"]),KV=new Set(["refresh.mainLastRefreshError","refresh.mainRefreshLeaseId","refresh.mainRefreshLeaseUntil","refresh.mainRefreshLeaseTokenHash","quota.mainQuota","quota.mainQuotaCheckedAt","quota.mainQuotaToken","quota.mainLastQuotaApiError"]);function NV(Y,J,X){let $=new Set;for(let G of Object.values(T6.settings))for(let z of G.legacy){let H=z.path.join(".");if($.add(H),J==="pi"&&!G.legacy.some((U)=>U.source==="pi-store")&&H4(Y,z.path)!==void 0){if(H==="dump.enabled"&&Object.hasOwn(Y,"dump"))continue;X(H,"other-host")}}let Q=(G,z="")=>{for(let[H,U]of Object.entries(G)){let V=z?`${z}.${H}`:H;if(!z&&BV.has(H)||KV.has(V)||V==="killswitch.schema")continue;if($.has(V))continue;if([...$].some((B)=>B.startsWith(`${V}.`)))if(L1(U))Q(U,V);else X(V,"invalid");else X(V,"retired")}};if(Q(Y),J==="opencode"&&L1(Y.cacheKeep)&&Y.cachekeep!==void 0)X("cachekeep","shadowed")}function L7(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(!L1(Q.value))throw Error("Settings source is not an object");let z=(H,U)=>{if(!J.unmapped.some((V)=>V.source===G&&V.key===H&&V.reason===U))J.unmapped.push({source:G,key:H,reason:U})};return NV(Q.value,Q.host,z),[{source:G,host:Q.host,store:Q.value,report:z}]});for(let Q of Object.keys(T6.settings)){if(Q.startsWith("killswitch_default_")||Q==="killswitch_account_floors")continue;let G=T6.settings[Q],z=X.filter((H)=>G.legacy.some((U)=>U.source===`${H.host}-store`)).map((H)=>({source:H.source,value:VV(Q,H.store,H.report)}));if(z.every((H)=>JSON.stringify(H.value)===JSON.stringify(G.default)))continue;for(let H of z)J.entries.push({...H,setting:Q})}let $=K7(Y);J.entries.push(...$.entries),J.unmapped.push(...$.unmapped);for(let Q of J.entries){if(!Object.hasOwn(T6.settings,Q.setting))N9(Q.setting);if(!t4(T6.settings[Q.setting].value,Q.value))N9(Q.setting)}return J}class AJ 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 F7(Y){let J=Y?.code;return typeof J==="string"&&/^[A-Z][A-Z0-9_]*$/.test(J)?J:"SETTINGS_MOVE_FAILED"}function jV(Y,J){if(Y instanceof AJ)return{kind:"cause",host:Y.host,path:Y.path,code:Y.code};if(Y instanceof j9)return{kind:"setting",setting:Y.setting};let X=Y?.path,$=J.find((G)=>G.path===X),Q=F7(Y);if($)return{kind:"cause",host:$.host,path:$.path,code:Q};return{kind:"cause",code:Q}}async function D7({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 N7(z)}catch(H){throw new AJ(G.host,G.configPath,H instanceof Error&&H.message==="Settings source is not JSON"?"SOURCE_NOT_JSON":"SOURCE_NOT_OBJECT")}}})),Q=await Z7({definition:T6,target:Y.target,separateInstall:!1,sources:$,map:L7,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((H)=>`${H.path}.MOVED_READPLEASE`===G.path);X.warn(`Settings move note: ${z?.host??"unknown"} ${G.path}: ${F7(G.error)}`)}if(Q.outcome==="failed"){Q.failure=jV(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 Z9 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 E7=Symbol.for("@cortexkit/openai-auth/settings-authority"),A7=globalThis,L9=A7[E7]??new Map;A7[E7]=L9;function e4(Y){return L9.get(a0(Y))}function M7(Y){let J=a0(Y.install.configIdentity),X=L9.get(J);if(X)return X;let $=Promise.resolve().then(()=>DV(Y));return L9.set(J,$),$}async function DV({install:Y,stateHome:J,record:X,log:$,fenceOptions:Q}){let G={decision:Y.separate?"separate":"shared",install:Y,ranMove:!1},z=()=>{return P7(Y.configIdentity,G.decision),G};if(Y.separate){try{await X("separate")}catch{}return z()}let H=q7(J),U=()=>{return G.completion=V9(Y),G.completion},V=(B)=>B.completed||!B.sourcePresent;try{return await ZV(H,{recursive:!0,mode:448}),await LV(H,448),await O7(FV(H,"settings-authority"),{name:"settings-authority",..._7},async(B)=>{if(!V(U()))if(G.fence=await MJ({...Q,stateHome:J}),G.fence.open){G.ranMove=!0;try{G.move=await D7({install:Y,log:$,async fence(){let N=await MJ({...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,j=U();G.decision=F==="moved"||F==="done-already"||F==="aborted-target-appeared"||j.completed?"shared":"legacy"}else G.decision="legacy";await B.assertOwned(),await X(G.decision)}),z()}catch(B){if(!V(U()))throw new Z9(H,B);return G.decision="shared",z()}}var x1=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.",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 F9(Y){return x1.refusal[Y]}function OV(Y){let J=x1;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 _V(Y,J,X=!1){let $=x1;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 T7=Symbol.for("@cortexkit/openai-auth/settings-diagnostics"),R7=globalThis,Y8=R7[T7]??{logged:new Set,sawTargetMissing:new Set};R7[T7]=Y8;async function C7({configPath:Y,snapshot:J,log:X}){let $=e4(Y);if(!$)throw Error("Settings authority has not been decided");let Q;try{Q=await $}catch(U){if(U instanceof Z9||U instanceof Error&&U.name==="SettingsAuthorityRefusal"&&"folder"in U&&typeof U.folder==="string"){let V=U.cause;return{lines:[x1.refused(String(U.folder),V instanceof Error?V.message:String(V))]}}throw U}if(Q.decision==="separate")return{lines:[x1.separate]};let G=Q.decision==="shared"?V9(Q.install):Q.completion,z=a0(Q.install.target);if(Q.decision==="shared"&&!G?.targetExists)Y8.sawTargetMissing.add(z);let H=[x1.file(Q.install.target),_V(Q,G,Y8.sawTargetMissing.has(z))];if(Q.decision==="shared"&&G){for(let U of["preExistingFile","removedFile"]){if(!G[U])continue;let V=x1[U](Q.install.target);H.push(V);let B=`${U}:${a0(Q.install.target)}`;if(!Y8.logged.has(B))Y8.logged.add(B),X.warn(V)}await J?.refresh(),H.push(...J?.report().map(OV)??[])}return{lines:H}}var T0=(Y)=>n(Y)?Y:{};function I7(Y){let{routing:J,killswitch:X}=Y.view(),$=Object.fromEntries(Object.entries(X?.accounts??{}).map(([Q,G])=>[Q,Object.fromEntries(Object.entries(T0(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 qV(Y){let J=new Set,X=!1,$=!0,Q=(z)=>{if(!$)return;if(z[0]!=="killswitch"||z[1]!=="accounts")return;if(X=!0,z[2]!==void 0)J.add(z[2])},G=(z,H)=>new Proxy(z,{ownKeys(U){return Q(H),Reflect.ownKeys(U)},get(U,V){let B=Reflect.get(U,V);return typeof V==="string"&&n(B)?G(B,[...H,V]):B},set(U,V,B){if(typeof V==="string")Q([...H,V]);return Reflect.set(U,V,B)},deleteProperty(U,V){if(typeof V==="string")Q([...H,V]);return Reflect.deleteProperty(U,V)}});return{value:G(Y,[]),accounts:J,touched:()=>X,finish:()=>{$=!1}}}function X8(Y){let{host:J,snapshot:X}=Y,$=Y.writer??U4(T6,{file:Y.file,log:Y.log,separateInstall:!1,createMissing:!0});return{async read(){return await X.refresh(),I7(X)},async update(Q){try{await X.refresh();let G=I7(X),z=qV(structuredClone(G)),H=await Q(z.value)??z.value;z.finish();let U=JSON.parse(JSON.stringify(H)),V=[],B=T0(U.routing),F=T0(G.routing);if(B.mode!==F.mode)V.push({setting:"routing_mode",value:B.mode});if(B.maxSameAccountWait!==F.maxSameAccountWait)V.push({setting:"max_same_account_wait",value:B.maxSameAccountWait===0?"off":B.maxSameAccountWait==="max"?"cache":"15m"});let j=T0(U.killswitch);if(j.enabled!==T0(G.killswitch).enabled)V.push({setting:"killswitch_enabled",value:j.enabled});let N=T0(T0(G.killswitch).accounts),Z=T0(j.accounts);for(let A of new Set([...Object.keys(N),...Object.keys(Z)]))if(!PV(N[A],Z[A]))z.accounts.add(A);let P=z.touched()||z.accounts.size>0;if(P){if(X.report().some((A)=>A.keyPath[0]==="killswitch_account_floors"||A.reason==="unreadable"||A.reason==="unparseable"))throw new h1("settings-invalid-value",Y.file)}await $.update((A)=>{let x=[...V];if(P){let q=A.status==="ready"&&Object.hasOwn(A.document,"killswitch_account_floors")?A.document.killswitch_account_floors:T6.settings.killswitch_account_floors.default;if(!Array.isArray(q))throw new h1("settings-invalid-value",Y.file);let C=q;for(let E of z.accounts){C=C.filter((f)=>T0(f).account!==E||!E.startsWith("vault:")&&T0(f).host!==J);let I=T0(Z[E]);if(Object.keys(I).length>0)C.push({account:E,host:E.startsWith("vault:")?"both":J,primary:I.primary??0,secondary:I.secondary??0})}x.push({setting:"killswitch_account_floors",value:C})}return x},{host:J}),await X.refresh()}catch(G){if(G instanceof h1)throw new J8(G.code,F9(G.code));throw G}}}}import{readFile as cV}from"node:fs/promises";import{readFileSync as MV,statSync as TV}from"node:fs";import{homedir as RV,tmpdir as CV}from"node:os";import{join as O9}from"node:path";var EV=["killswitch_enabled","killswitch_default_primary","killswitch_default_secondary","killswitch_account_floors","quota_minimum_remaining","cache_keep_window"];function w7(Y,J){return structuredClone(J&&Y==="killswitch_enabled"?!0:T6.settings[Y].default)}function AV(Y,J){let X=[],$=(U,V)=>{X.push({file:{kind:"user",path:J},keyPath:[U],reason:"invalid-value",detail:V})},Q=Y.killswitch_account_floors,G=Q.map(({account:U,host:V})=>JSON.stringify([U,V]));if(new Set(G).size!==G.length)$("killswitch_account_floors","Duplicate account and host pair");if(Q.some(({account:U,host:V})=>V==="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 H=Y.cache_keep_window;if(H.length>1||H.some(({start_hour:U,end_hour:V})=>U===V))$("cache_keep_window","Use at most one window with unequal hours");return X}function S7(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:H})=>[G,{primary:z,secondary:H}])),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]},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:K9,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 b7(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 TJ(Y,J){let X=Object.fromEntries(Object.keys(T6.settings).map(($)=>[$,w7($,!0)]));return b7(S7(X,Y),J)}async function k7(Y){let{handle:J,host:X,file:$}=Y,Q,G,z=[],H=!1,U=Promise.resolve(),V=new Set,B=async()=>{if(H)return;if(await J.read(),H)return;let N=Object.fromEntries(await Promise.all(Object.keys(T6.settings).map(async(q)=>[q,await J.get(q,{host:X})])));if(H)return;let Z=J.report();z=[...Z,...AV(N,$)];let P=Z.some((q)=>q.file.path===$&&(q.reason==="unreadable"||q.reason==="unparseable")),A=(q)=>z.some((C)=>C.reason==="invalid-value"&&C.keyPath[0]===q),x=(q)=>{N[q]=Q?structuredClone(Q[q]):w7(q,P)};for(let q of EV)if(P||A(q))x(q);if(A("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=S7(N,X),!H)for(let q of V)q()},F=()=>{return U=U.then(B,B),U},j=J.watch(()=>{F()});try{await F()}catch(N){throw j(),N}return{view(N){return b7(structuredClone(G),N)},get(N){return structuredClone(Q[N])},report(){return structuredClone(z)},refresh:F,onChange(N){return V.add(N),()=>{V.delete(N)}},dispose(){H=!0,j(),V.clear()}}}var IV="https://chatgpt.com/backend-api/codex/responses",x7=536870912,y7=$6("config"),h7=!1,wV="openai-auth.json",B0={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function SV(){let Y=process.env[B0.configDir]?.trim();if(Y)return Y;return O9(process.env.XDG_CONFIG_HOME||O9(RV(),".config"),"opencode")}function q0(){return process.env[B0.configFile]?.trim()||O9(SV(),wV)}function f7(Y){try{let J=JSON.parse(MV(Y,"utf8"));return J!=null&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}var g7=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshots"),m7=Symbol.for("@cortexkit/openai-auth/opencode-retired-settings-snapshots"),c7=Symbol.for("@cortexkit/openai-auth/opencode-settings-snapshot-warnings"),B4=globalThis;B4[g7]??=new Map;B4[m7]??=new Map;B4[c7]??=new Set;var D9=B4[g7],RJ=B4[m7],v7=B4[c7];function u7(Y,J){let X=Q8(Y),$=D9.get(X)??new Set;if($.size===0)$8.delete(X);RJ.delete(X),D9.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)D9.delete(X),RJ.set(X,J),$8.delete(X)}}function p7(Y){let J=Q8(Y),X=D9.get(J),$=RJ.get(J);for(let Q of X??[])$=Q;if(!$&&!v7.has(J))v7.add(J),y7.warn("Holding protection values strict until the shared settings file is read",{configPath:J});return $}function R0(Y,J=q0()){if(c0(J)!=="shared")return Y??{version:1,accounts:[]};return p7(J)?.view(Y)??TJ("opencode",Y)}function l7(Y){if(c0(Y)!=="shared")return f7(Y);return p7(Y)?.view()??TJ("opencode")}function d7(Y){let J=process.env[Y];if(J===void 0)return;let X=J.trim().toLowerCase();if(X==="1"||X==="true"||X==="yes"||X==="on")return!0;if(X===""||X==="0"||X==="false"||X==="no"||X==="off")return!1;return}function V4(Y,J,X){let $=d7(Y);if($!==void 0)return $;if(typeof J==="boolean")return J;return X}function bV(Y){let J=process.env[B0.dumpMaxBytes],X=J??Y;if(X===void 0)return x7;let $=J?.trim()?Number(J):X;if(typeof $==="number"&&Number.isSafeInteger($)&&$>=0)return $;if(!h7)h7=!0,y7.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:B0.dumpMaxBytes});return x7}function CJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var v1;function G8(Y=q0()){let J=d7(B0.dump);if(J!==void 0)return J;if(c0(Y)==="shared")return V4(B0.dump,CJ(l7(Y)),!1);let X=Y,$;try{$=TV(X)}catch{}if(v1?.path===X&&v1.mtimeMs===$?.mtimeMs&&v1.ctimeMs===$?.ctimeMs&&v1.size===$?.size)return v1.enabled;let Q=V4(B0.dump,CJ(f7(X)),!1);return v1={path:X,mtimeMs:$?.mtimeMs,ctimeMs:$?.ctimeMs,size:$?.size,enabled:Q},Q}function kV(Y){let J=l7(Y);return{webSockets:V4(B0.webSockets,J.webSockets,!1),rawWebSocket:V4(B0.rawWebSocket,J.rawWebSocket,!1),responsesLite:V4(B0.responsesLite,J.responsesLite,!1),dump:V4(B0.dump,CJ(J),!1),dumpDir:process.env[B0.dumpDir]?.trim()||(typeof J.dumpDir==="string"&&J.dumpDir.trim()?J.dumpDir.trim():O9(CV(),"opencode-openai-auth-dumps")),dumpMaxBytes:bV(J.dumpMaxBytes),codexApiEndpoint:process.env[B0.codexApiEndpoint]?.trim()||(typeof J.codexApiEndpoint==="string"&&J.codexApiEndpoint.trim()?J.codexApiEndpoint.trim():IV)}}var $8=new Map;function C0(Y=q0()){let J=Q8(Y),X=c0(Y)==="shared",$=$8.get(J);if(!$||$.shared!==X)$={shared:X,settings:kV(Y)},$8.set(J,$);return $.settings}function i7(Y=q0()){return $8.delete(Q8(Y)),v1=void 0,C0(Y)}import{readFileSync as xV}from"node:fs";var hV="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 vV(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 L4(Y,J={}){return N4({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:K4,...J})}function IJ(Y){try{let J=JSON.parse(xV(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return z8(J).migratedAt!==void 0}catch{return!1}}async function _9(Y,J){if(!IJ(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function P9(Y,J){if(Y===u0)return hV;if(z8(J.config).pending?.rowId===Y)return vV(Y);return}function yV(Y,J){return j4(Y,u0,J.legacyLocks).filter((X)=>X.name===W8)}function t0(Y,J={}){return yV(Y,J)}var Z4="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 Z1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function n7(Y){let J=Y.storage,X=y1(J);if(!J||!X||u6(X))return;let $=X,Q=Y.now(),G=(R0(J,Y.configPath).refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!$.access||!$.expires||$.expires-Q<=G)&&!e0($.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 H=$.access?.trim();if(!H)return;if(typeof $.expires!=="number"||$.expires<=Y.now())return;return{account:$,token:H}}import{readFile as e7}from"node:fs/promises";function q9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function Y$(Y){let J=await s7(Y.configPath),X=[];try{let Q=JSON.parse(await e7(Y.statePath,"utf8"));if(q9(Q)){let G=Q.accounts;if(q9(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 fV(Y){try{let J=JSON.parse(await e7(Y.configPath,"utf8"));return q9(J)&&q9(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var o7="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 J$(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&a6(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>a6(X)&&X.accountId===Y.mainAccountId)}function gV(Y,J){let X=Y.lastRefreshError;return e0(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=r7}function mV(Y){let J=[],X=[],$=Y.now??Date.now(),Q=J$(Y.storage),G=!1;if(u6(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. ${o7}`});else if(J0(Y.auth)){if(!y1(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 V=J.find((B)=>B.code==="auth-slot-missing"||B.code==="auth-slot-not-oauth"||B.code==="main-refresh-not-in-store");if(V)V.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(!a6(U)||!u6(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. ${o7}`})}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(!a6(U))continue;if(!gV(U,$))continue;let V={type:"clear-refresh-backoff",accountId:U.id};X.push(V),J.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:V})}let H=[...Y.orphanStateIds??[]];if(H.length>0){let U={type:"prune-orphan-state-ids",ids:H};X.push(U),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${H.join(", ")}.`,repair:U})}return{findings:J,repairs:X}}function X$(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(J0(await Y.readAuth()))return;let $=J$(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&&a6(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(),fV(Y.paths)]),z=mV({auth:Q.type==="missing"?void 0:Q,storage:X,orphanStateIds:$.orphanStateIds,retiredCustodyMode:G,now:Y.now()}),H=await N4({provider:"openai",quota:K4,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(H.status==="ready")for(let U of H.rows){if(U.disabledReason!==a7)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. ${t7}`})}return z.findings.map((U)=>{let V=U.repair?J(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...V?{repair:V}:{}}})}}]}var uV=q$,$$="OpenAI accounts",pV="ChatGPT accounts in the vault",lV="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 dV(){let{redirectUri:Y}=await B$(),J=await H$(),X=W$(crypto.getRandomValues(new Uint8Array(32)).buffer),$=U$(Y,J,X),Q=K$(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:f1(G)}}finally{V$(X)}}}}async function iV(Y){let{deviceData:J,url:X,instructions:$}=await N$(Y);return{url:X,instructions:$,method:"auto",async callback(){try{let Q=await j$(J,Y);return{type:"success",refresh:Q.refresh_token,access:Q.access_token,expires:Date.now()+(Q.expires_in??3600)*1000,accountId:f1(Q)}}catch{return{type:"failed"}}}}}function T$({client:Y,getAuth:J,getPaths:X=()=>m1(q0()),fetchImpl:$=fetch,packageVersion:Q=p0,dependencies:G,onMainSlotWritten:z,vault:H}){let U={authorizeBrowser:G?.authorizeBrowser??dV,authorizeHeadless:G?.authorizeHeadless??(()=>iV(Q)),beginAccountLogin:G?.beginAccountLogin??M9,loadAccounts:G?.loadAccounts??g1,mutateAccounts:G?.mutateAccounts??T9,readStoreIds:G?.readStoreIds??Y$,openBrowser:G?.openBrowser??uV,now:G?.now??Date.now,openAccountPool:G?.openAccountPool??L4,migrationBlockers:G?.migrationBlockers??(async()=>{let E=await O4({currentVersion:Q});return E.open?[]:E.blockers.map((I)=>({pid:I.pid,version:I.version}))}),...G?.terminal?{terminal:G.terminal}:{},...G?.vaultWait?{vaultWait:G.vaultWait}:{}},V=async()=>await J?.().catch(()=>{return})??{type:"missing"},B=async()=>{if(H&&await H.authority()!=="local")return!0;if((await V()).type!=="missing")return!0;let E=X(),I=U.openAccountPool(E);if((await I.read()).status==="ready")return O$(I);return((await U.loadAccounts(E))?.accounts.length??0)>0},F=async(E)=>{if(await A$(X().configPath,async()=>{if(H&&await H.authority()!=="local")return!1;if(J0(await V()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...E}}),!0}))await z?.().catch(()=>{})},j=(E)=>({begin:async({headless:I,signal:f})=>{if(H&&await H.authority()!=="local")throw Error(F4);let M=await U.beginAccountLogin({version:Q,headless:I,...f?{signal:f}:{}});return{url:M.url,instructions:M.instructions,completion:M.completion.then(async(k)=>{if(H&&await H.authority()!=="local")throw Error(F4);let l=await E.read(),p=l.status==="ready"?l.rows.find((Q6)=>Q6.id===u0)?.identity:void 0;if(k.accountId&&p&&k.accountId===p)throw Error("that account is already the OpenCode main credential");return{id:k.id,credential:{type:"oauth",refresh:k.refresh,...k.access!==void 0?{access:k.access}:{},...k.expires!==void 0?{expires:k.expires}:{}},...k.accountId!==void 0?{identity:k.accountId}:{},...k.label!==void 0?{label:k.label}:{}}})}},openBrowser:(I)=>U.openBrowser(I)}),N=async(E)=>{if(H&&await H.authority()!=="local")throw Error(F4);let I=E.credential;if(I?.type!=="oauth"||!I.access)throw Error("no usable access token for a quota check");let f=await H8({accessToken:I.access,fetchImpl:$,now:U.now,...E.identity?{accountId:E.identity}:{},accountKey:E.id});return D4(f,U.now(),!0)},Z=(E)=>X$({paths:X(),migrated:E,readAuth:V,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:F,now:U.now}),P=(E,I)=>({title:$$,store:FJ(I,{rowLocks:(f)=>j4(E,f)}),...U.terminal?{terminal:U.terminal}:{},login:j(I),protect:(f,M)=>P9(f,M),extraLocks:t0(E),pollQuota:N,doctor:Z(!0),status:async()=>{if(H&&await H.authority()==="host")return[Q$];let f=await H?.status();if(H&&await H.authority()!=="local"&&f)return[SJ(H.host,H.name,f.enrollment)];return[`Routing: ${(await U.loadAccounts(E))?.routing?.mode??"main-first"}`,...H?[SJ(H.host,H.name,(await H.status()).enrollment)]:[]]},...H&&!A9()?{extraActions:[A(H)]}:{}}),A=(E)=>{let I=E.enrolled();return{id:I?"vault-disconnect":"vault-connect",label:I?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(f)=>{let M=await E.authority();if(M==="host"){f.print(G$);return}if(I){if(M!=="local")await E.disconnect();f.print("Disconnected from the Claustrum vault.");return}if(M!=="local"){f.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}f.print(`Asking the Claustrum vault to enroll ${E.name}…`);let k,l=await E.waitForApproval({...U.vaultWait,onPending:(p)=>{let H6=p.state==="pending"?p.requestId??p.retryCode??"":p.state;if(H6===k)return;k=H6;for(let Q6 of L$(E.name,p))f.print(Q6);f.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});f.print(Z$(E,l).text)}}},x=async()=>{let E=await U.migrationBlockers();return D$({title:$$,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.",...E.length>0?["These processes still hold the move back:",...E.map((I)=>` ${I.pid==="unknown"?"processes that could not be read":`pid ${I.pid}`}: version ${I.version}`)]:[]],actions:[F$({checks:Z(!1)})],...U.terminal?{terminal:U.terminal}:{}})},q=async(E)=>{let I=X(),f=U.openAccountPool(I);if(H&&await H.authority()!=="local")return E9(P(I,f),H);if(await _9(I,f)===void 0)return x();let M=P(I,f);return H?E9(M,H):_$(M)},C=(E)=>async()=>{if(H&&await H.authority()!=="local")throw Error(F4);let I=await E();if(I.method!=="auto")return I;return{...I,callback:async()=>{let f=await I.callback();if(H&&await H.authority()!=="local")return{type:"failed"};return f}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:P$({hasCredential:B,openMenu:q,login:C(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:C(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...H?.enrolled()?[{label:pV,type:"oauth",authorize:async()=>({url:"",instructions:lV,method:"auto",callback:async()=>{let E=await z$(H.paths,H.name);if(E!=="vault"&&E!=="host")return{type:"failed"};try{let I=JSON.parse(await cV(M$(),"utf8"));if(!I||typeof I!=="object"||Array.isArray(I)||Object.hasOwn(I,"openai"))return{type:"failed"}}catch(I){if(I.code!=="ENOENT")return{type:"failed"}}return{...E$,type:"success"}}})}]:[]]}import{createHash as MB}from"node:crypto";var bJ=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function c1(Y){let J={};for(let X of bJ)if(X in Y)J[X]=Y[X];for(let X of Object.keys(Y))if(!(X in J))J[X]=Y[X];return J}import{createHash as BB}from"node:crypto";import{createHash as nV,randomBytes as R$}from"node:crypto";import{chmod as oV,lstat as C$,mkdir as rV,open as sV,readdir as y$,rename as aV,unlink as yJ,writeFile as tV}from"node:fs/promises";import{join as R9,resolve as kJ}from"node:path";var eV=100,xJ="session-unknown",YB=300000,JB=60000,XB=600000,$B=/\.(body|meta|request|response)\.json$/,QB=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,GB=/\.[a-f0-9]{24}\.partial$/;function f$(Y){let J=Y.replace($B,"");if(J===Y||!QB.test(J))return;return J}function zB(Y){let J=Y.replace(GB,"");return J!==Y&&f$(J)!==void 0}async function I$(Y){let{dir:J,maxBytes:X}=Y,$=Y.now??Date.now(),Q=Y.minAgeMs??JB,G=Y.partialStaleMs??XB,z={removed:0,freedBytes:0};if(!(X>0))return z;try{if(l0)await b$(J,"directory");if((await C$(J)).isSymbolicLink())return z;let H=new Set((Y.protectedPaths??[]).map((A)=>kJ(A))),U=await y$(J,{withFileTypes:!0}),V=[];await Promise.all(U.map(async(A)=>{if(!A.isFile())return;let x=zB(A.name),q=x?void 0:f$(A.name);if(!x&&q===void 0)return;let C=R9(J,A.name);try{let E=await C$(C);if(!E.isFile())return;V.push({path:C,size:E.size,mtimeMs:E.mtimeMs,group:q})}catch{}}));let B=V.reduce((A,x)=>A+x.size,0),F=0,j=0,N=async(A)=>{try{await yJ(A.path),B-=A.size,j+=A.size,F+=1}catch{}};for(let A of V){if(A.group!==void 0)continue;if(H.has(kJ(A.path)))continue;if($-A.mtimeMs<G)continue;await N(A)}let Z=new Map;for(let A of V){if(A.group===void 0)continue;let x=Z.get(A.group)??{files:[],newest:0};x.files.push(A),x.newest=Math.max(x.newest,A.mtimeMs),Z.set(A.group,x)}let P=[...Z.entries()].sort(([A,x],[q,C])=>x.newest-C.newest||A.localeCompare(q));for(let[,A]of P){if(B<=X)break;if($-A.newest<Q)continue;if(A.files.some((x)=>H.has(kJ(x.path))))continue;for(let x of A.files)await N(x)}if(F>0)Y.logger?.debug("removed old dump files",{removed:F,freedBytes:j});return{removed:F,freedBytes:j}}catch(H){if(H instanceof V8&&H.code==="ERR_PRIVATE_FILES_SECURITY")throw H;return z}}async function WB(Y,J,X){if(l0)return h$(Y,J,{stagePath:`${Y}.${X?X():R$(12).toString("hex")}.partial`});for(let $=0;;$+=1){let Q=`${Y}.${X?X():R$(12).toString("hex")}.partial`,G=!1,z;try{z=await sV(Q,"wx",384),G=!0,await z.writeFile(J,"utf8"),await z.chmod(384),await z.close(),z=void 0,await aV(Q,Y);return}catch(H){if(await z?.close().catch(()=>{}),G)await yJ(Q).catch(()=>{});if(H.code==="EEXIST"&&$===0)continue;throw H}}}function hJ(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function U8(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function w$(Y){return nV("sha256").update(Y).digest("hex")}function HB(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function S$(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function UB(Y,J){if(Y===void 0)return null;if(Y===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:J.length};let X=0;while(X<Y.length&&X<J.length&&Y[X]===J[X])X++;let $=Y.length-1,Q=J.length-1;while($>=X&&Q>=X&&Y[$]===J[Q])$--,Q--;return{changed:!0,firstByte:X,lastPreviousByte:$,lastCurrentByte:Q,changedPreviousBytes:$-X+1,changedCurrentBytes:Q-X+1,previousBytes:Y.length,currentBytes:J.length}}var VB=0;function g$(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,$=Y.now??Date.now,Q=Y.logger,G=new Set((Y.secretKeys??[]).map(HB)),z=v$({extraSecretKeys:(M)=>G.has(M),extraValuePatterns:[...Y.secretPatterns??[]]}),H=new Set(Y.schemaKeys??["tools"]),U=new Map,V=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function B(M){let k=z.redact({[M]:null})[M];return k===null?void 0:k}function F(M){if(Array.isArray(M))return M.map(F);if(S$(M)){let k={};for(let[l,p]of Object.entries(M)){let H6=B(l);if(H.has(l))k[l]=z.redactStrings(p);else if(H6!==void 0)k[l]=H6;else k[l]=F(p)}return k}return z.redactStrings(M)}function j(M){let k;try{k=JSON.parse(M)}catch{return{text:z.redactStrings(M),parsed:void 0}}let l=F(k),p=JSON.stringify(l);return{text:JSON.stringify(k)===p?M:p,parsed:S$(l)?l:void 0}}async function N(M,k,l,p){let H6=`-${U8(k,xJ)}-${U8(l,"channel")}`,Q6;try{Q6=await y$(M)}catch{return}let u=Q6.filter((R)=>R.endsWith(".meta.json")&&R.includes(H6)).sort().reverse();for(let R of u)try{if(JSON.parse(await vJ(R9(M,R),l0))?.baselineKey!==p)continue;return await vJ(R9(M,R.replace(/\.meta\.json$/,".body.json")),l0)}catch(L6){if(L6 instanceof V8&&(l0||L6.code==="ERR_PRIVATE_FILES_SECURITY"))throw L6}return}function Z(M,k){if(!U.has(M))while(U.size>=eV){let l=U.keys().next().value;if(l===void 0)break;U.delete(l)}U.set(M,k)}async function P(M){if(!J)return;let k=++VB,l=M.session?.trim()||xJ,p=V(),H6=new Date($()).toISOString(),Q6=[H6.replace(/[:.]/g,"-"),String(X),String(k).padStart(6,"0"),U8(l,xJ),U8(M.channel,"channel"),...M.phase?[U8(M.phase,"phase")]:[]].join("-"),u=R9(p,Q6),R={body:`${u}.body.json`,metadata:`${u}.meta.json`,request:`${u}.request.json`},L6=w$(`${M.channel}\x00${l}`);try{if(l0)await k$(p);else await rV(p,{recursive:!0,mode:448}),await oV(p,448);let q6=U.get(L6),d=q6===void 0?void 0:"memory";if(q6===void 0){if(q6=await N(p,l,M.channel,L6),q6!==void 0)d="disk"}let y6=j(M.bodyText),w6={id:Q6,createdAt:H6,pid:X,session:hJ(l),channel:M.channel,...M.phase?{phase:M.phase}:{},accountId:M.accountId,status:M.status,error:M.error===void 0?void 0:z.redactStrings(M.error),baselineKey:L6,bodyBytes:Buffer.byteLength(M.bodyText,"utf8"),bodyHash:w$(M.bodyText),diff:UB(q6,y6.text),baselineSource:d,body:y6.parsed?{parseable:!0,...Y.summarize?.(y6.parsed)}:{parseable:!1},...M.meta?{extra:F(M.meta)}:{},files:R},m=F({url:M.url,method:M.method,accountId:M.accountId,headers:M.headers===void 0?void 0:Object.fromEntries(new Headers(M.headers).entries())}),U6=(_6,Y6)=>l0?x$(_6,Y6):tV(_6,Y6,{encoding:"utf8",mode:384,flag:"wx"}),c=[[R.body,y6.text],[R.metadata,`${JSON.stringify(w6,null,2)}
|
|
2
2
|
`],[R.request,`${JSON.stringify(m,null,2)}
|
|
3
3
|
`]],E6=await Promise.allSettled(c.map(([_6,Y6])=>U6(_6,Y6))),i6=E6.find((_6)=>_6.status==="rejected");if(i6){if(Y.cleanupFailedDumps)await A(c,E6);throw i6.reason}return Z(L6,y6.text),Q?.debug("dumped request",{id:Q6,session:hJ(l),body:R.body}),I(p,Object.values(R)),{id:Q6,files:R,responseFile:`${u}.response.json`}}catch(q6){if(q6 instanceof V8&&(l0||q6.code==="ERR_PRIVATE_FILES_SECURITY"))throw q6;Q?.warn("request dump failed",{session:hJ(l),error:q6 instanceof Error?q6.message:String(q6)});return}}async function A(M,k){await Promise.all(M.map(async([l],p)=>{let H6=k[p];if(H6?.status==="rejected"&&H6.reason?.code==="EEXIST")return;await yJ(l).catch(()=>{})}))}let x=Y.maxBytes??0,q=Y.sweepIntervalMs??YB,C=0;function E(M,k){return{dir:M,maxBytes:x,protectedPaths:k,now:$(),minAgeMs:Y.sweepMinAgeMs,partialStaleMs:Y.partialStaleMs,logger:Q}}function I(M,k){if(!(x>0))return;let l=$();if(l-C<q)return;C=l,I$(E(M,k))}async function f(M,k){if(!M)return;let l=F({status:k.status,requestId:k.requestId,usage:k.usage,...k.fields,complete:k.complete??!0});try{return await WB(M.responseFile,`${JSON.stringify(l,null,2)}
|
|
4
4
|
`,Y.stageName),M.responseFile}catch(p){if(p instanceof V8&&(l0||p.code==="ERR_PRIVATE_FILES_SECURITY"))throw p;Q?.warn("response dump failed",{id:M.id,error:p instanceof Error?p.message:String(p)});return}}return{isEnabled:()=>J,setEnabled:(M)=>{J=M},dump:P,dumpResponse:f,sweep:(M)=>I$(E(V(),M))}}var m$=$6("dump"),F1="x-cortexkit-openai-auth-dump-session",KB=["chatgpt-account-id","email","org_name","organization_name"],NB=["tools"];function fJ(Y){return BB("sha256").update(JSON.stringify(Y)).digest("hex")}function jB(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function LB(Y){let J=Array.isArray(Y.input)?Y.input:[],X=Array.isArray(Y.tools)?Y.tools:[],$=Y.client_metadata!=null&&typeof Y.client_metadata==="object"&&!Array.isArray(Y.client_metadata)?Y.client_metadata:void 0;return{model:typeof Y.model==="string"?Y.model:void 0,stream:Y.stream,generate:Y.generate,store:Y.store,previousResponseID:typeof Y.previous_response_id==="string"?Y.previous_response_id:void 0,promptCacheKey:typeof Y.prompt_cache_key==="string"?Y.prompt_cache_key:void 0,reasoning:Y.reasoning,inputCount:J.length,inputHash:fJ(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:fJ(J[0]),toolsCount:X.length,toolTypes:X.map(jB),toolsHash:fJ(X),clientMetadataKeys:$?Object.keys($).sort():[]}}var B8,c$;function ZB(Y){return c$=Y,g$({dir:()=>C0().dumpDir,maxBytes:Y,logger:m$,secretKeys:KB,schemaKeys:NB,summarize:LB})}async function _4(Y){if(!G8()){B8?.setEnabled(!1);return}let J=C0().dumpMaxBytes;if(!B8||J!==c$)B8=ZB(J);B8.setEnabled(!0);let X=typeof Y.bodyText==="function"?Y.bodyText():Y.bodyText;await B8.dump({session:Y.sessionID,channel:Y.transport,phase:Y.phase,bodyText:X,accountId:Y.accountId,url:Y.url,method:Y.method,headers:Y.headers,status:Y.status,error:Y.error})}async function u1(Y){if(!G8())return;m$.debug("diagnostic",Y)}function P4(Y){return JSON.stringify(gJ(Y))??"undefined"}function gJ(Y){if(Array.isArray(Y))return Y.map(gJ);if(!n(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((J)=>[J,gJ(Y[J])]))}var FB=512,DB=2097152;function mJ(Y,J){if(typeof Y==="function"||typeof J==="function")return!1;if(J!==null&&typeof J==="object"&&Object.hasOwn(J,"toJSON")&&typeof J.toJSON==="function")return!1;if(Y===J)return!0;if(Array.isArray(Y))return Array.isArray(J)&&Y.length===J.length&&Y.every((G,z)=>mJ(G,J[z]));if(Y===null||J===null||typeof Y!=="object"||typeof J!=="object"||Array.isArray(J))return!1;let X=Y,$=J,Q=Object.keys(X);return Q.length===Object.keys($).length&&Q.every((G)=>Object.prototype.propertyIsEnumerable.call($,G)&&mJ(X[G],$[G]))}function p1(Y,J){let X=[],$=[],Q=0;for(let G=0;G<Y.length;G++){let z=J?.texts[G],H=z!==void 0&&mJ(J?.snapshots[G],Y[G]),U=H?z:P4(Y[G]);X.push(U),$.push(H?J?.snapshots[G]:U==="undefined"?void 0:JSON.parse(U)),Q+=U.length}return{texts:X,snapshots:$,retainable:Y.length<=FB&&Q<=DB}}function K8(Y){return Y.retainable?Y:void 0}function N8(Y,J){if(Y.texts.length>J.texts.length)return;for(let X=0;X<Y.texts.length;X++)if(Y.texts[X]!==J.texts[X])return;return Y.texts.length}var p$=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol","gpt-6.1-terra","gpt-6.2-sol","gpt-6.2-astra"]),OB="terminal_resize_reflow",C9="0.166.0",l$=`codex_exec/${C9} (Debian 12.0.0; aarch64) unknown (codex_exec; ${C9})`,_B="seccomp",l1="x-openai-auth-agent";function PB(Y){if(typeof Y!=="string")return;try{let J=JSON.parse(Y);return typeof J==="object"&&J!==null&&!Array.isArray(J)?J:void 0}catch{return}}function j8(Y,J){return n(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===J}function qB(Y,J,X){if(!Y.input)return J.length>0;let $=Y.canonicalInput??p1(Y.input);if(N8($,X)===void 0)return!0;return J.slice(Y.input.length).some((G)=>j8(G,"user")||j8(G,"developer"))}function EB(Y,J,X){let $=Array.isArray(J?.input)?J.input:void 0,Q=$?p1($,Y.canonicalInput):void 0;if($&&Q&&(qB(Y,$,Q)||!Y.turnID))Y.turnID=(X?.uuid??d1)(),Y.turnStartedAt=(X?.now??Date.now)();else if(!Y.turnStartedAt)Y.turnStartedAt=(X?.now??Date.now)();if($&&Q)Y.input=$.slice(),Y.canonicalInput=K8(Q)}function d$(Y){let J=Y.headers.get(l1);if(Y.headers.delete(l1),!Y.metadata)return{init:Y.init};let X=PB(Y.init?.body),$=Y.runtime?.now??Date.now;if(!Y.skipTurnUpdate){if(!Y.websocket)EB(Y.metadata,X,Y.runtime);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=$();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=$()}let Q=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:_B,turn_started_at_unix_ms:Y.metadata.turnStartedAt,request_kind:"turn",window_id:Y.metadata.windowID});if(Y.headers.set("originator","codex_exec"),Y.websocket)Y.headers.delete("accept"),Y.headers.delete("content-type");else Y.headers.set("accept","text/event-stream");if(Y.headers.set("session-id",Y.metadata.threadID),Y.headers.delete("x-session-id"),Y.headers.delete("x-session-affinity"),Y.headers.set("thread-id",Y.metadata.threadID),Y.headers.set("x-codex-window-id",Y.metadata.windowID),Y.headers.set("x-client-request-id",Y.metadata.threadID),Y.headers.set("x-codex-beta-features",OB),Y.headers.set("x-codex-turn-metadata",Q),Y.headers.set("user-agent",l$),Y.headers.set("version",C9),Y.dumpSessionID)Y.headers.set(F1,Y.dumpSessionID);let G=X;if(!G)return{init:Y.init};if(!Y.skipCallStatusRestore&&"input"in G)G.input=u$(G.input,G.model);let z=Y.responsesLite&&typeof G.model==="string"&&p$.has(G.model);if(z&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(G.prompt_cache_key=Y.metadata.threadID,G.parallel_tool_calls??=!0,Array.isArray(G.tools))G.tools=G.tools.map(AB);if(Y.applyEffort?.(G,Y.metadata,J),z)Y.rewriteLite(G);else if(!Y.preserveInstructions)I9(G);let H={...typeof G.client_metadata==="object"&&G.client_metadata!==null?G.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(H["x-codex-turn-metadata"]=Q,H["x-codex-ws-stream-request-start-ms"]=String($()),z)H.ws_request_header_x_openai_internal_codex_responses_lite="true"}return G.client_metadata=H,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(c1(G))}}}function AB(Y){if(!n(Y)||Y.type!=="function")return Y;let J=n(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:U,...V}=Y.parameters;return V})():Y.parameters,{type:X,name:$,description:Q,strict:G,parameters:z,...H}=Y;return{type:X,name:$,description:Q,strict:G??!1,parameters:J,...H}}var i$=new Set(["gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol"]),TB=new Set(["title","compaction","summary"]);function n$(Y,J,X){if(X!==null&&TB.has(X))return;let $=typeof Y.model==="string"?Y.model:"";if(!i$.has($))return;let Q=n(Y.reasoning)?Y.reasoning:void 0,G=typeof Q?.effort==="string"?Q.effort:void 0;if(!G)return;let z=Array.isArray(Y.input)?Y.input:void 0;J.effortUpdates??=[];let H=J.effortUpdates,U=(j)=>MB("sha256").update(P4(j)).digest("hex").slice(0,16);if(J.pinnedEffort===void 0||H.some((j)=>!z||!j8(z[j.anchor],"user")||U(z[j.anchor])!==j.fingerprint)){J.pinnedEffort=G,J.effortUpdates=[];return}if(!z||z.length===0)return;let V=z.findLastIndex((j)=>j8(j,"user")),B=H.at(-1),F=B?.effort??J.pinnedEffort;if(V>=0&&G!==F)if(B?.anchor===V){let j=H.at(-2)?.effort??J.pinnedEffort;if(G===j)H.pop();else B.effort=G}else H.push({anchor:V,fingerprint:U(z[V]),effort:G});else if(V<0&&G!==F)return;if(H.some((j,N)=>N>0&&j.anchor<=(H[N-1]?.anchor??-1))){J.pinnedEffort=G,J.effortUpdates=[];return}Y.reasoning={...Q,effort:J.pinnedEffort};for(let j=H.length-1;j>=0;j--){let N=H[j];if(!N)continue;z.splice(N.anchor,0,{type:"configuration_update",reasoning:{effort:N.effort}})}}function cJ(Y){if(Array.isArray(Y)){let X=Y;for(let $=0;$<Y.length;$++){let Q=cJ(Y[$]);if(Q===Y[$])continue;if(X===Y)X=Y.slice();X[$]=Q}return X}if(!n(Y))return Y;let J=Y;for(let X of Object.keys(Y)){if(Y.type==="input_image"&&X==="detail"){if(J===Y)J={...Y};delete J[X];continue}let $=cJ(Y[X]);if($===Y[X])continue;if(J===Y)J={...Y};J[X]=$}return J}function uJ(Y){let J=n(Y.reasoning)?{...Y.reasoning}:{};J.context="all_turns",Y.reasoning=J,Y.parallel_tool_calls=!1;let X=cJ(Array.isArray(Y.input)?Y.input:[]),$=Array.isArray(Y.tools)?Y.tools.filter((Q)=>!(n(Q)&&Q.type==="web_search")):[];Y.input=[{type:"additional_tools",role:"developer",tools:$},...X],I9(Y,{responsesLite:!0}),delete Y.tools,delete Y.instructions}var r$=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),s$=new Set(["gpt-5.6","gpt-6","gpt-6.1","gpt-6.2"]);function pJ(Y){if(r$.has(Y))return!0;if(s$.has(Y))return!1;let J=o$(Y);return J?parseFloat(J)>5.4:!1}function lJ(Y){if(Y.includes("gpt-5.5"))return{context:400000,input:272000,output:128000};if(Y.includes("gpt-5.6")||Y.includes("gpt-6-astra")||Y.includes("gpt-6-sol")||Y.includes("gpt-6-luna")||Y.includes("gpt-6.2-astra"))return{context:872000,input:744000,output:128000};if(Y.includes("gpt-6.1-sol")||Y.includes("gpt-6.1-terra")||Y.includes("gpt-6.2-sol"))return{context:500000,input:372000,output:128000};return}function dJ(Y){return Y==="gpt-6.1-terra"?"gpt-6.1-sol":void 0}import{lstat as a$,opendir as RB}from"node:fs/promises";import{join as CB}from"node:path";async function t$(Y){try{if(!(await a$(Y)).isDirectory())return;let J=0,X=!1,$=[],Q=async(G)=>{try{let z=await a$(CB(Y,G));if(z.isFile())J+=z.size}catch(z){if(z.code!=="ENOENT")X=!0}};for await(let G of await RB(Y)){if(!G.isFile())continue;if($.push(Q(G.name)),$.length===32)await Promise.all($),$=[]}return await Promise.all($),X?void 0:J}catch(J){return J.code==="ENOENT"?0:void 0}}function iJ(Y){let J=["B","KiB","MiB","GiB","TiB","PiB"],X=0,$=Y;while($>=1024&&X<J.length-1)$/=1024,X++;return`${Number($.toFixed(1))} ${J[X]}`}var nJ={rpcRoot:"openai-auth",directoryPrefix:X5,registrationSessionId:"process"},w9=new Map;function gP(Y,J){if(J?.aborted)return Promise.resolve(!1);if(oJ(Y))return Promise.resolve(!0);return new Promise((X)=>{let $=(H)=>{if(clearTimeout(G),J?.removeEventListener("abort",Q),z.delete($),z.size===0)w9.delete(Y);X(H)},Q=()=>$(!1),G=setTimeout(()=>$(!1),2000),z=w9.get(Y)??new Set;w9.set(Y,z),z.add($),J?.addEventListener("abort",Q,{once:!0})})}function S9(Y,J){e$(nJ,Y,J)}function $5(Y=0,J){let X=Y5(nJ,Y,J);if(J!==void 0)for(let $ of w9.get(J)??[])$(!0);return X}function oJ(Y){return J5(nJ,Y)}var D1=$6("commands");function i1(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function G5(Y){return Y.configPath??i1(Y).configPath}async function L8(Y){let J=Y.settingsSnapshot,X=G5(Y);if(!J||c0(X)!=="shared")return;let $=await e4(X);if($?.decision!=="shared")return;let Q=$.install.target;return{snapshot:J,file:Q,writer:U4(T6,{file:Q,log:D1,separateInstall:!1,createMissing:!0})}}async function sJ(Y,J,X){let $=await L8(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 h1("settings-invalid-value",$.file)}await $.writer.update([J],{host:"opencode"}),await $.snapshot.refresh()}catch(Q){if(Q instanceof h1)throw new J8(Q.code,F9(Q.code));throw Q}}function rJ(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function IB(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 wB="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 SB(Y){let J=(X,$,Q)=>sJ(Y,{setting:X,value:$},()=>k1(Y.store(),t0(i1(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 L8(Y);await $?.snapshot.refresh();let Q=k9($?$.snapshot.view():await Y.loadAccounts(i1(Y))),G=Q?.enabled===!0,z=Q?.subagents===!0,H=X.status(),U=H.window?rJ(H.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${H.tracked===0?"no sessions":`${H.tracked} session${H.tracked===1?"":"s"}`}`,`Timer ${H.running?"armed":"idle"} · subagents ${z?"on":"off"} · sustain ${H.sustain?"on":"off"}`,`Window ${U}`,...Y.cacheKeepNotice?[Y.cacheKeepNotice]:[],`TTL ${Math.round(H.ttlMs/1000)}s · lead ${Math.round(H.leadMs/1000)}s · idle cap ${Math.round(H.maxIdleWarmMs/60000)}min (subagents ${Math.round(H.maxSubagentIdleMs/60000)}min)`],items:H.targets.map((V)=>({id:V.sessionKey,label:V.sessionKey,group:"Sessions",detail:[V.accountId??"main",`expires in ${Math.ceil((V.cacheExpiresAt-H.generatedAt)/1000)}s`,...V.lastWarmedAt?[`last warm ${Math.ceil((H.generatedAt-V.lastWarmedAt)/1000)}s ago`]:[],...V.backoffUntil&&V.backoffUntil>H.generatedAt?[`backoff ${Math.ceil((V.backoffUntil-H.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:V})=>{let B=V.enabled===!0;if(await J("cache_keep_enabled",B,(F)=>{F.enabled=B}),Y.setCacheKeepEnabled?.(B),B)X.start();else{for(let F of X.status().targets)if(!x9(F.sessionKey,!1))X.remove(F.sessionKey);if(X.status().tracked===0)X.stop()}return D1.info(B?"cachekeep enabled":"cachekeep disabled"),B?`Keep-warm is on. TTL ${Math.round(H.ttlMs/1000)}s, idle cap ${Math.round(H.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:V})=>{let B=V.subagents===!0;return await J("cache_keep_subagents",B,(F)=>{F.subagents=B}),Y.setCacheKeepSubagents?.(B),`Subagent warming is ${B?"on":"off"}.`}},{id:"sustain",label:H.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!H.sustain}],run:async({values:V})=>{let B=V.sustain===!0;return await J("cache_keep_sustain",B,(F)=>{F.sustain=B}),Y.setCacheKeepSustain?.(B),B?wB:"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",...H.window?{value:rJ(H.window)}:{}}],run:async({values:V})=>{let B=V.window;if(typeof B!=="string"||B.trim()==="")return await J("cache_keep_window",[],(Z)=>{delete Z.startHour,delete Z.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let F=IB(B);if(!F.ok)return{ok:!1,text:`Invalid window: ${F.reason}`};let{startHour:j,endHour:N}=F;return await J("cache_keep_window",[{start_hour:j,end_hour:N}],(Z)=>{Z.startHour=j,Z.endHour=N}),Y.setCacheKeepWindow?.({startHour:j,endHour:N}),`Warming limited to ${rJ(F)} local hours.`}}]}}}}var Q5=["error","warn","info","debug","trace"];function bB(Y){return{title:"Diagnostics",build:async()=>{let J=G5(Y),X=e4(J)?await C7({configPath:J,snapshot:Y.settingsSnapshot,log:D1}):{lines:[]},$=await L8(Y),Q=C0(J),G=G8(J),H=($?$.snapshot.view():await Y.loadAccounts(i1(Y)).catch(()=>null))?.logging?.level,U=!H||H==="default"?"info":H,V=G?await t$(Q.dumpDir):void 0,B=V===void 0?"size unavailable":iJ(V),F=Q.dumpMaxBytes===0?"no cap":`${iJ(Q.dumpMaxBytes)} cap`,j=Y.layoutNotice?.();return{lines:[G?`Dumps on (${B} / ${F})`:"Dumps off",`Dump directory: ${Q.dumpDir}`,`Log level: ${U}`,...j?[j]:[],...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 Z=N.enabled===!0;await sJ(Y,{setting:"request_dumps",value:Z},()=>k1(Y.store(),t0(i1(Y)),(A)=>{A.dump={...A.dump??{},enabled:Z}}));let P=i7(J);return D1.info(Z?"request dump enabled":"request dump disabled"),Z?`Request dumps are on, written to ${P.dumpDir}.
|