@cortexkit/opencode-openai-auth 1.8.4 → 1.8.6

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 (47) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-C78nXs79.d.ts → codex-request-By530v1D.d.ts} +2 -1
  3. package/dist/{index-k7zb6wa7.js → index-25p8t63g.js} +1 -1
  4. package/dist/{index-hvmj07f7.js → index-a8wbqm6a.js} +20 -20
  5. package/dist/{index-pg5c6by3.js → index-jh90fx7y.js} +1 -1
  6. package/dist/index-n12zjwh9.js +8 -0
  7. package/dist/{index-e7gekawr.js → index-pnvp8hvs.js} +1 -1
  8. package/dist/{index-t8248wa4.js → index-v6jcz0hz.js} +21 -21
  9. package/dist/{index-nsdjapq1.js → index-zah8t2d2.js} +1 -1
  10. package/dist/{index-1htk005d.js → index-zf649dj2.js} +1 -1
  11. package/dist/index-zne9tzy9.js +91 -0
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/rpc/port-file.js +1 -1
  15. package/dist/rpc/protocol.js +1 -1
  16. package/dist/rpc/rpc-client.js +1 -1
  17. package/dist/sidebar-state.js +1 -1
  18. package/dist/tui-preferences.js +1 -1
  19. package/dist/tui.d.ts +1 -20
  20. package/dist/v2/server.d.ts +1 -1
  21. package/dist/v2/server.js +2 -2
  22. package/package.json +2 -2
  23. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +20 -6
  24. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +25 -0
  25. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +1 -1
  26. package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +55 -5
  27. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +1 -1
  28. package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +497 -0
  29. package/src/tui-compiled/raw/shared/7c97ac0cec074ae7-format.js +208 -0
  30. package/src/tui-compiled/raw/shared/b4ad0d49429f0096-map.js +98 -0
  31. package/src/tui-compiled/raw/shared/b717cdcce3966455-projection.js +90 -0
  32. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +3 -1
  33. package/src/tui-compiled/raw/tui.tsx +233 -634
  34. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +20 -6
  35. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +25 -0
  36. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +1 -1
  37. package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +55 -5
  38. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +1 -1
  39. package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +550 -0
  40. package/src/tui-compiled/runtime/shared/7c97ac0cec074ae7-format.js +208 -0
  41. package/src/tui-compiled/runtime/shared/b4ad0d49429f0096-map.js +98 -0
  42. package/src/tui-compiled/runtime/shared/b717cdcce3966455-projection.js +90 -0
  43. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +3 -1
  44. package/src/tui-compiled/runtime/tui.js +258 -879
  45. package/dist/index-a5h82jha.js +0 -8
  46. package/dist/index-kemp2vh4.js +0 -91
  47. /package/dist/{index-hnmbhgk4.js → index-95s2mw9w.js} +0 -0
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as s0}from"./index-e7gekawr.js";import{Aa as y0,Ba as f,Ca as F,Da as E,Lb as n0,hb as a0,na as p0,oa as S,pa as g,qa as m0,zb as i0}from"./index-hvmj07f7.js";import{nd as c0,td as O0,vd as d,wd as w,xd as u0,yd as u,zd as M0}from"./index-kemp2vh4.js";import"./index-a5h82jha.js";import"./index-k7zb6wa7.js";import"./index-pg5c6by3.js";import{Ze as q0,df as Q0,ff as K0,if as l0}from"./index-1htk005d.js";import"./index-hnmbhgk4.js";import"./index-5wgxt362.js";import"./index-byz2j6hz.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(`
2
+ import{c as s0}from"./index-pnvp8hvs.js";import{Aa as y0,Ba as f,Ca as F,Da as E,Lb as n0,hb as a0,na as p0,oa as S,pa as g,qa as m0,zb as i0}from"./index-a8wbqm6a.js";import{nd as c0,td as O0,vd as d,wd as w,xd as u0,yd as u,zd as M0}from"./index-zne9tzy9.js";import"./index-n12zjwh9.js";import"./index-25p8t63g.js";import"./index-jh90fx7y.js";import{Ze as q0,df as Q0,ff as K0,if as l0}from"./index-zf649dj2.js";import"./index-95s2mw9w.js";import"./index-5wgxt362.js";import"./index-byz2j6hz.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
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:
4
4
  ${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
5
5
  `)}
@@ -9,6 +9,6 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);thi
9
9
  `:`
10
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
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.8.4",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.29.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.0"},dependencies:{"@cortexkit/claustrum-client":"^0.13.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.8.4",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.29.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.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:
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.8.6",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.31.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.0"},dependencies:{"@cortexkit/claustrum-client":"^0.13.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.8.6",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.31.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.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
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
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}
@@ -132,7 +132,8 @@ interface LockLoss {
132
132
  interface RefreshFileLock {
133
133
  readonly ownerId: string;
134
134
  assertOwned(): Promise<void>;
135
- release(): Promise<void>;
135
+ /** Abort stops release retries; the unrenewed lease is left to expire by TTL. */
136
+ release(signal?: AbortSignal): Promise<void>;
136
137
  /** Resolves once on detected loss; remains pending after an owner's release. */
137
138
  whenLost(): Promise<LockLoss>;
138
139
  hasLost(): boolean;
@@ -1,2 +1,2 @@
1
- import{Se as w,Te as O,Ue as k}from"./index-pg5c6by3.js";import{kf as h,pf as D}from"./index-hnmbhgk4.js";import{vf as j}from"./index-5wgxt362.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.8.4";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
1
+ import{Se as w,Te as O,Ue as k}from"./index-jh90fx7y.js";import{kf as h,pf as D}from"./index-95s2mw9w.js";import{vf as j}from"./index-5wgxt362.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.8.6";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
2
2
  export{i as Ke,n as Le,a as Me,Bf as Ne,Hf as Oe,R as Pe,bf as Qe,Cf as Re};