@cortexkit/opencode-openai-auth 1.9.5 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{codex-request-CZ16goZ6.d.ts → codex-request-BLzSBegI.d.ts} +4 -0
  3. package/dist/{index-4gnwkw3a.js → index-17rh67pr.js} +1 -1
  4. package/dist/{index-npj40h62.js → index-29ztc0ay.js} +2 -2
  5. package/dist/{index-f1cqptqa.js → index-361xxyg2.js} +2 -2
  6. package/dist/index-3p1tc2e2.js +91 -0
  7. package/dist/index-3r9thx6n.js +76 -0
  8. package/dist/{index-mcy24ej8.js → index-95z5dpe1.js} +2 -2
  9. package/dist/index-dcyhv7eh.js +8 -0
  10. package/dist/{index-y4j7y8b8.js → index-dkhy2peg.js} +1 -1
  11. package/dist/{index-7qxa018z.js → index-fd3f8vw2.js} +2 -2
  12. package/dist/{index-s2vrkdj4.js → index-mf3dqvbn.js} +2 -2
  13. package/dist/{index-cf0mrvqj.js → index-mkda7acs.js} +1 -1
  14. package/dist/{index-s52j2h64.js → index-w37815v4.js} +1 -1
  15. package/dist/index-ya96m6wr.js +64 -0
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.js +1 -1
  18. package/dist/rpc/port-file.js +1 -1
  19. package/dist/rpc/protocol.js +1 -1
  20. package/dist/rpc/rpc-client.js +1 -1
  21. package/dist/rpc/rpc-dir.js +1 -1
  22. package/dist/sidebar-state.js +1 -1
  23. package/dist/{token-djwdynff.js → token-pd3t5f20.js} +1 -1
  24. package/dist/token-util-807rzwws.js +1 -0
  25. package/dist/tui-preferences.js +1 -1
  26. package/dist/v2/server.d.ts +1 -2
  27. package/dist/v2/server.js +3 -3
  28. package/package.json +6 -6
  29. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +32 -8
  30. package/src/tui-compiled/raw/shared/5f8cc863449a6c85-limits-namespace.js +19 -7
  31. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +10 -5
  32. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
  33. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +47 -3
  34. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +32 -8
  35. package/src/tui-compiled/runtime/shared/5f8cc863449a6c85-limits-namespace.js +19 -7
  36. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +10 -5
  37. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
  38. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +47 -3
  39. package/dist/index-1nrre3d8.js +0 -91
  40. package/dist/index-41yn5c02.js +0 -8
  41. package/dist/index-8rj2xddq.js +0 -63
  42. package/dist/index-h3vtzckv.js +0 -76
  43. package/dist/token-util-0xt1ws82.js +0 -1
