@cortexkit/opencode-openai-auth 1.8.2 → 1.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as u0}from"./index-7sa6ncxb.js";import{Aa as f,Ba as x,Ca as E,Kb as l0,gb as d0,na as h0,oa as S,pa as J0,yb as c0,za as T0}from"./index-ctch2vgj.js";import{md as f0,sd as Y0,ud as m,vd as w,wd as g0,xd as c,yd as B0}from"./index-b0s5cty6.js";import"./index-fyrgwfx3.js";import"./index-z36br4a0.js";import"./index-yt52fztj.js";import{Ye as $0,cf as P0,ef as S0,hf as m0}from"./index-dw6yd976.js";import"./index-g556s1mz.js";import"./index-c50p5mem.js";import"./index-hpnj460b.js";import{spawn as i0}from"node:child_process";var N=4096,s0=1048576;class Z0{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 Z0,D=[],V=0,q=!1,j=!1,W=!1,U;try{U=i0(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(()=>{W=!0,U.kill("SIGTERM")},Q):void 0;U.stdout?.on("data",(B)=>{let C=s0-V,b=Math.min(C,B.length);if(b>0)D.push(B.subarray(0,b)),V+=b;if(B.length>C)q=!0,U.kill("SIGTERM")}),U.stderr?.on("data",(B)=>K.push(B));let Y=!1,F=(B,C)=>{if(Y)return;if(Y=!0,X)clearTimeout(X);$({exitCode:j?1:q?1:B??1,stdout:Buffer.concat(D,V).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...j?{spawnError:!0}:{},signal:C??null,timedOut:W,durationMs:performance.now()-G})};U.once("error",()=>{if(j=!0,U.pid===void 0)F(null,null)}),U.once("close",(B,C)=>F(B,C))})}};function g(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 r0="Pi install failed; run pi install after checking your npm connection.";function n0(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 o0(z){let J=z.indexOf(`
2
+ import{c as u0}from"./index-0v7ar02e.js";import{Aa as f,Ba as x,Ca as E,Kb as l0,gb as d0,na as h0,oa as S,pa as J0,yb as c0,za as T0}from"./index-rw932qm9.js";import{md as f0,sd as Y0,ud as m,vd as w,wd as g0,xd as c,yd as B0}from"./index-b0s5cty6.js";import"./index-fyrgwfx3.js";import"./index-z81cged1.js";import"./index-yt52fztj.js";import{Ye as $0,cf as P0,ef as S0,hf as m0}from"./index-dw6yd976.js";import"./index-g556s1mz.js";import"./index-c50p5mem.js";import"./index-hpnj460b.js";import{spawn as i0}from"node:child_process";var N=4096,s0=1048576;class Z0{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 Z0,D=[],V=0,q=!1,j=!1,W=!1,U;try{U=i0(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(()=>{W=!0,U.kill("SIGTERM")},Q):void 0;U.stdout?.on("data",(B)=>{let C=s0-V,b=Math.min(C,B.length);if(b>0)D.push(B.subarray(0,b)),V+=b;if(B.length>C)q=!0,U.kill("SIGTERM")}),U.stderr?.on("data",(B)=>K.push(B));let Y=!1,F=(B,C)=>{if(Y)return;if(Y=!0,X)clearTimeout(X);$({exitCode:j?1:q?1:B??1,stdout:Buffer.concat(D,V).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...j?{spawnError:!0}:{},signal:C??null,timedOut:W,durationMs:performance.now()-G})};U.once("error",()=>{if(j=!0,U.pid===void 0)F(null,null)}),U.once("close",(B,C)=>F(B,C))})}};function g(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 r0="Pi install failed; run pi install after checking your npm connection.";function n0(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 o0(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(r0);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?o0(z.stderrTail):z.stderrTail,Z=$0(J);this.stderrTail=n0(typeof Z==="string"?Z:"")}}var t0={opencode:"OpenCode",pi:"Pi"},e0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function G0({host:z,outcome:J}){return`${t0[z]}: ${e0[J]}`}var z2=new WeakMap;function Q0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;z2.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as Q2,constants as K2,existsSync as b2,readFileSync as q2,realpathSync as X2,statSync as D2}from"node:fs";import{mkdtemp as W2,rm as V2}from"node:fs/promises";import{tmpdir as j2}from"node:os";import{join as U2}from"node:path";import{parse as Y2}from"jsonc-parser";import{homedir as J2}from"node:os";import{posix as Z2,win32 as $2}from"node:path";import{fileURLToPath as G2}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?$2:Z2,G=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??J2(),Q=z.cwd??process.cwd(),K=(j)=>$.resolve(Q,j),D=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=G2(q);return{env:J,platform:Z,path:$,home:G,cwd:Q,opencode:D?K(D):V?$.join(K(V),"opencode"):$.join(G,".config","opencode"),pi:K(q)}}function u(z,J){try{return D2(z)[J]()}catch{return!1}}var T={exists:b2,isFile:(z)=>u(z,"isFile"),isDirectory:(z)=>u(z,"isDirectory"),isExecutable(z){try{return Q2(z,K2.X_OK),u(z,"isFile")}catch{return!1}},readText:(z)=>q2(z,"utf8"),realpath:X2};function I(z,J={}){let{env:Z,platform:$,path:G,cwd:Q}=k(J),K=J.fs??T,D=Object.entries(Z).find(([q])=>$==="win32"?q.toUpperCase()==="PATH":q==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let q of D.split($==="win32"?";":":")){let j=q.trim().replace(/^"|"$/g,"");if(!j)continue;for(let W of V){let U=G.resolve(Q,j,z+W);if($==="win32"?K.isFile(U):K.isExecutable(U))return U}}return null}function K0(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 p(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 D=$.join($.dirname(z),...K.split(/[/\\]+/));if(Z.isFile(D))return Z.realpath(D)}return Z.realpath(z)}catch{return z}}function B2(z,J){let Z=J.fs??T,{path:$}=k(J),G=$.dirname(p(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 b0(z={}){let J=I("opencode",z),Z=I("opencode2",z),$=J&&Z&&p(J,z)===p(Z,z),G=z.fs??T,{path:Q,opencode:K}=k(z),D="1";for(let q of["jsonc","json"]){let j=Q.join(K,`opencode.${q}`);if(!G.exists(j))continue;try{if(Object.hasOwn(Y2(G.readText(j))??{},"plugins"))D="2"}catch{}break}let V=J?B2(J,z)??($?"2":D):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??D}async function l(z,J={}){let Z=J.fs??T,{env:$,platform:G,opencode:Q,pi:K}=k(J),D=J.runner??_,V=I("opencode",J)??I("opencode2",J),q=I("pi",J),j=I("ck",J),W=async(F)=>{if(!F)return null;let B;try{B=await W2(U2(j2(),"common-auth-setup-version-"));let C={...$,HOME:B,USERPROFILE:B,XDG_CONFIG_HOME:B,XDG_DATA_HOME:B,XDG_STATE_HOME:B,XDG_CACHE_HOME:B,OPENCODE_CONFIG_DIR:B,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:B},b=await g(D,G,F,["--version"],C,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(B)await V2(B,{recursive:!0,force:!0}).catch(()=>{})}},U=!1;if(j&&Z.exists(z.vault.connectionFile))try{(await(J.connect??m)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),U=!0}catch{U=!1}let[X,Y]=await Promise.all([W(V),W(q)]);return{opencode:{installed:Z.isDirectory(Q)||K0(J).some((F)=>Z.exists(F))||V!==null,executable:V,version:X,directory:Q,generation:b0(J)},pi:{installed:q!==null||Z.isDirectory(K),executable:q,version:Y,directory:K},claustrum:{available:U,executable:j}}}import{setTimeout as N2}from"node:timers/promises";import{writeEnrollmentTokenFile as k2}from"@cortexkit/claustrum-client";var q0=45000,a=new Set(["opencode","litecode","opencode2","pi"]),D0=new Set(["node","bun"]),x2=[...a,...D0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),F2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${x2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,H2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function O2(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function X0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var M2=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"]),C2=new Set(["-e","--eval","-p","--print"]);function R2(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(C2.has($))return;if($.startsWith("-")){if(!$.includes("=")&&M2.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function W0(z){let[J,...Z]=O2(z);if(J===void 0)return null;let $=X0(J);if(a.has($))return $;if(!D0.has($))return null;let G=R2($,Z);if(G===void 0)return null;let Q=X0(G);if(a.has(Q))return Q;return H2.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:W0(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,D=G[J],V=Array.isArray(D)?[...D]:[],q=V.flatMap((U,X)=>n(U)===Z?[X]:[]),j=`${Z}@${$}`;if(!q.length)K=r(K,N0(K,D===void 0?[J]:[J,V.length],D===void 0?[j]:j,Q));else{let U=q[0],X=V[U],Y=Array.isArray(X)?[j,...X.slice(1)]:X&&typeof X==="object"?{...X,package:j}:j;if(JSON.stringify(X)!==JSON.stringify(Y))K=r(K,N0(K,[J,U],Y,Q));for(let F of q.slice(1).reverse())K=k0(K,J,F)}let W=J==="plugin"?"plugins":"plugin";if(Array.isArray(G[W])){let U=G[W];for(let X=U.length-1;X>=0;X--)if(n(U[X])===Z)K=k0(K,W,X)}return K}function o(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`),W=$.exists(q)?q:$.exists(j)?j:q,U=$.exists(W),X=U?$.readText(W):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
11
11
  `,Y=I0(X,K),F=[],B=[];for(let b of["plugin","plugins"]){if(!Array.isArray(Y[b]))continue;for(let H of Y[b]){let O=A0(H);if(O===null)continue;if(p2(O,W,Z)===z.packages.opencode)F.push(JSON.stringify(H));else if(n(H)===z.packages.opencode)B.push(JSON.stringify(H))}}if(F.length>0)return{path:W,content:X,changed:!1,existingLocalEntries:F,existingNpmEntries:B};let C=_0(X,K,z.packages.opencode,z.version);return{path:W,content:C,changed:!U||C!==X}})}async function t(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await R0(Z.path,Z.content,{beforeRename:J})}}async function e(z,J,Z={}){let{platform:$,env:G}=k(Z),Q=await g(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 w0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function l2(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 a2(z,J,Z){let $=[];for(let G of J){let Q=Z.get(G)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:D}=z.vault.hosts[G],V=await c(w(D),K).catch(()=>"unreadable");if(V==="vault")Q="enrolled";else if(V==="local")Q="not-enrolled"}$.push({host:G,outcome:Q})}return $}async function z0(z,J=[],Z={}){let $=M0(J);l2(z);let G=Z.terminal??T0(),Q=await l(z,Z);x(G,`${z.displayName} setup`);for(let[b,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])x(G,`${b}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);x(G,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)x(G,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let D=["opencode","pi"].filter((b)=>Q[b].installed&&!(b==="pi"&&K));if($.hosts.some((b)=>!D.includes(b)))throw Error(O0);let V=$.yes||$.dryRun&&!f(G);if(!V&&!f(G))throw Error("Setup requires a TTY or --yes.");let q=$.hosts.length?D.filter((b)=>$.hosts.includes(b)):V?D:await C0(G,D)??[],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(w0);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 x(G,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:q,dryRun:$.dryRun,mode:"local",detection:Q};let{env:W,platform:U}=k(Z),X=Z.fence??y(Z.runner??_,{platform:U}),Y=async()=>{try{await v(X,W)}catch(b){if(b instanceof M)x(G,b.refusalText);throw b}};if(x(G,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let b=X.previewRunningHosts?await X.previewRunningHosts(W):{hosts:await X.listRunningHosts(W),uncheckedRuntimes:0},H=b.hosts;if(b.uncheckedRuntimes>0)x(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)x(G,`${R} is running; setup will ask you to quit it.`)}catch(b){if(x(G,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof M)x(G,b.refusalText)}else await Y();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 F=$.claustrum||$.enrollOnly;if(!F&&!$.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 x(G,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};F=b===!0}let B=F?"claustrum":"local",C=!$.enrollOnly&&q.includes("opencode")?o(z,j,Z):[];for(let b of C){for(let O of b.existingLocalEntries??[])x(G,`OpenCode: already registered from ${O} in ${b.path}.`);let H=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(H.length>1)x(G,`Warning: ${z.displayName} may load twice in ${b.path}: ${H.join(", ")}. Entries were left unchanged.`)}if($.dryRun){x(G,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of q){if(z.beforeSignIn)x(G,`Would run beforeSignIn(${b}, ${B}).`);if(F){let H=w(z.vault.hosts[b].paths);x(G,`Would Connect ${b}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else x(G,`Would sign in locally for ${b}.`);if(!$.enrollOnly&&z.beforeRegister)x(G,`Would run beforeRegister(${b}, ${B}).`)}for(let b of C)x(G,`${b.changed?"Would write":"Unchanged"} ${b.path}:
12
- ${b.content}`);if(!$.enrollOnly&&q.includes("pi"))x(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let b of q)x(G,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:j,mode:B,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await Y(),await z.beforeSignIn?.(O,b),await Y(),F){H.set(O,"unknown");try{await H0(z,O,Z,G,Y)}catch(R){if(R instanceof A)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await z.signInLocal(O,b);if(await Y(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,B,b),await Y(),O==="opencode")await t(C,Y);else await e(z,Q.pi.executable,Z);await Y(),await z.migrate?.(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await a2(z,q,H);Q0(O,R);for(let a0 of R)x(G,G0(a0))}catch{}throw O}}if(x(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${q.join(", ")} (${B}).`),$.enrollOnly)x(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),x(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else x(G,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:q,dryRun:$.dryRun,mode:B,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.8.2",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 t2}from"node:path";import{resolveClaustrumConnectionPath as e2}from"@cortexkit/claustrum-client";var L0={name:"@cortexkit/pi-openai-auth",version:"1.8.2",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{homedir as r2}from"node:os";import{join as y0}from"node:path";function n2(){return process.env.PI_AGENT_DIR?.trim()||y0(r2(),".pi","agent")}function v0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||y0(n2(),P0)}function o2(z=v0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||S0(z)}function E0(z=v0()){return{configPath:z,statePath:o2(z)}}function p0(z={}){let J=z.print??console.log,Z=z.fence??y(),$={opencode:{stateDir:J0(d0().statePath),host:"opencode"},pi:{stateDir:J0(E0().statePath),host:"pi"}},G=async(Q)=>{if(await c(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:L0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:e2(),hosts:{opencode:{name:S("opencode"),paths:$.opencode},pi:{name:S("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let D=await g0(w($[Q]),S(Q)),V=D.state==="approved"?D.approvedName:void 0,q=V??("proposedName"in D?D.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"))x(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let b of q)x(G,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:j,mode:B,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await Y(),await z.beforeSignIn?.(O,b),await Y(),F){H.set(O,"unknown");try{await H0(z,O,Z,G,Y)}catch(R){if(R instanceof A)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await z.signInLocal(O,b);if(await Y(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,B,b),await Y(),O==="opencode")await t(C,Y);else await e(z,Q.pi.executable,Z);await Y(),await z.migrate?.(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await a2(z,q,H);Q0(O,R);for(let a0 of R)x(G,G0(a0))}catch{}throw O}}if(x(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${q.join(", ")} (${B}).`),$.enrollOnly)x(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),x(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else x(G,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:q,dryRun:$.dryRun,mode:B,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.8.3",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","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 t2}from"node:path";import{resolveClaustrumConnectionPath as e2}from"@cortexkit/claustrum-client";var L0={name:"@cortexkit/pi-openai-auth",version:"1.8.3",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @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{homedir as r2}from"node:os";import{join as y0}from"node:path";function n2(){return process.env.PI_AGENT_DIR?.trim()||y0(r2(),".pi","agent")}function v0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||y0(n2(),P0)}function o2(z=v0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||S0(z)}function E0(z=v0()){return{configPath:z,statePath:o2(z)}}function p0(z={}){let J=z.print??console.log,Z=z.fence??y(),$={opencode:{stateDir:J0(d0().statePath),host:"opencode"},pi:{stateDir:J0(E0().statePath),host:"pi"}},G=async(Q)=>{if(await c(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:L0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:e2(),hosts:{opencode:{name:S("opencode"),paths:$.opencode},pi:{name:S("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let D=await g0(w($[Q]),S(Q)),V=D.state==="approved"?D.approvedName:void 0,q=V??("proposedName"in D?D.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 ${h0.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 B=t2(I("opencode2",z.io)??I("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${B} 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(c0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let D=u0(),V={path:{id:"openai"}};if(await D.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let q=z.beginLogin??f0,j=new AbortController,W=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),U={version:L.version,signal:j.signal},X,Y=!W;try{X=await q({...U,headless:W})}catch(B){if(W)throw B;Y=!1,J("Browser callback unavailable; using device-code sign-in."),X=await q({version:L.version,headless:!0})}if(Y){if(!(z.openBrowser??m0)(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 F=await X.completion;await v(Z),await G(Q),await D.set({...V,body:{type:"oauth",access:F.access,refresh:F.refresh,expires:F.expires,...F.accountId?{accountId:F.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 l0({version:L.version}),await z0(p0(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
@@ -1,3 +1,3 @@
1
- import{xb as X,zb as V}from"./index-ctch2vgj.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{xb as X,zb as V}from"./index-rw932qm9.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};