package/dist/bin.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{c as s0}from"./index-4gnwkw3a.js";import{Aa as y0,Ba as f,Ca as F,Da as E,Hb as i0,Tb as n0,na as p0,oa as S,pa as g,pb as a0,qa as m0}from"./index-h3vtzckv.js";import{Bd as O0,Dd as d,Ed as w,Fd as u0,Gd as u,Hd as M0,vd as c0}from"./index-1nrre3d8.js";import"./index-41yn5c02.js";import"./index-f1cqptqa.js";import"./index-npj40h62.js";import{ff as q0,lf as Q0,nf as K0,qf as l0}from"./index-s2vrkdj4.js";import"./index-mcy24ej8.js";import"./index-y4j7y8b8.js";import"./index-cf0mrvqj.js";import{spawn as t0}from"node:child_process";var N=4096,e0=1048576;class b0{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 _={run(z,J,Z={}){return new Promise(($)=>{let G=performance.now(),Q=Z.timeoutMs??15000,K=new b0,W=[],V=0,q=!1,j=!1,D=!1,Y;try{Y=t0(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()-G});return}let X=Q>0?setTimeout(()=>{D=!0,Y.kill("SIGTERM")},Q):void 0;Y.stdout?.on("data",(U)=>{let C=e0-V,b=Math.min(C,U.length);if(b>0)W.push(U.subarray(0,b)),V+=b;if(U.length>C)q=!0,Y.kill("SIGTERM")}),Y.stderr?.on("data",(U)=>K.push(U));let B=!1,x=(U,C)=>{if(B)return;if(B=!0,X)clearTimeout(X);$({exitCode:j?1:q?1:U??1,stdout:Buffer.concat(W,V).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...j?{spawnError:!0}:{},signal:C??null,timedOut:D,durationMs:performance.now()-G})};Y.once("error",()=>{if(j=!0,Y.pid===void 0)x(null,null)}),Y.once("close",(U,C)=>x(U,C))})}};function m(z,J,Z,$,G,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:G,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:G,timeoutMs:Q})}var z2="Pi install failed; run pi install after checking your npm connection.";function J2(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 Z2(z){let J=z.indexOf(`
3
- `);return J<0?"":z.slice(J+1)}class h extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(z2);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?Z2(z.stderrTail):z.stderrTail,Z=q0(J);this.stderrTail=J2(typeof Z==="string"?Z:"")}}var $2={opencode:"OpenCode",pi:"Pi"},G2={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function X0({host:z,outcome:J}){return`${$2[z]}: ${G2[J]}`}var Q2=new WeakMap;function W0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;Q2.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as W2,constants as V2,existsSync as D2,readFileSync as j2,realpathSync as Y2,statSync as B2}from"node:fs";import{mkdtemp as U2,rm as F2}from"node:fs/promises";import{tmpdir as x2}from"node:os";import{join as H2}from"node:path";import{parse as O2}from"jsonc-parser";import{homedir as K2}from"node:os";import{posix as b2,win32 as q2}from"node:path";import{fileURLToPath as X2}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?q2:b2,G=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??K2(),Q=z.cwd??process.cwd(),K=(j)=>$.resolve(Q,j),W=J.OPENCODE_CONFIG_DIR?.trim(),V=J.XDG_CONFIG_HOME?.trim(),q=J.PI_CODING_AGENT_DIR?.trim()||$.join(G,".pi","agent");if(q==="~")q=G;else if(/^~[/\\]/.test(q))q=$.join(G,q.slice(2));if(q.startsWith("file://"))q=X2(q);return{env:J,platform:Z,path:$,home:G,cwd:Q,opencode:W?K(W):V?$.join(K(V),"opencode"):$.join(G,".config","opencode"),pi:K(q)}}function i(z,J){try{return B2(z)[J]()}catch{return!1}}var T={exists:D2,isFile:(z)=>i(z,"isFile"),isDirectory:(z)=>i(z,"isDirectory"),isExecutable(z){try{return W2(z,V2.X_OK),i(z,"isFile")}catch{return!1}},readText:(z)=>j2(z,"utf8"),realpath:Y2};function A(z,J={}){let{env:Z,platform:$,path:G,cwd:Q}=k(J),K=J.fs??T,W=Object.entries(Z).find(([q])=>$==="win32"?q.toUpperCase()==="PATH":q==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let q of W.split($==="win32"?";":":")){let j=q.trim().replace(/^"|"$/g,"");if(!j)continue;for(let D of V){let Y=G.resolve(Q,j,z+D);if($==="win32"?K.isFile(Y):K.isExecutable(Y))return Y}}return null}function V0(z={}){let{platform:J,home:Z,env:$,path:G}=k(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",G.join(Z,"Applications","OpenCode.app"),G.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.LOCALAPPDATA||G.join(Z,"AppData","Local");return[G.join(Q,"Programs","opencode"),G.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",G.join(Z,".local","share","applications","opencode.desktop")]}function s(z,J){let Z=J.fs??T,{path:$}=k(J);try{let G=Z.readText(z);if(G.length>65536)return z;let Q=[...G.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...G.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Q.at(-1)?.[1];if(K){let W=$.join($.dirname(z),...K.split(/[/\\]+/));if(Z.isFile(W))return Z.realpath(W)}return Z.realpath(z)}catch{return z}}function M2(z,J){let Z=J.fs??T,{path:$}=k(J),G=$.dirname(s(z,J));for(;;){try{let K=JSON.parse(Z.readText($.join(G,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(K.name))return"2";if(K.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(K.version??"")?"2":"1"}catch{}let Q=$.dirname(G);if(Q===G)return null;G=Q}}function D0(z={}){let J=A("opencode",z),Z=A("opencode2",z),$=J&&Z&&s(J,z)===s(Z,z),G=z.fs??T,{path:Q,opencode:K}=k(z),W="1";for(let q of["jsonc","json"]){let j=Q.join(K,`opencode.${q}`);if(!G.exists(j))continue;try{if(Object.hasOwn(O2(G.readText(j))??{},"plugins"))W="2"}catch{}break}let V=J?M2(J,z)??($?"2":W):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??W}async function r(z,J={}){let Z=J.fs??T,{env:$,platform:G,opencode:Q,pi:K}=k(J),W=J.runner??_,V=A("opencode",J)??A("opencode2",J),q=A("pi",J),j=A("ck",J),D=async(x)=>{if(!x)return null;let U;try{U=await U2(H2(x2(),"common-auth-setup-version-"));let C={...$,HOME:U,USERPROFILE:U,XDG_CONFIG_HOME:U,XDG_DATA_HOME:U,XDG_STATE_HOME:U,XDG_CACHE_HOME:U,OPENCODE_CONFIG_DIR:U,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:U},b=await m(W,G,x,["--version"],C,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(U)await F2(U,{recursive:!0,force:!0}).catch(()=>{})}},Y=!1;if(j&&Z.exists(z.vault.connectionFile))try{(await(J.connect??d)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),Y=!0}catch{Y=!1}let[X,B]=await Promise.all([D(V),D(q)]);return{opencode:{installed:Z.isDirectory(Q)||V0(J).some((x)=>Z.exists(x))||V!==null,executable:V,version:X,directory:Q,generation:D0(J)},pi:{installed:q!==null||Z.isDirectory(K),executable:q,version:B,directory:K},claustrum:{available:Y,executable:j}}}import{setTimeout as T2}from"node:timers/promises";import{writeEnrollmentTokenFile as w2}from"@cortexkit/claustrum-client";var j0=45000,n=new Set(["opencode","litecode","opencode2","pi"]),B0=new Set(["node","bun"]),C2=[...n,...B0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),R2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${C2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,N2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function k2(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function Y0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var I2=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"]),A2=new Set(["-e","--eval","-p","--print"]);function _2(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(A2.has($))return;if($.startsWith("-")){if(!$.includes("=")&&I2.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function U0(z){let[J,...Z]=k2(z);if(J===void 0)return null;let $=Y0(J);if(n.has($))return $;if(!B0.has($))return null;let G=_2($,Z);if(G===void 0)return null;let Q=Y0(G);if(n.has(Q))return Q;return N2.test(G)?"pi":null}class M extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,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 P extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:U0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
2
+ import{c as r0}from"./index-17rh67pr.js";import{Fa as v0,Ga as g,Ha as H,Ia as f,Kb as i0,ac as s0,nc as o0,sa as l0,ta as S,ua as m,va as h0}from"./index-3r9thx6n.js";import{$d as w,Sd as u0,Yd as M0,_d as c,ae as p0,be as p,ce as C0}from"./index-3p1tc2e2.js";import"./index-dcyhv7eh.js";import"./index-361xxyg2.js";import"./index-29ztc0ay.js";import{Df as X0,Jf as K0,Lf as b0,Of as a0}from"./index-mf3dqvbn.js";import"./index-95z5dpe1.js";import"./index-dkhy2peg.js";import"./index-mkda7acs.js";import{spawn as t0}from"node:child_process";var R=4096,e0=1048576;class q0{buffer=Buffer.alloc(R);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=R){if(z.length>R||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-R),this.start=0,this.length=R;return}let J=Math.max(0,this.length+z.length-R);if(J>0)this.truncated=!0;this.start=(this.start+J)%R,this.length-=J;let Z=(this.start+this.length)%R,$=Math.min(z.length,R-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,R-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 _={run(z,J,Z={}){return new Promise(($)=>{let G=performance.now(),Q=Z.timeoutMs??15000,K=new q0,q=[],W=0,b=!1,j=!1,V=!1,Y;try{Y=t0(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()-G});return}let X=Q>0?setTimeout(()=>{V=!0,Y.kill("SIGTERM")},Q):void 0;Y.stdout?.on("data",(F)=>{let C=e0-W,D=Math.min(C,F.length);if(D>0)q.push(F.subarray(0,D)),W+=D;if(F.length>C)b=!0,Y.kill("SIGTERM")}),Y.stderr?.on("data",(F)=>K.push(F));let B=!1,x=(F,C)=>{if(B)return;if(B=!0,X)clearTimeout(X);$({exitCode:j?1:b?1:F??1,stdout:Buffer.concat(q,W).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...j?{spawnError:!0}:{},signal:C??null,timedOut:V,durationMs:performance.now()-G})};Y.once("error",()=>{if(j=!0,Y.pid===void 0)x(null,null)}),Y.once("close",(F,C)=>x(F,C))})}};function h(z,J,Z,$,G,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:G,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:G,timeoutMs:Q})}var z1="Pi install failed; run pi install after checking your npm connection.";function J1(z){let J=Buffer.from(z,"utf8");if(J.length<=R)return z;let Z=J.length-R;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function Z1(z){let J=z.indexOf(`
3
+ `);return J<0?"":z.slice(J+1)}class d extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(z1);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?Z1(z.stderrTail):z.stderrTail,Z=X0(J);this.stderrTail=J1(typeof Z==="string"?Z:"")}}var $1={opencode:"OpenCode",pi:"Pi"},G1={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function W0({host:z,outcome:J}){return`${$1[z]}: ${G1[J]}`}var Q1=new WeakMap;function V0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;Q1.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as W1,constants as V1,existsSync as D1,readFileSync as j1,realpathSync as Y1,statSync as B1}from"node:fs";import{mkdtemp as U1,rm as F1}from"node:fs/promises";import{tmpdir as x1}from"node:os";import{join as H1}from"node:path";import{parse as O1}from"jsonc-parser";import{homedir as K1}from"node:os";import{posix as b1,win32 as q1}from"node:path";import{fileURLToPath as X1}from"node:url";function N(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?q1:b1,G=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??K1(),Q=z.cwd??process.cwd(),K=(j)=>$.resolve(Q,j),q=J.OPENCODE_CONFIG_DIR?.trim(),W=J.XDG_CONFIG_HOME?.trim(),b=J.PI_CODING_AGENT_DIR?.trim()||$.join(G,".pi","agent");if(b==="~")b=G;else if(/^~[/\\]/.test(b))b=$.join(G,b.slice(2));if(b.startsWith("file://"))b=X1(b);return{env:J,platform:Z,path:$,home:G,cwd:Q,opencode:q?K(q):W?$.join(K(W),"opencode"):$.join(G,".config","opencode"),pi:K(b)}}function s(z,J){try{return B1(z)[J]()}catch{return!1}}var T={exists:D1,isFile:(z)=>s(z,"isFile"),isDirectory:(z)=>s(z,"isDirectory"),isExecutable(z){try{return W1(z,V1.X_OK),s(z,"isFile")}catch{return!1}},readText:(z)=>j1(z,"utf8"),realpath:Y1};function A(z,J={}){let{env:Z,platform:$,path:G,cwd:Q}=N(J),K=J.fs??T,q=Object.entries(Z).find(([b])=>$==="win32"?b.toUpperCase()==="PATH":b==="PATH")?.[1]??"",W=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let b of q.split($==="win32"?";":":")){let j=b.trim().replace(/^"|"$/g,"");if(!j)continue;for(let V of W){let Y=G.resolve(Q,j,z+V);if($==="win32"?K.isFile(Y):K.isExecutable(Y))return Y}}return null}function D0(z={}){let{platform:J,home:Z,env:$,path:G}=N(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",G.join(Z,"Applications","OpenCode.app"),G.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.LOCALAPPDATA||G.join(Z,"AppData","Local");return[G.join(Q,"Programs","opencode"),G.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",G.join(Z,".local","share","applications","opencode.desktop")]}function r(z,J){let Z=J.fs??T,{path:$}=N(J);try{let G=Z.readText(z);if(G.length>65536)return z;let Q=[...G.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...G.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Q.at(-1)?.[1];if(K){let q=$.join($.dirname(z),...K.split(/[/\\]+/));if(Z.isFile(q))return Z.realpath(q)}return Z.realpath(z)}catch{return z}}function M1(z,J){let Z=J.fs??T,{path:$}=N(J),G=$.dirname(r(z,J));for(;;){try{let K=JSON.parse(Z.readText($.join(G,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(K.name))return"2";if(K.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(K.version??"")?"2":"1"}catch{}let Q=$.dirname(G);if(Q===G)return null;G=Q}}function j0(z={}){let J=A("opencode",z),Z=A("opencode2",z),$=J&&Z&&r(J,z)===r(Z,z),G=z.fs??T,{path:Q,opencode:K}=N(z),q="1";for(let b of["jsonc","json"]){let j=Q.join(K,`opencode.${b}`);if(!G.exists(j))continue;try{if(Object.hasOwn(O1(G.readText(j))??{},"plugins"))q="2"}catch{}break}let W=J?M1(J,z)??($?"2":q):null;if(Z&&W==="1"&&!$)return"ambiguous";return Z||$?"2":W??q}async function n(z,J={}){let Z=J.fs??T,{env:$,platform:G,opencode:Q,pi:K}=N(J),q=J.runner??_,W=A("opencode",J)??A("opencode2",J),b=A("pi",J),j=A("ck",J),V=async(x)=>{if(!x)return null;let F;try{F=await U1(H1(x1(),"common-auth-setup-version-"));let C={...$,HOME:F,USERPROFILE:F,XDG_CONFIG_HOME:F,XDG_DATA_HOME:F,XDG_STATE_HOME:F,XDG_CACHE_HOME:F,OPENCODE_CONFIG_DIR:F,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:F},D=await h(q,G,x,["--version"],C,2000);return D.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(D.stdout)?.[0]??null:null}catch{return null}finally{if(F)await F1(F,{recursive:!0,force:!0}).catch(()=>{})}},Y=!1;if(j&&Z.exists(z.vault.connectionFile))try{(await(J.connect??c)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),Y=!0}catch{Y=!1}let[X,B]=await Promise.all([V(W),V(b)]);return{opencode:{installed:Z.isDirectory(Q)||D0(J).some((x)=>Z.exists(x))||W!==null,executable:W,version:X,directory:Q,generation:j0(J)},pi:{installed:b!==null||Z.isDirectory(K),executable:b,version:B,directory:K},claustrum:{available:Y,executable:j}}}import{setTimeout as T1}from"node:timers/promises";import{writeEnrollmentTokenFile as w1}from"@cortexkit/claustrum-client";var Y0=45000,o=new Set(["opencode","litecode","opencode2","pi"]),U0=new Set(["node","bun"]),C1=[...o,...U0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),R1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${C1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,N1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function k1(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function B0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var I1=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"]),A1=new Set(["-e","--eval","-p","--print"]);function _1(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(A1.has($))return;if($.startsWith("-")){if(!$.includes("=")&&I1.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function F0(z){let[J,...Z]=k1(z);if(J===void 0)return null;let $=B0(J);if(o.has($))return $;if(!U0.has($))return null;let G=_1($,Z);if(G===void 0)return null;let Q=B0(G);if(o.has(Q))return Q;return N1.test(G)?"pi":null}class M extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,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 P extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:F0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
4
  ${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
5
5
  `)}
6
6
 
7
- Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function o(z=_,J={}){let Z=(J.platform??process.platform)==="win32",$=J.selfPid??process.pid,G={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(K,W,V,q)=>{let j=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let D=await z.run(W,V,{env:J.env,timeoutMs:q});return G={step:K,exitCode:D.exitCode,signal:D.signal??null,timedOut:D.timedOut??!1,durationMs:D.durationMs??performance.now()-j},D}finally{if(G.exitCode===null)G.durationMs=performance.now()-j;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",R2],j0);if(q.exitCode!==0)throw new M(G);let j=JSON.parse(q.stdout);if(!j||typeof j!=="object"||!("complete"in j)||j.complete!==!0||!("processes"in j))throw new M(G);let D=j.processes,Y=D===null?[]:Array.isArray(D)?D:[D],X=[];for(let B of Y){if(!B||typeof B!=="object"||!("Name"in B)||typeof B.Name!=="string"||!("ProcessId"in B)||!Number.isSafeInteger(B.ProcessId)||B.ProcessId<0||!("CommandLine"in B))throw new M(G);let x=B.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(B.Name))X.push({pid:x,command:B.Name});else if(typeof B.CommandLine==="string")X.push({pid:x,command:B.CommandLine});else if(x!==$)throw new M(G)}return X}let K=await Q(Z?"tasklist":"ps",Z?"tasklist.exe":"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new M(G);let W=[];for(let q of K.stdout.split(/\r?\n/)){let j=q.trim();if(!j)continue;let D,Y;if(Z){let X=/^"([^"]+)","(\d+)"(?:,|$)/.exec(j);if(!X)throw new M(G);Y=X[1]??"",D=Number(X[2])}else{let X=/^(\d+)\s+(.+)$/.exec(j);if(!X){if(/^PID\s+COMMAND$/i.test(j))continue;throw new M(G)}D=Number(X[1]),Y=X[2]??""}if(!Number.isSafeInteger(D)||D<0)throw new M(G);W.push({pid:D,command:Y})}if(!W.length)throw new M(G);let V=W.filter((q)=>q.pid!==$&&/^(?:node|bun)\.exe$/i.test(q.command));if(Z&&V.length&&J.inspectRuntimes!==!1){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],j0);if(q.exitCode!==0)throw new M(G);let j=JSON.parse(q.stdout||"null"),D=j===null?[]:Array.isArray(j)?j:[j],Y=new Map;for(let X of D){if(!X||typeof X!=="object"||!("ProcessId"in X)||!("CommandLine"in X)||!Number.isSafeInteger(X.ProcessId))throw new M(G);if(typeof X.CommandLine==="string")Y.set(Number(X.ProcessId),X.CommandLine);else if(V.some((B)=>B.pid===X.ProcessId))throw new M(G)}for(let X of V)X.command=Y.get(X.pid)??""}return W}catch(K){if(K instanceof M)throw K;throw new M(G)}}function y(z=_,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&U0(G.command)!==null;return{async listRunningHosts(G){return(await o(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await o(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((W)=>W.pid!==Z&&/^(?:node|bun)\.exe$/i.test(W.command)).length:0}}}}async function v(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var L2="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",C0='This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',R0=300000,F0=1000,x0=[1000,2000,4000,8000,16000,30000];function t(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class I extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=t(J.lastErrorCode)}}function H0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function N0(z,J,Z,$,G){let{name:Q,paths:K}=z.vault.hosts[J],W=w(K);await G();let V=await(Z.connect??d)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new I("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),q=Z.now??(()=>performance.now()),j=Z.wait??T2;try{let D=new M0({proposedName:Q,paths:W,client:V,writeTokenFile:async(b,H)=>{await G(),await w2(b,H)}});F($,`Asking the vault to connect ${Q}…`);let Y=q()+R0,X,B,x,U=0;for(;;){await G();let b=await D.reconcile();if(b.state==="approved"){F($,`Connected ${J} to Claustrum.`);return}if(b.state==="unavailable"&&b.code===O0)throw new I(C0,{reason:"unsupported-vault",lastErrorCode:b.code});if(b.state!=="pending"&&b.state!=="busy")throw new I("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in b&&{lastErrorCode:b.code}});let H=F0;if(b.state==="busy")B="busy";else if(b.retryCode)B=b.retryCode;if(b.state==="pending"&&b.requestId){if(U=0,b.requestId!==X){if(!/^[a-zA-Z0-9_-]+$/.test(b.requestId))throw new I("Invalid enrollment request id.",{reason:"invalid-request"});X=b.requestId,F($,"Waiting for approval. In another terminal, run:"),F($,` ${H0(b.requestId,Q)}`),F($,`Enrollment files: ${W.statePath}, ${W.tokenPath}`)}}else if(b.state==="pending"&&b.retryCode){H=x0[Math.min(U,x0.length-1)]??F0,U++;let R=t(b.retryCode);if(R!==x)x=R,F($,`The vault has not created the request yet (${R}); retrying.`)}let O=Y-q();if(O<=0)break;await j(Math.min(H,O))}if(X)throw new I(`Claustrum approval is still pending. In another terminal, run: ${H0(X,Q)} and then rerun setup.`,{reason:"approval-pending",...B!==void 0&&{lastErrorCode:B}});let C=t(B);throw new I(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(D){if(D instanceof P||D instanceof M||D instanceof I)throw D;let Y=D?.code;throw new I(L2,{reason:"incomplete",...typeof Y==="string"&&{lastErrorCode:Y}})}finally{V.close()}}var k0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",P2=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function c(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function I0(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let Z=0;Z<z.length;Z++){let $=z[Z],G=$.indexOf("="),Q=G===-1?$:$.slice(0,G),K=P2.find((V)=>V.name===Q);if(!K)throw c($);if(!("values"in K)){if(G!==-1)throw c($);J[K.key]=!0;continue}let W;if(G!==-1)W=$.slice(G+1);else if(K.spaceForm)W=z[++Z];else throw c($);if(W===void 0||!K.values.includes(W))throw K.invalid?Error(K.invalid):c($);if(K.key==="hosts")J.hosts.push(W);else J.opencode=W}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function A0(z,J){let Z=new Set(J);for(;;){let $=await E(z,[...["opencode","pi"].map((G)=>({value:G,label:`[${Z.has(G)?"x":" "}] ${G==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(G)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if($===null)return null;if($==="done")return[...Z];if(Z.has($))Z.delete($);else Z.add($)}}import{domainToUnicode as u2}from"node:url";import{applyEdits as e,createScanner as p2,findNodeAtLocation as l2,modify as T0,parse as a2,parseTree as i2}from"jsonc-parser";import{randomUUID as S2}from"node:crypto";import{mkdir as y2,open as v2,rename as E2,stat as f2,unlink as g2}from"node:fs/promises";import{basename as m2,dirname as h2,join as d2}from"node:path";import{setTimeout as c2}from"node:timers/promises";async function _0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=h2(z);await y2(G,{recursive:!0});let Q;if(!$)try{Q=(await f2(z)).mode&4095}catch(V){if(V.code!=="ENOENT")throw V}let K=d2(G,`.${m2(z)}.${(Z.stageName??S2)()}.tmp`),W=!1;try{let V=await v2(K,"wx",Q??438);W=!0;try{if(await V.writeFile(J,"utf8"),Q!==void 0)await V.chmod(Q)}finally{await V.close()}let q=Z.now??(()=>performance.now()),j=q();for(let D=0;;D++){await Z.beforeRename?.();try{await(Z.rename??E2)(K,z),W=!1;return}catch(Y){let X=Y.code,B=2000-(q()-j);if(!$||!["EPERM","EBUSY","EACCES"].includes(X??"")||B<=0||D>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??c2)(Math.min(B,25*2**Math.min(D,2)))}}}finally{if(W)await g2(K).catch(()=>{})}}function L0(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function z0(z){let J=L0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function s2(z,J){let Z=new URL(z);if(/%2f/i.test(Z.pathname)||J&&/%5c/i.test(Z.pathname))throw Error("Encoded path separators are not valid in a file URL.");let $=decodeURIComponent(Z.pathname);if(!J){if(Z.hostname)throw Error("A POSIX file URL must be local.");return $}let G=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${u2(Z.hostname)}${G}`;if(!/^\\[a-z]:/i.test(G))throw Error("A Windows file URL must have an absolute drive path.");return G.slice(1)}function r2(z,J,Z){let{path:$,platform:G}=k(Z);try{let Q=/^file:\/\//i.test(z)?s2(z,G==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let K=JSON.parse((Z.fs??T).readText($.join(Q,"package.json")));return K&&typeof K==="object"&&"name"in K&&typeof K.name==="string"?K.name:null}catch{return null}}function P0(z,J){let Z=[],$=a2(z,Z,{allowTrailingComma:!0});if(Z.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");if($[J]!==void 0&&!Array.isArray($[J]))throw Error(`OpenCode ${J} must be an array.`);return $}function w0(z,J,Z){let $=i2(z),G=$&&l2($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let W=[{offset:K.offset,length:K.length,content:""}],V=(q,j)=>{let D=p2(z.slice(q,j),!0);if(D.scan(),z[q+D.getTokenOffset()]===",")W.push({offset:q+D.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let q=Q[Z-1];if(q)V(q.offset+q.length,K.offset);V(K.offset+K.length,G.offset+G.length-1)}else V(K.offset+K.length,Q[Z+1]?.offset??K.offset+K.length);return e(z,W)}function S0(z,J,Z,$){let G=P0(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
7
+ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function t(z=_,J={}){let Z=(J.platform??process.platform)==="win32",$=J.selfPid??process.pid,G={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(K,q,W,b)=>{let j=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let V=await z.run(q,W,{env:J.env,timeoutMs:b});return G={step:K,exitCode:V.exitCode,signal:V.signal??null,timedOut:V.timedOut??!1,durationMs:V.durationMs??performance.now()-j},V}finally{if(G.exitCode===null)G.durationMs=performance.now()-j;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let b=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",R1],Y0);if(b.exitCode!==0)throw new M(G);let j=JSON.parse(b.stdout);if(!j||typeof j!=="object"||!("complete"in j)||j.complete!==!0||!("processes"in j))throw new M(G);let V=j.processes,Y=V===null?[]:Array.isArray(V)?V:[V],X=[];for(let B of Y){if(!B||typeof B!=="object"||!("Name"in B)||typeof B.Name!=="string"||!("ProcessId"in B)||!Number.isSafeInteger(B.ProcessId)||B.ProcessId<0||!("CommandLine"in B))throw new M(G);let x=B.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(B.Name))X.push({pid:x,command:B.Name});else if(typeof B.CommandLine==="string")X.push({pid:x,command:B.CommandLine});else if(x!==$)throw new M(G)}return X}let K=await Q(Z?"tasklist":"ps",Z?"tasklist.exe":"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new M(G);let q=[];for(let b of K.stdout.split(/\r?\n/)){let j=b.trim();if(!j)continue;let V,Y;if(Z){let X=/^"([^"]+)","(\d+)"(?:,|$)/.exec(j);if(!X)throw new M(G);Y=X[1]??"",V=Number(X[2])}else{let X=/^(\d+)\s+(.+)$/.exec(j);if(!X){if(/^PID\s+COMMAND$/i.test(j))continue;throw new M(G)}V=Number(X[1]),Y=X[2]??""}if(!Number.isSafeInteger(V)||V<0)throw new M(G);q.push({pid:V,command:Y})}if(!q.length)throw new M(G);let W=q.filter((b)=>b.pid!==$&&/^(?:node|bun)\.exe$/i.test(b.command));if(Z&&W.length&&J.inspectRuntimes!==!1){let b=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],Y0);if(b.exitCode!==0)throw new M(G);let j=JSON.parse(b.stdout||"null"),V=j===null?[]:Array.isArray(j)?j:[j],Y=new Map;for(let X of V){if(!X||typeof X!=="object"||!("ProcessId"in X)||!("CommandLine"in X)||!Number.isSafeInteger(X.ProcessId))throw new M(G);if(typeof X.CommandLine==="string")Y.set(Number(X.ProcessId),X.CommandLine);else if(W.some((B)=>B.pid===X.ProcessId))throw new M(G)}for(let X of W)X.command=Y.get(X.pid)??""}return q}catch(K){if(K instanceof M)throw K;throw new M(G)}}function v(z=_,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&F0(G.command)!==null;return{async listRunningHosts(G){return(await t(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await t(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((q)=>q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(q.command)).length:0}}}}async function E(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var L1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",R0='This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',N0=300000,x0=1000,H0=[1000,2000,4000,8000,16000,30000];function e(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class I extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=e(J.lastErrorCode)}}function O0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function k0(z,J,Z,$,G){let{name:Q,paths:K}=z.vault.hosts[J],q=w(K);await G();let W=await(Z.connect??c)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new I("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),b=Z.now??(()=>performance.now()),j=Z.wait??T1;try{let V=new C0({proposedName:Q,paths:q,client:W,writeTokenFile:async(U,O)=>{await G(),await w1(U,O)}});await G();let Y=await V.status();if(Y.state==="approved"){H($,`Already connected as ${Y.approvedName??Y.proposedName}.`);return}H($,`Asking the vault to connect ${Q}…`);let X=b()+N0,B,x,F,C=0;for(;;){let U=await V.reconcile();if(U.state==="approved"){H($,`Connected ${J} to Claustrum.`);return}if(U.state==="unavailable"&&U.code===M0)throw new I(R0,{reason:"unsupported-vault",lastErrorCode:U.code});if(U.state!=="pending"&&U.state!=="busy")throw new I("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in U&&{lastErrorCode:U.code}});let O=x0;if(U.state==="busy")x="busy";else if(U.retryCode)x=U.retryCode;if(U.state==="pending"&&U.requestId){if(C=0,U.requestId!==B){if(!/^[a-zA-Z0-9_-]+$/.test(U.requestId))throw new I("Invalid enrollment request id.",{reason:"invalid-request"});B=U.requestId,H($,"Waiting for approval. In another terminal, run:"),H($,` ${O0(U.requestId,Q)}`),H($,`Enrollment files: ${q.statePath}, ${q.tokenPath}`)}}else if(U.state==="pending"&&U.retryCode){O=H0[Math.min(C,H0.length-1)]??x0,C++;let y=e(U.retryCode);if(y!==F)F=y,H($,`The vault has not created the request yet (${y}); retrying.`)}let k=X-b();if(k<=0)break;await j(Math.min(O,k)),await G()}if(B)throw new I(`Claustrum approval is still pending. In another terminal, run: ${O0(B,Q)} and then rerun setup.`,{reason:"approval-pending",...x!==void 0&&{lastErrorCode:x}});let D=e(x);throw new I(`The vault never created the enrollment request (last error: ${D}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:D})}catch(V){if(V instanceof P||V instanceof M||V instanceof I)throw V;let Y=V?.code;throw new I(L1,{reason:"incomplete",...typeof Y==="string"&&{lastErrorCode:Y}})}finally{W.close()}}var I0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",P1=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function u(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function A0(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let Z=0;Z<z.length;Z++){let $=z[Z],G=$.indexOf("="),Q=G===-1?$:$.slice(0,G),K=P1.find((W)=>W.name===Q);if(!K)throw u($);if(!("values"in K)){if(G!==-1)throw u($);J[K.key]=!0;continue}let q;if(G!==-1)q=$.slice(G+1);else if(K.spaceForm)q=z[++Z];else throw u($);if(q===void 0||!K.values.includes(q))throw K.invalid?Error(K.invalid):u($);if(K.key==="hosts")J.hosts.push(q);else J.opencode=q}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function _0(z,J){let Z=new Set(J);for(;;){let $=await f(z,[...["opencode","pi"].map((G)=>({value:G,label:`[${Z.has(G)?"x":" "}] ${G==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(G)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if($===null)return null;if($==="done")return[...Z];if(Z.has($))Z.delete($);else Z.add($)}}import{domainToUnicode as u1}from"node:url";import{applyEdits as z0,createScanner as p1,findNodeAtLocation as l1,modify as w0,parse as a1,parseTree as i1}from"jsonc-parser";import{randomUUID as S1}from"node:crypto";import{mkdir as y1,open as v1,rename as E1,stat as f1,unlink as g1}from"node:fs/promises";import{basename as m1,dirname as h1,join as d1}from"node:path";import{setTimeout as c1}from"node:timers/promises";async function T0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=h1(z);await y1(G,{recursive:!0});let Q;if(!$)try{Q=(await f1(z)).mode&4095}catch(W){if(W.code!=="ENOENT")throw W}let K=d1(G,`.${m1(z)}.${(Z.stageName??S1)()}.tmp`),q=!1;try{let W=await v1(K,"wx",Q??438);q=!0;try{if(await W.writeFile(J,"utf8"),Q!==void 0)await W.chmod(Q)}finally{await W.close()}let b=Z.now??(()=>performance.now()),j=b();for(let V=0;;V++){await Z.beforeRename?.();try{await(Z.rename??E1)(K,z),q=!1;return}catch(Y){let X=Y.code,B=2000-(b()-j);if(!$||!["EPERM","EBUSY","EACCES"].includes(X??"")||B<=0||V>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??c1)(Math.min(B,25*2**Math.min(V,2)))}}}finally{if(q)await g1(K).catch(()=>{})}}function P0(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function J0(z){let J=P0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function s1(z,J){let Z=new URL(z);if(/%2f/i.test(Z.pathname)||J&&/%5c/i.test(Z.pathname))throw Error("Encoded path separators are not valid in a file URL.");let $=decodeURIComponent(Z.pathname);if(!J){if(Z.hostname)throw Error("A POSIX file URL must be local.");return $}let G=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${u1(Z.hostname)}${G}`;if(!/^\\[a-z]:/i.test(G))throw Error("A Windows file URL must have an absolute drive path.");return G.slice(1)}function r1(z,J,Z){let{path:$,platform:G}=N(Z);try{let Q=/^file:\/\//i.test(z)?s1(z,G==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let K=JSON.parse((Z.fs??T).readText($.join(Q,"package.json")));return K&&typeof K==="object"&&"name"in K&&typeof K.name==="string"?K.name:null}catch{return null}}function S0(z,J){let Z=[],$=a1(z,Z,{allowTrailingComma:!0});if(Z.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");if($[J]!==void 0&&!Array.isArray($[J]))throw Error(`OpenCode ${J} must be an array.`);return $}function L0(z,J,Z){let $=i1(z),G=$&&l1($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let q=[{offset:K.offset,length:K.length,content:""}],W=(b,j)=>{let V=p1(z.slice(b,j),!0);if(V.scan(),z[b+V.getTokenOffset()]===",")q.push({offset:b+V.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let b=Q[Z-1];if(b)W(b.offset+b.length,K.offset);W(K.offset+K.length,G.offset+G.length-1)}else W(K.offset+K.length,Q[Z+1]?.offset??K.offset+K.length);return z0(z,q)}function y0(z,J,Z,$){let G=S0(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
8
8
  `)?`\r
9
9
  `:`
10
- `}},K=z,W=G[J],V=Array.isArray(W)?[...W]:[],q=V.flatMap((Y,X)=>z0(Y)===Z?[X]:[]),j=`${Z}@${$}`;if(!q.length)K=e(K,T0(K,W===void 0?[J]:[J,V.length],W===void 0?[j]:j,Q));else{let Y=q[0],X=V[Y],B=Array.isArray(X)?[j,...X.slice(1)]:X&&typeof X==="object"?{...X,package:j}:j;if(JSON.stringify(X)!==JSON.stringify(B))K=e(K,T0(K,[J,Y],B,Q));for(let x of q.slice(1).reverse())K=w0(K,J,x)}let D=J==="plugin"?"plugins":"plugin";if(Array.isArray(G[D])){let Y=G[D];for(let X=Y.length-1;X>=0;X--)if(z0(Y[X])===Z)K=w0(K,D,X)}return K}function J0(z,J,Z={}){let $=Z.fs??T,{path:G,opencode:Q}=k(Z),K=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((V)=>{let q=G.join(Q,`${V}.jsonc`),j=G.join(Q,`${V}.json`),D=$.exists(q)?q:$.exists(j)?j:q,Y=$.exists(D),X=Y?$.readText(D):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
11
- `,B=P0(X,K),x=[],U=[];for(let b of["plugin","plugins"]){if(!Array.isArray(B[b]))continue;for(let H of B[b]){let O=L0(H);if(O===null)continue;if(r2(O,D,Z)===z.packages.opencode)x.push(JSON.stringify(H));else if(z0(H)===z.packages.opencode)U.push(JSON.stringify(H))}}if(x.length>0)return{path:D,content:X,changed:!1,existingLocalEntries:x,existingNpmEntries:U};let C=S0(X,K,z.packages.opencode,z.version);return{path:D,content:C,changed:!Y||C!==X}})}async function Z0(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await _0(Z.path,Z.content,{beforeRename:J})}}async function $0(z,J,Z={}){let{platform:$,env:G}=k(Z),Q=await m(Z.runner??_,$,J,["install",`npm:${z.packages.pi}@${z.version}`],G);if(Q.exitCode!==0||Q.timedOut)throw new h({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var v0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function n2(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.")}async function o2(z,J,Z){let $=[];for(let G of J){let Q=Z.get(G)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:W}=z.vault.hosts[G],V=await u(w(W),K).catch(()=>"unreadable");if(V==="vault")Q="enrolled";else if(V==="local")Q="not-enrolled"}$.push({host:G,outcome:Q})}return $}async function G0(z,J=[],Z={}){let $=I0(J);n2(z);let G=Z.terminal??y0(),Q=await r(z,Z);F(G,`${z.displayName} setup`);for(let[b,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])F(G,`${b}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);F(G,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)F(G,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let W=["opencode","pi"].filter((b)=>Q[b].installed&&!(b==="pi"&&K));if($.hosts.some((b)=>!W.includes(b)))throw Error(k0);let V=$.yes||$.dryRun&&!f(G);if(!V&&!f(G))throw Error("Setup requires a TTY or --yes.");let q=$.hosts.length?W.filter((b)=>$.hosts.includes(b)):V?W:await A0(G,W)??[],j=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(q.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(V||!f(G))throw Error(v0);let b=await E(G,[{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};j=b}if(!q.length)return F(G,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:q,dryRun:$.dryRun,mode:"local",detection:Q};let{env:D,platform:Y}=k(Z),X=Z.fence??y(Z.runner??_,{platform:Y}),B=async()=>{try{await v(X,D)}catch(b){if(b instanceof M)F(G,b.refusalText);throw b}};if(F(G,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let b=X.previewRunningHosts?await X.previewRunningHosts(D):{hosts:await X.listRunningHosts(D),uncheckedRuntimes:0},H=b.hosts;if(b.uncheckedRuntimes>0)F(G,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let O=new Set(new P(H).activeHosts.map((R)=>R.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let R of O)F(G,`${R} is running; setup will ask you to quit it.`)}catch(b){if(F(G,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof M)F(G,b.refusalText)}else await B();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 x=$.claustrum||$.enrollOnly;if(!x&&!$.login&&!$.noClaustrum&&!V&&Q.claustrum.available&&f(G)){let b=await E(G,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(b===null)return F(G,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};x=b===!0}let U=x?"claustrum":"local",C=!$.enrollOnly&&q.includes("opencode")?J0(z,j,Z):[];for(let b of C){for(let O of b.existingLocalEntries??[])F(G,`OpenCode: already registered from ${O} in ${b.path}.`);let H=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(H.length>1)F(G,`Warning: ${z.displayName} may load twice in ${b.path}: ${H.join(", ")}. Entries were left unchanged.`)}if($.dryRun){F(G,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of q){if(z.beforeSignIn)F(G,`Would run beforeSignIn(${b}, ${U}).`);if(x){let H=w(z.vault.hosts[b].paths);F(G,`Would Connect ${b}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else F(G,`Would sign in locally for ${b}.`);if(!$.enrollOnly&&z.beforeRegister)F(G,`Would run beforeRegister(${b}, ${U}).`)}for(let b of C)F(G,`${b.changed?"Would write":"Unchanged"} ${b.path}:
12
- ${b.content}`);if(!$.enrollOnly&&q.includes("pi"))F(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let b of q)F(G,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:j,mode:U,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await B(),await z.beforeSignIn?.(O,b),await B(),x){H.set(O,"unknown");try{await N0(z,O,Z,G,B)}catch(R){if(R instanceof I)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await z.signInLocal(O,b);if(await B(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,U,b),await B(),O==="opencode")await Z0(C,B);else await $0(z,Q.pi.executable,Z);await B(),await z.migrate?.(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await o2(z,q,H);W0(O,R);for(let o0 of R)F(G,X0(o0))}catch{}throw O}}if(F(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${q.join(", ")} (${U}).`),$.enrollOnly)F(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(G,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:q,dryRun:$.dryRun,mode:U,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.9.5",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","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.34.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.0"},dependencies:{"@cortexkit/claustrum-client":"^0.14.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.7.0","@opentui/solid":">=0.7.0",ai:"^7.0.155","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};import{basename as $1}from"node:path";import{resolveClaustrumConnectionPath as G1}from"@cortexkit/claustrum-client";var E0={name:"@cortexkit/pi-openai-auth",version:"1.9.5",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 @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","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.34.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.14.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0"},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 p}from"node:fs";import{homedir as l}from"node:os";import{join as a,resolve as f0}from"node:path";import{fileURLToPath as z1}from"node:url";var g0=new Set;function J1(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return a(l(),".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 l();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return a(l(),z.slice(2));return z.startsWith("file://")?z1(z):z}function h0(z=J1()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=a(z,Q0),$=a(l(),".pi","agent",Q0),G=(K)=>{let W=K0(K),V=m0(g(W),"pi");return p(K)||p(W)||p(V.tokenPath)||p(V.statePath)};if(f0(Z)===f0($)||G(Z)||!G($))return Z;let Q=`${Z}\x00${$}`;if(!g0.has(Q))g0.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 Z1(z=h0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||K0(z)}function d0(z=h0()){return{configPath:z,statePath:Z1(z)}}function r0(z={}){let J=z.print??console.log,Z=z.fence??y(),$={opencode:{stateDir:g(a0().statePath),host:"opencode"},pi:{stateDir:g(d0().statePath),host:"pi"}},G=async(Q)=>{if(await u(w($[Q]),S(Q))!=="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:L.name,pi:E0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:G1(),hosts:{opencode:{name:S("opencode"),paths:$.opencode},pi:{name:S("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let W=await u0(w($[Q]),S(Q)),V=W.state==="approved"?W.approvedName:void 0,q=V??("proposedName"in W?W.proposedName:S(Q));if(!V)J("The enrollment state does not record an approved name. The command below uses the proposed name; if the vault approved a different name, substitute it.");if(J(`Allow this host to read OpenAI accounts with:
13
- ck auth grant --principal enrolled:${q} --selector-kind category --selector ${p0.category} --operation read`),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 G(Q)},async signInLocal(Q,K){if(await G(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let U=$1(A("opencode2",z.io)??A("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${U} 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(K.opencodeGeneration==="2")return;if(i0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let W=s0(),V={path:{id:"openai"}};if(await W.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let q=z.beginLogin??c0,j=new AbortController,D=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),Y={version:L.version,signal:j.signal},X,B=!D;try{X=await q({...Y,headless:D})}catch(U){if(D)throw U;B=!1,J("Browser callback unavailable; using device-code sign-in."),X=await q({version:L.version,headless:!0})}if(B){if(!(z.openBrowser??l0)(X.url))j.abort(),await X.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),X=await q({version:L.version,headless:!0})}J(`${X.url}
14
- ${X.instructions}`);let x=await X.completion;await v(Z),await G(Q),await W.set({...V,body:{type:"oauth",access:x.access,refresh:x.refresh,expires:x.expires,...x.accountId?{accountId:x.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 n0({version:L.version}),await G0(r0(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
10
+ `}},K=z,q=G[J],W=Array.isArray(q)?[...q]:[],b=W.flatMap((Y,X)=>J0(Y)===Z?[X]:[]),j=`${Z}@${$}`;if(!b.length)K=z0(K,w0(K,q===void 0?[J]:[J,W.length],q===void 0?[j]:j,Q));else{let Y=b[0],X=W[Y],B=Array.isArray(X)?[j,...X.slice(1)]:X&&typeof X==="object"?{...X,package:j}:j;if(JSON.stringify(X)!==JSON.stringify(B))K=z0(K,w0(K,[J,Y],B,Q));for(let x of b.slice(1).reverse())K=L0(K,J,x)}let V=J==="plugin"?"plugins":"plugin";if(Array.isArray(G[V])){let Y=G[V];for(let X=Y.length-1;X>=0;X--)if(J0(Y[X])===Z)K=L0(K,V,X)}return K}function Z0(z,J,Z={}){let $=Z.fs??T,{path:G,opencode:Q}=N(Z),K=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((W)=>{let b=G.join(Q,`${W}.jsonc`),j=G.join(Q,`${W}.json`),V=$.exists(b)?b:$.exists(j)?j:b,Y=$.exists(V),X=Y?$.readText(V):`${JSON.stringify({$schema:`https://opencode.ai/${W==="tui"?"tui":"config"}.json`},null,2)}
11
+ `,B=S0(X,K),x=[],F=[];for(let D of["plugin","plugins"]){if(!Array.isArray(B[D]))continue;for(let U of B[D]){let O=P0(U);if(O===null)continue;if(r1(O,V,Z)===z.packages.opencode)x.push(JSON.stringify(U));else if(J0(U)===z.packages.opencode)F.push(JSON.stringify(U))}}if(x.length>0)return{path:V,content:X,changed:!1,existingLocalEntries:x,existingNpmEntries:F};let C=y0(X,K,z.packages.opencode,z.version);return{path:V,content:C,changed:!Y||C!==X}})}async function $0(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await T0(Z.path,Z.content,{beforeRename:J})}}async function G0(z,J,Z={}){let{platform:$,env:G}=N(Z),Q=await h(Z.runner??_,$,J,["install",`npm:${z.packages.pi}@${z.version}`],G);if(Q.exitCode!==0||Q.timedOut)throw new d({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 n1(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.")}async function o1(z,J,Z){let $=[];for(let G of J){let Q=Z.get(G)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:q}=z.vault.hosts[G],W=await p(w(q),K).catch(()=>"unreadable");if(W==="vault")Q="enrolled";else if(W==="local")Q="not-enrolled"}$.push({host:G,outcome:Q})}return $}async function Q0(z,J=[],Z={}){let $=A0(J);n1(z);let G=Z.terminal??v0(),Q=await n(z,Z);H(G,`${z.displayName} setup`);for(let[D,U]of[["OpenCode",Q.opencode],["Pi",Q.pi]])H(G,`${D}: ${U.installed?`found (version ${U.version??"unknown"})`:"not found"} — ${U.directory}`);H(G,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)H(G,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let q=["opencode","pi"].filter((D)=>Q[D].installed&&!(D==="pi"&&K));if($.hosts.some((D)=>!q.includes(D)))throw Error(I0);let W=$.yes||$.dryRun&&!g(G);if(!W&&!g(G))throw Error("Setup requires a TTY or --yes.");let b=$.hosts.length?q.filter((D)=>$.hosts.includes(D)):W?q:await _0(G,q)??[],j=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(b.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(W||!g(G))throw Error(E0);let D=await f(G,[{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(D===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};j=D}if(!b.length)return H(G,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:b,dryRun:$.dryRun,mode:"local",detection:Q};let{env:V,platform:Y}=N(Z),X=Z.fence??v(Z.runner??_,{platform:Y}),B=async()=>{try{await E(X,V)}catch(D){if(D instanceof M)H(G,D.refusalText);throw D}};if(H(G,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let D=X.previewRunningHosts?await X.previewRunningHosts(V):{hosts:await X.listRunningHosts(V),uncheckedRuntimes:0},U=D.hosts;if(D.uncheckedRuntimes>0)H(G,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let O=new Set(new P(U).activeHosts.map((k)=>k.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let k of O)H(G,`${k} is running; setup will ask you to quit it.`)}catch(D){if(H(G,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),D instanceof M)H(G,D.refusalText)}else await B();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 x=$.claustrum||$.enrollOnly;if(!x&&!$.login&&!$.noClaustrum&&!W&&Q.claustrum.available&&g(G)){let D=await f(G,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(D===null)return H(G,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};x=D===!0}let F=x?"claustrum":"local",C=!$.enrollOnly&&b.includes("opencode")?Z0(z,j,Z):[];for(let D of C){for(let O of D.existingLocalEntries??[])H(G,`OpenCode: already registered from ${O} in ${D.path}.`);let U=[...D.existingLocalEntries??[],...D.existingNpmEntries??[]];if(U.length>1)H(G,`Warning: ${z.displayName} may load twice in ${D.path}: ${U.join(", ")}. Entries were left unchanged.`)}if($.dryRun){H(G,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let D of b){if(z.beforeSignIn)H(G,`Would run beforeSignIn(${D}, ${F}).`);if(x){let U=w(z.vault.hosts[D].paths);H(G,`Would Connect ${D}: write ${U.statePath} and ${U.tokenPath}; wait for ck auth enroll approve.`)}else H(G,`Would sign in locally for ${D}.`);if(!$.enrollOnly&&z.beforeRegister)H(G,`Would run beforeRegister(${D}, ${F}).`)}for(let D of C)H(G,`${D.changed?"Would write":"Unchanged"} ${D.path}:
12
+ ${D.content}`);if(!$.enrollOnly&&b.includes("pi"))H(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let D of b)H(G,`Would migrate ${D} using the plugin callback (provider-specific writes).`)}else{let D={opencodeGeneration:j,mode:F,hosts:Object.freeze([...b]),piAgentDir:Q.pi.directory},U=new Map;try{for(let O of b){if(await B(),await z.beforeSignIn?.(O,D),await B(),x){U.set(O,"unknown");try{await k0(z,O,Z,G,B)}catch(k){if(k instanceof I)U.set(O,"not-enrolled");throw k}U.set(O,"enrolled")}else await z.signInLocal(O,D);if(await B(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,F,D),await B(),O==="opencode")await $0(C,B);else await G0(z,Q.pi.executable,Z);await B(),await z.migrate?.(O,D)}}catch(O){if(U.size===0)throw O;try{let k=await o1(z,b,U);V0(O,k);for(let y of k)H(G,W0(y))}catch{}throw O}}if(H(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${b.join(", ")} (${F}).`),$.enrollOnly)H(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),H(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else H(G,`Next: ${b.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:b,dryRun:$.dryRun,mode:F,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.10.0",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","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.39.1","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.5"},dependencies:{"@cortexkit/claustrum-client":"^0.15.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.7.0","@opentui/solid":">=0.7.0",ai:"^7.0.159","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as $2}from"node:path";import{resolveClaustrumConnectionPath as G2}from"@cortexkit/claustrum-client";var f0={name:"@cortexkit/pi-openai-auth",version:"1.10.0",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 @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","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.39.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.15.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0"},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 l}from"node:fs";import{homedir as a}from"node:os";import{join as i,resolve as g0}from"node:path";import{fileURLToPath as z2}from"node:url";var m0=new Set;function J2(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return i(a(),".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 a();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return i(a(),z.slice(2));return z.startsWith("file://")?z2(z):z}function d0(z=J2()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=i(z,K0),$=i(a(),".pi","agent",K0),G=(K)=>{let q=b0(K),W=h0(m(q),"pi");return l(K)||l(q)||l(W.tokenPath)||l(W.statePath)};if(g0(Z)===g0($)||G(Z)||!G($))return Z;let Q=`${Z}\x00${$}`;if(!m0.has(Q))m0.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 Z2(z=d0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||b0(z)}function c0(z=d0()){return{configPath:z,statePath:Z2(z)}}function n0(z={}){let J=z.print??console.log,Z=z.fence??v(),$={opencode:{stateDir:m(i0().statePath),host:"opencode"},pi:{stateDir:m(c0().statePath),host:"pi"}},G=async(Q)=>{if(await p(w($[Q]),S(Q))!=="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:L.name,pi:f0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:G2(),hosts:{opencode:{name:S("opencode"),paths:$.opencode},pi:{name:S("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let q=await p0(w($[Q]),S(Q)),W=q.state==="approved"?q.approvedName:void 0,b=W??("proposedName"in q?q.proposedName:S(Q));if(!W)J("The enrollment state does not record an approved name. The command below uses the proposed name; if the vault approved a different name, substitute it.");if(J(`Allow this host to read OpenAI accounts with:
13
+ ck auth grant --principal enrolled:${b} --selector-kind category --selector ${l0.category} --operation read`),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 G(Q)},async signInLocal(Q,K){if(await G(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let F=$2(A("opencode2",z.io)??A("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${F} 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(K.opencodeGeneration==="2")return;if(s0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let q=r0(),W={path:{id:"openai"}};if(await q.get(W)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let b=z.beginLogin??u0,j=new AbortController,V=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),Y={version:L.version,signal:j.signal},X,B=!V;try{X=await b({...Y,headless:V})}catch(F){if(V)throw F;B=!1,J("Browser callback unavailable; using device-code sign-in."),X=await b({version:L.version,headless:!0})}if(B){if(!(z.openBrowser??a0)(X.url))j.abort(),await X.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),X=await b({version:L.version,headless:!0})}J(`${X.url}
14
+ ${X.instructions}`);let x=await X.completion;await E(Z),await G(Q),await q.set({...W,body:{type:"oauth",access:x.access,refresh:x.refresh,expires:x.expires,...x.accountId?{accountId:x.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 o0({version:L.version}),await Q0(n0(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
@@ -1,6 +1,8 @@
1
1
  import { gt as QuotaMap } from "./sidebar-state-CrRiE9hw.js";
2
2
  import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
3
3
  import "@cortexkit/private-files";
4
+ import { Plugin } from "@opencode/plugin";
5
+ import "@opencode/plugin/promise/session";
4
6
  type OAuthCredential = {
5
7
  type: 'oauth';
6
8
  access?: string;
@@ -937,6 +939,8 @@ declare class OpenAiVault {
937
939
  */
938
940
  assertHostSlot(auth: unknown): void;
939
941
  close(): void;
942
+ /** Join the consumer's bounded drain so a restart cannot inherit a half-written lease. */
943
+ dispose(): Promise<void>;
940
944
  }
941
945
  interface ResetTargetIdentity {
942
946
  accountKey: string;
@@ -1,3 +1,3 @@
1
- import{Gb as X,Ib as V}from"./index-h3vtzckv.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)}
1
+ import{$b as X,bc as V}from"./index-3r9thx6n.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{Cf as c,rf as U,sf as E,wf as F,xf as p,yf as L}from"./index-mcy24ej8.js";import{createHash as Cz,randomUUID as y}from"node:crypto";import{chmod as zz,mkdir as Gz,open as Jz,readdir as b,rename as Kz,rmdir as Nz,stat as S,unlink as T}from"node:fs/promises";import{uptime as Qz}from"node:os";import{join as R,resolve as g}from"node:path";function x(z){return(z.now??Date.now)()-(z.uptime??Qz)()*1000-300000}function k(z,G,Q){let V=z.startedAt===void 0?G?.mtimeMs:z.startedAt;return typeof V==="number"&&Number.isFinite(V)&&V<Q}async function Vz(z,G,Q,V){if(!Q)return;await V?.(z);try{let J=await L(z),K=await S(z);if(J===G&&K.dev===Q.dev&&K.ino===Q.ino&&K.mtimeMs===Q.mtimeMs&&K.size===Q.size)await T(z).catch(()=>{})}catch(J){if(J instanceof E&&J.code!=="ENOENT")throw J}}function a(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function u(z){if(!a(z))return!1;try{return process.kill(z,0),!0}catch(G){return G.code==="EPERM"}}function Uz(z){return(G)=>Wz(G,z)}function Wz(z,G){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(G)&&/^[0-9a-f]{16}$/.test(z.slice(G.length))}function Xz(z){let G=/^port-(\d+)\.json$/.exec(z);return G?Number(G[1]):void 0}function s(z,G){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:Q,port:V,token:J}=z;return a(Q)&&Xz(G)===Q&&typeof V==="number"&&Number.isInteger(V)&&V>=1&&V<=65535&&typeof J==="string"&&J.length>0}async function l(z,G){G?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await T(z).catch(()=>{})}async function Ez(z,G,Q={}){let V=async()=>{let J=R(z,`port-${G.pid}.json`);if(U)return await p(z,Q.secureDir??!1),await Q.beforeWrite?.(),await c(J,JSON.stringify({...G,startedAt:Date.now()}),{stagePath:`${J}.${(Q.stageName??y)()}.tmp`}),J;if(await Gz(z,{recursive:!0,mode:Q.secureDir?448:void 0}),Q.secureDir)await zz(z,448);await Q.beforeWrite?.();let K={...G,startedAt:Date.now()},Y=`${J}.${(Q.stageName??y)()}.tmp`,W,N=!1;try{W=await Jz(Y,"wx",384),N=!0,await W.writeFile(JSON.stringify(K),"utf8"),await W.chmod(384),await W.close(),W=void 0,await Kz(Y,J),N=!1}finally{if(await W?.close().catch(()=>{}),N)await T(Y).catch(()=>{})}return J};try{return await V()}catch(J){if(J.code==="ENOENT")return await V();throw J}}async function Lz(z,G,Q,V,J={}){let K=x(J),Y;try{Y=await b(z,{withFileTypes:!0})}catch(N){if(N.code==="ENOENT")return;throw N}let W=g(G);for(let N of Y){if(!N.isDirectory()||!Q(N.name))continue;let X=R(z,N.name),Z;try{Z=await b(X)}catch($){if($.code==="ENOENT")continue;throw $}for(let $ of Z){if(!$.startsWith("port-")||!$.endsWith(".json"))continue;let H=R(X,$),C=await S(H).catch(()=>{return}),q;try{q=await L(H)}catch(O){if(O instanceof E&&O.code!=="ENOENT")throw O;continue}if(q===void 0)continue;let A;try{A=JSON.parse(q)}catch{await l(H,V);continue}if(!s(A,$)){await l(H,V);continue}let I=A;if(!u(I.pid))await T(H).catch(()=>{});else if(k(I,C,K))await Vz(H,q,C,J.beforeRemove)}if(g(X)!==W)await Nz(X).catch(()=>{})}}async function d(z,G,Q={}){let V=x(Q);if(!u(G.pid))return null;let J=R(g(z),`port-${G.pid}.json`);try{if(U)await F(J,"file");let K=await S(J);if(k(G,K,V))return null;return`${J}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch(K){if(K instanceof E&&K.code!=="ENOENT")throw K;return null}}async function n(z,G,Q={}){let V=x(Q),J;try{if(U)await F(z,"directory");J=await b(z)}catch(X){if(X instanceof E&&X.code!=="ENOENT")throw X;return null}let K=[];for(let X of J){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;try{let Z=JSON.parse(await L(R(z,X)));if(s(Z,X))if(u(Z.pid)){let $=Z.startedAt===void 0?await S(R(z,X)).catch(()=>{return}):void 0;if(!k(Z,$,V))K.push(Z)}else await T(R(z,X)).catch(()=>{})}catch(Z){if(Z instanceof E&&Z.code!=="ENOENT")throw Z}}if(K.length===0)return null;let Y=G!==void 0&&G>=1?K.filter((X)=>X.pid===G):[];if(Q.exactPid===!0&&Y.length===0)return null;let W=Y.length>0?Y:K,N=(X)=>typeof X.startedAt==="number"&&Number.isFinite(X.startedAt)?X.startedAt:-1/0;return W.sort((X,Z)=>N(Z)-N(X))[0]??null}import{open as Yz}from"node:fs/promises";import{connect as Zz}from"node:net";import{join as $z,resolve as t}from"node:path";var e=2000,_=new Map,B=new Map;async function Hz(z,G){let Q=$z(t(z),`port-${G.pid}.json`);if(U){let J=JSON.parse(await L(Q));if(J.pid!==G.pid||J.port!==G.port||J.token!==G.token)return null;return null}let V;try{V=await Yz(Q,"r");let J=await V.stat(),K=JSON.parse(await V.readFile("utf8"));if(K.pid!==G.pid||K.port!==G.port||K.token!==G.token)return null;return`${Q}:${J.dev}:${J.ino}:${J.mtimeMs}:${J.size}`}catch{return null}finally{await V?.close().catch(()=>{})}}async function i(z,G,Q,V){let J=_.get(z);if(!U&&J&&await d(G,J.entry)===J.identity)return J;_.delete(z);let K=B.get(z);if(K)return K;let Y=(async()=>{let W=await(V.discover??n)(G,Q,V);if(!W)return null;let N=await Hz(G,W);if(!N)return{entry:W,identity:""};let X={entry:W,identity:N};return _.set(z,X),X})();B.set(z,Y);try{return await Y}finally{if(B.get(z)===Y)B.delete(z)}}async function o(z,G,Q,V=e){return new Promise((J)=>{let K,Y=!1,W=!1,N=(Z,$=!1)=>{if(Y)return;Y=!0,clearTimeout(X),K?.destroy(),J({value:Z,stale:$})},X=setTimeout(()=>N(null),V);try{let Z=JSON.stringify(Q);K=Zz({host:"127.0.0.1",port:z.port}),K.on("connect",()=>{W=!0,K?.write(`POST /rpc/${G} HTTP/1.0\r
1
+ import{Pf as U,Qf as E,Uf as F,Vf as p,Wf as L,_f as c}from"./index-95z5dpe1.js";import{createHash as Cz,randomUUID as y}from"node:crypto";import{chmod as zz,mkdir as Gz,open as Jz,readdir as b,rename as Kz,rmdir as Nz,stat as S,unlink as T}from"node:fs/promises";import{uptime as Qz}from"node:os";import{join as R,resolve as g}from"node:path";function x(z){return(z.now??Date.now)()-(z.uptime??Qz)()*1000-300000}function k(z,G,Q){let V=z.startedAt===void 0?G?.mtimeMs:z.startedAt;return typeof V==="number"&&Number.isFinite(V)&&V<Q}async function Vz(z,G,Q,V){if(!Q)return;await V?.(z);try{let J=await L(z),K=await S(z);if(J===G&&K.dev===Q.dev&&K.ino===Q.ino&&K.mtimeMs===Q.mtimeMs&&K.size===Q.size)await T(z).catch(()=>{})}catch(J){if(J instanceof E&&J.code!=="ENOENT")throw J}}function a(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function u(z){if(!a(z))return!1;try{return process.kill(z,0),!0}catch(G){return G.code==="EPERM"}}function Uz(z){return(G)=>Wz(G,z)}function Wz(z,G){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(G)&&/^[0-9a-f]{16}$/.test(z.slice(G.length))}function Xz(z){let G=/^port-(\d+)\.json$/.exec(z);return G?Number(G[1]):void 0}function s(z,G){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:Q,port:V,token:J}=z;return a(Q)&&Xz(G)===Q&&typeof V==="number"&&Number.isInteger(V)&&V>=1&&V<=65535&&typeof J==="string"&&J.length>0}async function l(z,G){G?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await T(z).catch(()=>{})}async function Ez(z,G,Q={}){let V=async()=>{let J=R(z,`port-${G.pid}.json`);if(U)return await p(z,Q.secureDir??!1),await Q.beforeWrite?.(),await c(J,JSON.stringify({...G,startedAt:Date.now()}),{stagePath:`${J}.${(Q.stageName??y)()}.tmp`}),J;if(await Gz(z,{recursive:!0,mode:Q.secureDir?448:void 0}),Q.secureDir)await zz(z,448);await Q.beforeWrite?.();let K={...G,startedAt:Date.now()},Y=`${J}.${(Q.stageName??y)()}.tmp`,W,N=!1;try{W=await Jz(Y,"wx",384),N=!0,await W.writeFile(JSON.stringify(K),"utf8"),await W.chmod(384),await W.close(),W=void 0,await Kz(Y,J),N=!1}finally{if(await W?.close().catch(()=>{}),N)await T(Y).catch(()=>{})}return J};try{return await V()}catch(J){if(J.code==="ENOENT")return await V();throw J}}async function Lz(z,G,Q,V,J={}){let K=x(J),Y;try{Y=await b(z,{withFileTypes:!0})}catch(N){if(N.code==="ENOENT")return;throw N}let W=g(G);for(let N of Y){if(!N.isDirectory()||!Q(N.name))continue;let X=R(z,N.name),Z;try{Z=await b(X)}catch($){if($.code==="ENOENT")continue;throw $}for(let $ of Z){if(!$.startsWith("port-")||!$.endsWith(".json"))continue;let H=R(X,$),C=await S(H).catch(()=>{return}),q;try{q=await L(H)}catch(O){if(O instanceof E&&O.code!=="ENOENT")throw O;continue}if(q===void 0)continue;let A;try{A=JSON.parse(q)}catch{await l(H,V);continue}if(!s(A,$)){await l(H,V);continue}let I=A;if(!u(I.pid))await T(H).catch(()=>{});else if(k(I,C,K))await Vz(H,q,C,J.beforeRemove)}if(g(X)!==W)await Nz(X).catch(()=>{})}}async function d(z,G,Q={}){let V=x(Q);if(!u(G.pid))return null;let J=R(g(z),`port-${G.pid}.json`);try{if(U)await F(J,"file");let K=await S(J);if(k(G,K,V))return null;return`${J}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch(K){if(K instanceof E&&K.code!=="ENOENT")throw K;return null}}async function n(z,G,Q={}){let V=x(Q),J;try{if(U)await F(z,"directory");J=await b(z)}catch(X){if(X instanceof E&&X.code!=="ENOENT")throw X;return null}let K=[];for(let X of J){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;try{let Z=JSON.parse(await L(R(z,X)));if(s(Z,X))if(u(Z.pid)){let $=Z.startedAt===void 0?await S(R(z,X)).catch(()=>{return}):void 0;if(!k(Z,$,V))K.push(Z)}else await T(R(z,X)).catch(()=>{})}catch(Z){if(Z instanceof E&&Z.code!=="ENOENT")throw Z}}if(K.length===0)return null;let Y=G!==void 0&&G>=1?K.filter((X)=>X.pid===G):[];if(Q.exactPid===!0&&Y.length===0)return null;let W=Y.length>0?Y:K,N=(X)=>typeof X.startedAt==="number"&&Number.isFinite(X.startedAt)?X.startedAt:-1/0;return W.sort((X,Z)=>N(Z)-N(X))[0]??null}import{open as Yz}from"node:fs/promises";import{connect as Zz}from"node:net";import{join as $z,resolve as t}from"node:path";var e=2000,_=new Map,B=new Map;async function Hz(z,G){let Q=$z(t(z),`port-${G.pid}.json`);if(U){let J=JSON.parse(await L(Q));if(J.pid!==G.pid||J.port!==G.port||J.token!==G.token)return null;return null}let V;try{V=await Yz(Q,"r");let J=await V.stat(),K=JSON.parse(await V.readFile("utf8"));if(K.pid!==G.pid||K.port!==G.port||K.token!==G.token)return null;return`${Q}:${J.dev}:${J.ino}:${J.mtimeMs}:${J.size}`}catch{return null}finally{await V?.close().catch(()=>{})}}async function i(z,G,Q,V){let J=_.get(z);if(!U&&J&&await d(G,J.entry)===J.identity)return J;_.delete(z);let K=B.get(z);if(K)return K;let Y=(async()=>{let W=await(V.discover??n)(G,Q,V);if(!W)return null;let N=await Hz(G,W);if(!N)return{entry:W,identity:""};let X={entry:W,identity:N};return _.set(z,X),X})();B.set(z,Y);try{return await Y}finally{if(B.get(z)===Y)B.delete(z)}}async function o(z,G,Q,V=e){return new Promise((J)=>{let K,Y=!1,W=!1,N=(Z,$=!1)=>{if(Y)return;Y=!0,clearTimeout(X),K?.destroy(),J({value:Z,stale:$})},X=setTimeout(()=>N(null),V);try{let Z=JSON.stringify(Q);K=Zz({host:"127.0.0.1",port:z.port}),K.on("connect",()=>{W=!0,K?.write(`POST /rpc/${G} 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
@@ -9,4 +9,4 @@ Authorization: Bearer ${z.token}\r
9
9
  \r
10
10
  `);if(D>=0)C=D+4;if((C??A.length)>16384)return N(null);if(C!==void 0){let P=A.subarray(0,D).toString("latin1").split(`\r
11
11
  `),f=/^HTTP\/1\.[01] (\d{3})(?: |$)/.exec(P[0]??"");if(!f)return N(null);let j=Number(f[1]);if(j<200||j>=300)return N(null,[401,403,404,410].includes(j));for(let w of P.slice(1)){let v=w.indexOf(":"),h=w.slice(0,v).toLowerCase(),m=w.slice(v+1).trim();if(h==="transfer-encoding")return N(null);if(h==="content-length"){if(q!==void 0||!/^\d+$/.test(m))return N(null);if(q=Number(m),!Number.isSafeInteger(q)||q>8388608)return N(null)}}A=Buffer.alloc(0)}}let M=H-(C??H);if(M>8388608)return N(null);if(q!==void 0){if(M>q)return N(null);if(M===q)I()}}),K.on("end",()=>{if(q!==void 0&&H-(C??0)!==q)return N(null);I()}),K.on("error",()=>N(null,!W)),K.on("close",()=>N(null))}catch{N(null,!W)}})}async function r(z,G,Q,V,J,K,Y=e){let W=JSON.stringify([t(z),G??null,Q.exactPid===!0]),N=await i(W,z,G,Q);if(V(N?.entry??null),!N)return null;let X=Date.now()+Y,Z=await o(N.entry,J,K,Y);if(!Z.stale)return Z.value;if(_.get(W)===N)_.delete(W);let $=await i(W,z,G,Q);if(!$||Date.now()>=X)return null;if($.entry.port===N.entry.port&&$.entry.pid===N.entry.pid&&$.entry.token===N.entry.token){if(_.get(W)===$)_.delete(W);return null}let H=await o($.entry,J,K,X-Date.now());if(H.stale&&_.get(W)===$)_.delete(W);return H.value}function jz(z,G,Q,V={}){let J={exactPid:V.exactPid,discover:V.discover},K=!1,Y=(W)=>{if(K)return;Q?.(W),K=!0};return{async pending(W,N,X){return(await r(z,G,J,Y,"pending-notifications",{lastReceivedId:W,sessionId:N},X))?.messages??[]},async apply(W,N){return await r(z,G,J,Y,"apply",{...W},N)??{text:"apply failed",knobs:{}}}}}
12
- export{Uz as _e,Ez as $e,Lz as af,n as bf,e as cf,jz as df};
12
+ export{Uz as wf,Ez as xf,Lz as yf,n as zf,e as Af,jz as Bf};
@@ -1,2 +1,2 @@
1
- import{$e as O,_e as w,af as k}from"./index-npj40h62.js";import{sf as h,yf as D}from"./index-mcy24ej8.js";import{Ef as j}from"./index-y4j7y8b8.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.9.5";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
2
- export{i as Se,n as Te,a as Ue,Bf as Ve,Hf as We,R as Xe,bf as Ye,Cf as Ze};
1
+ import{wf as w,xf as O,yf as k}from"./index-29ztc0ay.js";import{Qf as h,Wf as D}from"./index-95z5dpe1.js";import{ag as j}from"./index-dkhy2peg.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.10.0";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
2
+ export{i as of,n as pf,a as qf,Bf as rf,Hf as sf,R as tf,bf as uf,Cf as vf};