@cortexkit/opencode-openai-auth 1.6.1 → 1.7.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 (42) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{codex-request-D_In8uaR.d.ts → codex-request-CN4rD2kf.d.ts} +2 -832
  3. package/dist/{index-z8bptbrk.js → index-0p3cbtwq.js} +2 -2
  4. package/dist/{index-1qxz4s8a.js → index-2e2kqmsy.js} +2 -2
  5. package/dist/{index-b0ty9qam.js → index-7zy4vdd3.js} +2 -2
  6. package/dist/{index-ge60xry3.js → index-apkavdvq.js} +2 -2
  7. package/dist/{index-rf0ht3gc.js → index-b5459de4.js} +2 -2
  8. package/dist/{index-8xq099qf.js → index-dr93b3g6.js} +2 -2
  9. package/dist/{index-jkpg9d1p.js → index-g08eptzm.js} +1 -1
  10. package/dist/{index-ya9c5e4m.js → index-jaqm1xda.js} +1 -1
  11. package/dist/{index-79y7w9bz.js → index-p9vnmnzr.js} +1 -1
  12. package/dist/index-qg2syg0r.js +65 -0
  13. package/dist/{index-x9nffaye.js → index-r4avvxf0.js} +1 -1
  14. package/dist/{index-k5anexvs.js → index-se9ykks8.js} +2 -2
  15. package/dist/{index-7nmdsmpp.js → index-yayz83vv.js} +2 -2
  16. package/dist/index.d.ts +4 -79
  17. package/dist/index.js +1 -1
  18. package/dist/{model-D22uj0OB.d.ts → protocol-BeeDdtpa.d.ts} +24 -66
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.d.ts +1 -1
  21. package/dist/rpc/protocol.js +1 -1
  22. package/dist/rpc/rpc-client.d.ts +2 -12
  23. package/dist/rpc/rpc-client.js +1 -1
  24. package/dist/rpc/rpc-dir.js +1 -1
  25. package/dist/rpc-client-DlR9a0_7.d.ts +13 -0
  26. package/dist/{sidebar-state-Bb9L9oPq.d.ts → sidebar-state-DHsZ9axt.d.ts} +1 -3
  27. package/dist/sidebar-state.d.ts +2 -2
  28. package/dist/sidebar-state.js +1 -1
  29. package/dist/{token-xtq3457d.js → token-511npvw8.js} +1 -1
  30. package/dist/token-util-jsw1zdc6.js +1 -0
  31. package/dist/tui-preferences.js +1 -1
  32. package/dist/tui.d.ts +11 -2
  33. package/dist/v2/server.d.ts +2 -2
  34. package/dist/v2/server.js +2 -2
  35. package/package.json +1 -1
  36. package/src/tui-compiled/raw/tui/v2.tsx +88 -6
  37. package/src/tui-compiled/raw/tui.tsx +45 -3
  38. package/src/tui-compiled/runtime/tui/v2.js +66 -5
  39. package/src/tui-compiled/runtime/tui.js +32 -3
  40. package/dist/index-cv6aqcvk.js +0 -65
  41. package/dist/protocol-CK9guiFy.d.ts +0 -29
  42. package/dist/token-util-nyvn9866.js +0 -1
package/dist/bin.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{c as f1}from"./index-79y7w9bz.js";import{Db as E1,Ga as N1,Ha as E,Ia as Y,Ja as v,lb as v1,ua as S1,va as f,wa as e}from"./index-k5anexvs.js";import{dd as y1,jd as j1,ld as h,md as L,od as d,pd as D1}from"./index-ge60xry3.js";import"./index-8xq099qf.js";import{Le as b1,Re as w1,Se as I1,Ve as P1}from"./index-b0ty9qam.js";import"./index-7nmdsmpp.js";import"./index-ya9c5e4m.js";import{spawn as h1}from"node:child_process";var N=4096,d1=1048576;class G1{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=N){if(G.length>N||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-N),this.start=0,this.length=N;return}let b=Math.max(0,this.length+G.length-N);if(b>0)this.truncated=!0;this.start=(this.start+b)%N,this.length-=b;let z=(this.start+this.length)%N,Z=Math.min(G.length,N-z);if(G.copy(this.buffer,z,0,Z),Z<G.length)G.copy(this.buffer,0,Z);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),b=Math.min(this.length,N-this.start);if(this.buffer.copy(G,0,this.start,this.start+b),b<this.length)this.buffer.copy(G,b,0,this.length-b);let z=0;while(z<G.length){let Z=G[z];if(Z===void 0||(Z&192)!==128)break;z++}return G.subarray(z).toString("utf8")}}var I={run(G,b,z={}){return new Promise((Z)=>{let J=performance.now(),$=z.timeoutMs??15000,K=new G1,W=[],j=0,Q=!1,D=!1,U=!1,V;try{V=h1(G,[...b],{env:z.env??process.env,windowsHide:!0,windowsVerbatimArguments:z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-J});return}let x=$>0?setTimeout(()=>{U=!0,V.kill("SIGTERM")},$):void 0;V.stdout?.on("data",(F)=>{let k=d1-j,q=Math.min(k,F.length);if(q>0)W.push(F.subarray(0,q)),j+=q;if(F.length>k)Q=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(F)=>K.push(F));let X=!1,B=(F,k)=>{if(X)return;if(X=!0,x)clearTimeout(x);Z({exitCode:D?1:Q?1:F??1,stdout:Buffer.concat(W,j).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...D?{spawnError:!0}:{},signal:k??null,timedOut:U,durationMs:performance.now()-J})};V.once("error",()=>{if(D=!0,V.pid===void 0)B(null,null)}),V.once("close",(F,k)=>B(F,k))})}};function g(G,b,z,Z,J,$=15000){if(b==="win32"&&/\.(cmd|bat)$/i.test(z)){if(/["%!\r\n]/.test(z)||Z.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${z}" ${Z.join(" ")}"`],{env:J,timeoutMs:$,windowsVerbatimArguments:!0})}return G.run(z,Z,{env:J,timeoutMs:$})}var c1="Pi install failed; run pi install after checking your npm connection.";function u1(G){let b=Buffer.from(G,"utf8");if(b.length<=N)return G;let z=b.length-N;while(z<b.length){let Z=b[z];if(Z===void 0||(Z&192)!==128)break;z++}return b.subarray(z).toString("utf8")}function p1(G){let b=G.indexOf(`
3
- `);return b<0?"":G.slice(b+1)}class m extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(c1);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let b=G.stderrTruncated?p1(G.stderrTail):G.stderrTail,z=b1(b);this.stderrTail=u1(typeof z==="string"?z:"")}}var l1={opencode:"OpenCode",pi:"Pi"},a1={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function z1({host:G,outcome:b}){return`${l1[G]}: ${a1[b]}`}var i1=new WeakMap;function J1(G,b){if(typeof G!=="object"&&typeof G!=="function"||!G)return;i1.set(G,Object.freeze(b.map((z)=>Object.freeze({...z}))))}import{accessSync as t1,constants as e1,existsSync as G0,readFileSync as b0,realpathSync as z0,statSync as J0}from"node:fs";import{mkdtemp as Z0,rm as $0}from"node:fs/promises";import{tmpdir as Q0}from"node:os";import{join as K0}from"node:path";import{parse as q0}from"jsonc-parser";import{homedir as s1}from"node:os";import{posix as r1,win32 as n1}from"node:path";import{fileURLToPath as o1}from"node:url";function R(G={}){let b=G.env??process.env,z=G.platform??process.platform,Z=z==="win32"?n1:r1,J=G.home??(z==="win32"?b.USERPROFILE:b.HOME)??s1(),$=G.cwd??process.cwd(),K=(D)=>Z.resolve($,D),W=b.OPENCODE_CONFIG_DIR?.trim(),j=b.XDG_CONFIG_HOME?.trim(),Q=b.PI_CODING_AGENT_DIR?.trim()||Z.join(J,".pi","agent");if(Q==="~")Q=J;else if(/^~[/\\]/.test(Q))Q=Z.join(J,Q.slice(2));if(Q.startsWith("file://"))Q=o1(Q);return{env:b,platform:z,path:Z,home:J,cwd:$,opencode:W?K(W):j?Z.join(K(j),"opencode"):Z.join(J,".config","opencode"),pi:K(Q)}}function c(G,b){try{return J0(G)[b]()}catch{return!1}}var _={exists:G0,isFile:(G)=>c(G,"isFile"),isDirectory:(G)=>c(G,"isDirectory"),isExecutable(G){try{return t1(G,e1.X_OK),c(G,"isFile")}catch{return!1}},readText:(G)=>b0(G,"utf8"),realpath:z0};function w(G,b={}){let{env:z,platform:Z,path:J,cwd:$}=R(b),K=b.fs??_,W=Object.entries(z).find(([Q])=>Z==="win32"?Q.toUpperCase()==="PATH":Q==="PATH")?.[1]??"",j=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let Q of W.split(Z==="win32"?";":":")){let D=Q.trim().replace(/^"|"$/g,"");if(!D)continue;for(let U of j){let V=J.resolve($,D,G+U);if(Z==="win32"?K.isFile(V):K.isExecutable(V))return V}}return null}function Z1(G={}){let{platform:b,home:z,env:Z,path:J}=R(G);if(b==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",J.join(z,"Applications","OpenCode.app"),J.join(z,"Applications","OpenCode Beta.app")];if(b==="win32"){let $=Z.LOCALAPPDATA||J.join(z,"AppData","Local");return[J.join($,"Programs","opencode"),J.join($,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",J.join(z,".local","share","applications","opencode.desktop")]}function u(G,b){let z=b.fs??_,{path:Z}=R(b);try{let J=z.readText(G);if(J.length>65536)return G;let $=[...J.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!$.length)$.push(...J.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=$.at(-1)?.[1];if(K){let W=Z.join(Z.dirname(G),...K.split(/[/\\]+/));if(z.isFile(W))return z.realpath(W)}return z.realpath(G)}catch{return G}}function x0(G,b){let z=b.fs??_,{path:Z}=R(b),J=Z.dirname(u(G,b));for(;;){try{let K=JSON.parse(z.readText(Z.join(J,"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 $=Z.dirname(J);if($===J)return null;J=$}}function $1(G={}){let b=w("opencode",G),z=w("opencode2",G),Z=b&&z&&u(b,G)===u(z,G),J=G.fs??_,{path:$,opencode:K}=R(G),W="1";for(let Q of["jsonc","json"]){let D=$.join(K,`opencode.${Q}`);if(!J.exists(D))continue;try{if(Object.hasOwn(q0(J.readText(D))??{},"plugins"))W="2"}catch{}break}let j=b?x0(b,G)??(Z?"2":W):null;if(z&&j==="1"&&!Z)return"ambiguous";return z||Z?"2":j??W}async function p(G,b={}){let z=b.fs??_,{env:Z,platform:J,opencode:$,pi:K}=R(b),W=b.runner??I,j=w("opencode",b)??w("opencode2",b),Q=w("pi",b),D=w("ck",b),U=async(B)=>{if(!B)return null;let F;try{F=await Z0(K0(Q0(),"common-auth-setup-version-"));let k={...Z,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},q=await g(W,J,B,["--version"],k,2000);return q.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(q.stdout)?.[0]??null:null}catch{return null}finally{if(F)await $0(F,{recursive:!0,force:!0}).catch(()=>{})}},V=!1;if(D&&z.exists(G.vault.connectionFile))try{(await(b.connect??h)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),V=!0}catch{V=!1}let[x,X]=await Promise.all([U(j),U(Q)]);return{opencode:{installed:z.isDirectory($)||Z1(b).some((B)=>z.exists(B))||j!==null,executable:j,version:x,directory:$,generation:$1(b)},pi:{installed:Q!==null||z.isDirectory(K),executable:Q,version:X,directory:K},claustrum:{available:V,executable:D}}}import{setTimeout as Y0}from"node:timers/promises";import{writeEnrollmentTokenFile as B0}from"@cortexkit/claustrum-client";var Q1=45000,l=new Set(["opencode","litecode","opencode2","pi"]),q1=new Set(["node","bun"]),U0=[...l,...q1].map((G)=>`Name LIKE '${G}%'`).join(" OR "),W0=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${U0}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,X0=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function j0(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((b)=>b[1]??b[2]??"")}function K1(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var D0=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"]),V0=new Set(["-e","--eval","-p","--print"]);function F0(G,b){for(let z=0;z<b.length;z++){let Z=b[z]??"";if(Z==="--")return b[z+1];if(V0.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&D0.has(Z))z++;continue}if(G==="bun"&&Z==="run")continue;return Z}return}function x1(G){let[b,...z]=j0(G);if(b===void 0)return null;let Z=K1(b);if(l.has(Z))return Z;if(!q1.has(Z))return null;let J=F0(Z,z);if(J===void 0)return null;let $=K1(J);if(l.has($))return $;return X0.test(J)?"pi":null}class H extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(G){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=G.step,this.exitCode=G.exitCode,this.signal=G.signal,this.timedOut=G.timedOut,this.durationMs=G.durationMs}get refusalText(){let G=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}: ${G} after ${Math.round(this.durationMs)} ms.`}}class T extends Error{activeHosts;constructor(G){let b=G.map((z)=>({pid:z.pid,command:x1(z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
2
+ import{c as g0}from"./index-p9vnmnzr.js";import{Eb as f0,Ha as R0,Ia as f,Ja as Y,Ka as E,mb as E0,va as P0,wa as S,xa as e}from"./index-se9ykks8.js";import{ed as y0,kd as j0,md as d,nd as _,od as S0,pd as h,qd as D0}from"./index-apkavdvq.js";import"./index-dr93b3g6.js";import{Me as b0,Se as w0,Te as I0,We as v0}from"./index-7zy4vdd3.js";import"./index-yayz83vv.js";import"./index-jaqm1xda.js";import{spawn as h0}from"node:child_process";var R=4096,c0=1048576;class G0{buffer=Buffer.alloc(R);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=R){if(G.length>R||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-R),this.start=0,this.length=R;return}let b=Math.max(0,this.length+G.length-R);if(b>0)this.truncated=!0;this.start=(this.start+b)%R,this.length-=b;let z=(this.start+this.length)%R,Z=Math.min(G.length,R-z);if(G.copy(this.buffer,z,0,Z),Z<G.length)G.copy(this.buffer,0,Z);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),b=Math.min(this.length,R-this.start);if(this.buffer.copy(G,0,this.start,this.start+b),b<this.length)this.buffer.copy(G,b,0,this.length-b);let z=0;while(z<G.length){let Z=G[z];if(Z===void 0||(Z&192)!==128)break;z++}return G.subarray(z).toString("utf8")}}var I={run(G,b,z={}){return new Promise((Z)=>{let J=performance.now(),$=z.timeoutMs??15000,K=new G0,x=[],W=0,Q=!1,D=!1,X=!1,V;try{V=h0(G,[...b],{env:z.env??process.env,windowsHide:!0,windowsVerbatimArguments:z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-J});return}let U=$>0?setTimeout(()=>{X=!0,V.kill("SIGTERM")},$):void 0;V.stdout?.on("data",(F)=>{let k=c0-W,q=Math.min(k,F.length);if(q>0)x.push(F.subarray(0,q)),W+=q;if(F.length>k)Q=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(F)=>K.push(F));let j=!1,B=(F,k)=>{if(j)return;if(j=!0,U)clearTimeout(U);Z({exitCode:D?1:Q?1:F??1,stdout:Buffer.concat(x,W).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...D?{spawnError:!0}:{},signal:k??null,timedOut:X,durationMs:performance.now()-J})};V.once("error",()=>{if(D=!0,V.pid===void 0)B(null,null)}),V.once("close",(F,k)=>B(F,k))})}};function g(G,b,z,Z,J,$=15000){if(b==="win32"&&/\.(cmd|bat)$/i.test(z)){if(/["%!\r\n]/.test(z)||Z.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${z}" ${Z.join(" ")}"`],{env:J,timeoutMs:$,windowsVerbatimArguments:!0})}return G.run(z,Z,{env:J,timeoutMs:$})}var u0="Pi install failed; run pi install after checking your npm connection.";function p0(G){let b=Buffer.from(G,"utf8");if(b.length<=R)return G;let z=b.length-R;while(z<b.length){let Z=b[z];if(Z===void 0||(Z&192)!==128)break;z++}return b.subarray(z).toString("utf8")}function l0(G){let b=G.indexOf(`
3
+ `);return b<0?"":G.slice(b+1)}class m extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(u0);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let b=G.stderrTruncated?l0(G.stderrTail):G.stderrTail,z=b0(b);this.stderrTail=p0(typeof z==="string"?z:"")}}var a0={opencode:"OpenCode",pi:"Pi"},i0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function z0({host:G,outcome:b}){return`${a0[G]}: ${i0[b]}`}var s0=new WeakMap;function J0(G,b){if(typeof G!=="object"&&typeof G!=="function"||!G)return;s0.set(G,Object.freeze(b.map((z)=>Object.freeze({...z}))))}import{accessSync as e0,constants as G1,existsSync as b1,readFileSync as z1,realpathSync as J1,statSync as Z1}from"node:fs";import{mkdtemp as $1,rm as Q1}from"node:fs/promises";import{tmpdir as K1}from"node:os";import{join as q1}from"node:path";import{parse as x1}from"jsonc-parser";import{homedir as r0}from"node:os";import{posix as n0,win32 as o0}from"node:path";import{fileURLToPath as t0}from"node:url";function N(G={}){let b=G.env??process.env,z=G.platform??process.platform,Z=z==="win32"?o0:n0,J=G.home??(z==="win32"?b.USERPROFILE:b.HOME)??r0(),$=G.cwd??process.cwd(),K=(D)=>Z.resolve($,D),x=b.OPENCODE_CONFIG_DIR?.trim(),W=b.XDG_CONFIG_HOME?.trim(),Q=b.PI_CODING_AGENT_DIR?.trim()||Z.join(J,".pi","agent");if(Q==="~")Q=J;else if(/^~[/\\]/.test(Q))Q=Z.join(J,Q.slice(2));if(Q.startsWith("file://"))Q=t0(Q);return{env:b,platform:z,path:Z,home:J,cwd:$,opencode:x?K(x):W?Z.join(K(W),"opencode"):Z.join(J,".config","opencode"),pi:K(Q)}}function c(G,b){try{return Z1(G)[b]()}catch{return!1}}var T={exists:b1,isFile:(G)=>c(G,"isFile"),isDirectory:(G)=>c(G,"isDirectory"),isExecutable(G){try{return e0(G,G1.X_OK),c(G,"isFile")}catch{return!1}},readText:(G)=>z1(G,"utf8"),realpath:J1};function w(G,b={}){let{env:z,platform:Z,path:J,cwd:$}=N(b),K=b.fs??T,x=Object.entries(z).find(([Q])=>Z==="win32"?Q.toUpperCase()==="PATH":Q==="PATH")?.[1]??"",W=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let Q of x.split(Z==="win32"?";":":")){let D=Q.trim().replace(/^"|"$/g,"");if(!D)continue;for(let X of W){let V=J.resolve($,D,G+X);if(Z==="win32"?K.isFile(V):K.isExecutable(V))return V}}return null}function Z0(G={}){let{platform:b,home:z,env:Z,path:J}=N(G);if(b==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",J.join(z,"Applications","OpenCode.app"),J.join(z,"Applications","OpenCode Beta.app")];if(b==="win32"){let $=Z.LOCALAPPDATA||J.join(z,"AppData","Local");return[J.join($,"Programs","opencode"),J.join($,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",J.join(z,".local","share","applications","opencode.desktop")]}function u(G,b){let z=b.fs??T,{path:Z}=N(b);try{let J=z.readText(G);if(J.length>65536)return G;let $=[...J.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!$.length)$.push(...J.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=$.at(-1)?.[1];if(K){let x=Z.join(Z.dirname(G),...K.split(/[/\\]+/));if(z.isFile(x))return z.realpath(x)}return z.realpath(G)}catch{return G}}function U1(G,b){let z=b.fs??T,{path:Z}=N(b),J=Z.dirname(u(G,b));for(;;){try{let K=JSON.parse(z.readText(Z.join(J,"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 $=Z.dirname(J);if($===J)return null;J=$}}function $0(G={}){let b=w("opencode",G),z=w("opencode2",G),Z=b&&z&&u(b,G)===u(z,G),J=G.fs??T,{path:$,opencode:K}=N(G),x="1";for(let Q of["jsonc","json"]){let D=$.join(K,`opencode.${Q}`);if(!J.exists(D))continue;try{if(Object.hasOwn(x1(J.readText(D))??{},"plugins"))x="2"}catch{}break}let W=b?U1(b,G)??(Z?"2":x):null;if(z&&W==="1"&&!Z)return"ambiguous";return z||Z?"2":W??x}async function p(G,b={}){let z=b.fs??T,{env:Z,platform:J,opencode:$,pi:K}=N(b),x=b.runner??I,W=w("opencode",b)??w("opencode2",b),Q=w("pi",b),D=w("ck",b),X=async(B)=>{if(!B)return null;let F;try{F=await $1(q1(K1(),"common-auth-setup-version-"));let k={...Z,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},q=await g(x,J,B,["--version"],k,2000);return q.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(q.stdout)?.[0]??null:null}catch{return null}finally{if(F)await Q1(F,{recursive:!0,force:!0}).catch(()=>{})}},V=!1;if(D&&z.exists(G.vault.connectionFile))try{(await(b.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),V=!0}catch{V=!1}let[U,j]=await Promise.all([X(W),X(Q)]);return{opencode:{installed:z.isDirectory($)||Z0(b).some((B)=>z.exists(B))||W!==null,executable:W,version:U,directory:$,generation:$0(b)},pi:{installed:Q!==null||z.isDirectory(K),executable:Q,version:j,directory:K},claustrum:{available:V,executable:D}}}import{setTimeout as B1}from"node:timers/promises";import{writeEnrollmentTokenFile as H1}from"@cortexkit/claustrum-client";var Q0=45000,l=new Set(["opencode","litecode","opencode2","pi"]),q0=new Set(["node","bun"]),W1=[...l,...q0].map((G)=>`Name LIKE '${G}%'`).join(" OR "),X1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${W1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,j1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function D1(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((b)=>b[1]??b[2]??"")}function K0(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var V1=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"]),F1=new Set(["-e","--eval","-p","--print"]);function Y1(G,b){for(let z=0;z<b.length;z++){let Z=b[z]??"";if(Z==="--")return b[z+1];if(F1.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&V1.has(Z))z++;continue}if(G==="bun"&&Z==="run")continue;return Z}return}function x0(G){let[b,...z]=D1(G);if(b===void 0)return null;let Z=K0(b);if(l.has(Z))return Z;if(!q0.has(Z))return null;let J=Y1(Z,z);if(J===void 0)return null;let $=K0(J);if(l.has($))return $;return j1.test(J)?"pi":null}class H extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(G){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=G.step,this.exitCode=G.exitCode,this.signal=G.signal,this.timedOut=G.timedOut,this.durationMs=G.durationMs}get refusalText(){let G=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}: ${G} after ${Math.round(this.durationMs)} ms.`}}class L extends Error{activeHosts;constructor(G){let b=G.map((z)=>({pid:z.pid,command:x0(z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
4
  ${b.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=b,this.name="ProcessFenceViolationError"}}async function a(G=I,b={}){let z=(b.platform??process.platform)==="win32",Z=b.selfPid??process.pid,J={step:z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},$=async(K,W,j,Q)=>{let D=performance.now();J={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let U=await G.run(W,j,{env:b.env,timeoutMs:Q});return J={step:K,exitCode:U.exitCode,signal:U.signal??null,timedOut:U.timedOut??!1,durationMs:U.durationMs??performance.now()-D},U}finally{if(J.exitCode===null)J.durationMs=performance.now()-D;b.onStep?.({...J})}};try{if(z&&b.hostImagesOnly){let Q=await $("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",W0],Q1);if(Q.exitCode!==0)throw new H(J);let D=JSON.parse(Q.stdout);if(!D||typeof D!=="object"||!("complete"in D)||D.complete!==!0||!("processes"in D))throw new H(J);let U=D.processes,V=U===null?[]:Array.isArray(U)?U:[U],x=[];for(let X of V){if(!X||typeof X!=="object"||!("Name"in X)||typeof X.Name!=="string"||!("ProcessId"in X)||!Number.isSafeInteger(X.ProcessId)||X.ProcessId<0||!("CommandLine"in X))throw new H(J);let B=X.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(X.Name))x.push({pid:B,command:X.Name});else if(typeof X.CommandLine==="string")x.push({pid:B,command:X.CommandLine});else if(B!==Z)throw new H(J)}return x}let K=await $(z?"tasklist":"ps",z?"tasklist.exe":"ps",z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new H(J);let W=[];for(let Q of K.stdout.split(/\r?\n/)){let D=Q.trim();if(!D)continue;let U,V;if(z){let x=/^"([^"]+)","(\d+)"(?:,|$)/.exec(D);if(!x)throw new H(J);V=x[1]??"",U=Number(x[2])}else{let x=/^(\d+)\s+(.+)$/.exec(D);if(!x){if(/^PID\s+COMMAND$/i.test(D))continue;throw new H(J)}U=Number(x[1]),V=x[2]??""}if(!Number.isSafeInteger(U)||U<0)throw new H(J);W.push({pid:U,command:V})}if(!W.length)throw new H(J);let j=W.filter((Q)=>Q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(Q.command));if(z&&j.length&&b.inspectRuntimes!==!1){let Q=await $("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`],Q1);if(Q.exitCode!==0)throw new H(J);let D=JSON.parse(Q.stdout||"null"),U=D===null?[]:Array.isArray(D)?D:[D],V=new Map;for(let x of U){if(!x||typeof x!=="object"||!("ProcessId"in x)||!("CommandLine"in x)||!Number.isSafeInteger(x.ProcessId))throw new H(J);if(typeof x.CommandLine==="string")V.set(Number(x.ProcessId),x.CommandLine);else if(j.some((X)=>X.pid===x.ProcessId))throw new H(J)}for(let x of j)x.command=V.get(x.pid)??""}return W}catch(K){if(K instanceof H)throw K;throw new H(J)}}function S(G=I,b={}){let z=b.selfPid??process.pid,Z=(J)=>J.pid!==z&&x1(J.command)!==null;return{async listRunningHosts(J){return(await a(G,{...b,env:J,hostImagesOnly:!0})).filter(Z)},async previewRunningHosts(J){let $=await a(G,{...b,env:J,inspectRuntimes:!1}),K=(b.platform??process.platform)==="win32";return{hosts:$.filter(Z),uncheckedRuntimes:K?$.filter((W)=>W.pid!==z&&/^(?:node|bun)\.exe$/i.test(W.command)).length:0}}}}async function P(G,b){let z=await G.listRunningHosts(b);if(z.length)throw new T(z)}var H0="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",V1='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.',F1=300000,U1=1000,W1=[1000,2000,4000,8000,16000,30000];function i(G){return G&&/^[a-z][a-z0-9_]{0,63}$/.test(G)?G:"unknown"}class A extends Error{reason;lastErrorCode;constructor(G,b){super(G);if(this.name="HostNotEnrolledError",this.reason=b.reason,b.lastErrorCode!==void 0)this.lastErrorCode=i(b.lastErrorCode)}}function X1(G,b){return`ck auth enroll approve --request-id ${G} --name ${b}`}async function Y1(G,b,z,Z,J){let{name:$,paths:K}=G.vault.hosts[b],W=L(K);await J();let j=await(z.connect??h)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new A("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),Q=z.now??(()=>performance.now()),D=z.wait??Y0;try{let U=new D1({proposedName:$,paths:W,client:j,writeTokenFile:async(q,O)=>{await J(),await B0(q,O)}});Y(Z,`Asking the vault to connect ${$}…`);let V=Q()+F1,x,X,B,F=0;for(;;){await J();let q=await U.reconcile();if(q.state==="approved"){Y(Z,`Connected ${b} to Claustrum.`);return}if(q.state==="unavailable"&&q.code===j1)throw new A(V1,{reason:"unsupported-vault",lastErrorCode:q.code});if(q.state!=="pending"&&q.state!=="busy")throw new A("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in q&&{lastErrorCode:q.code}});let O=U1;if(q.state==="busy")X="busy";else if(q.retryCode)X=q.retryCode;if(q.state==="pending"&&q.requestId){if(F=0,q.requestId!==x){if(!/^[a-zA-Z0-9_-]+$/.test(q.requestId))throw new A("Invalid enrollment request id.",{reason:"invalid-request"});x=q.requestId,Y(Z,"Waiting for approval. In another terminal, run:"),Y(Z,` ${X1(q.requestId,$)}`),Y(Z,`Enrollment files: ${W.statePath}, ${W.tokenPath}`)}}else if(q.state==="pending"&&q.retryCode){O=W1[Math.min(F,W1.length-1)]??U1,F++;let C=i(q.retryCode);if(C!==B)B=C,Y(Z,`The vault has not created the request yet (${C}); retrying.`)}let M=V-Q();if(M<=0)break;await D(Math.min(O,M))}if(x)throw new A(`Claustrum approval is still pending. In another terminal, run: ${X1(x,$)} and then rerun setup.`,{reason:"approval-pending",...X!==void 0&&{lastErrorCode:X}});let k=i(X);throw new A(`The vault never created the enrollment request (last error: ${k}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:k})}catch(U){if(U instanceof T||U instanceof H||U instanceof A)throw U;let V=U?.code;throw new A(H0,{reason:"incomplete",...typeof V==="string"&&{lastErrorCode:V}})}finally{j.close()}}async function B1(G,b){let z=new Set(b);for(;;){let Z=await v(G,[...["opencode","pi"].map((J)=>({value:J,label:`[${z.has(J)?"x":" "}] ${J==="opencode"?"OpenCode":"Pi"}`,hint:b.includes(J)?"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(Z===null)return null;if(Z==="done")return[...z];if(z.has(Z))z.delete(Z);else z.add(Z)}}import{applyEdits as s,createScanner as T0,findNodeAtLocation as L0,modify as O1,parse as y0,parseTree as S0}from"jsonc-parser";import{randomUUID as O0}from"node:crypto";import{mkdir as M0,open as k0,rename as C0,stat as N0,unlink as R0}from"node:fs/promises";import{basename as A0,dirname as w0,join as I0}from"node:path";import{setTimeout as _0}from"node:timers/promises";async function H1(G,b,z={}){let Z=(z.platform??process.platform)==="win32",J=w0(G);await M0(J,{recursive:!0});let $;if(!Z)try{$=(await N0(G)).mode&4095}catch(j){if(j.code!=="ENOENT")throw j}let K=I0(J,`.${A0(G)}.${(z.stageName??O0)()}.tmp`),W=!1;try{let j=await k0(K,"wx",$??438);W=!0;try{if(await j.writeFile(b,"utf8"),$!==void 0)await j.chmod($)}finally{await j.close()}let Q=z.now??(()=>performance.now()),D=Q();for(let U=0;;U++){await z.beforeRename?.();try{await(z.rename??C0)(K,G),W=!1;return}catch(V){let x=V.code,X=2000-(Q()-D);if(!Z||!["EPERM","EBUSY","EACCES"].includes(x??"")||X<=0||U>=40)throw Error(`Unable to replace host config ${G}. Close editors or other programs using the file, then rerun setup.`);await(z.wait??_0)(Math.min(X,25*2**Math.min(U,2)))}}}finally{if(W)await R0(K).catch(()=>{})}}function M1(G){let b=typeof G==="string"?G:Array.isArray(G)?G[0]:G&&typeof G==="object"&&("package"in G)?G.package:null;if(typeof b!=="string")return null;let z=b.indexOf("@",b.startsWith("@")?1:0);return z<0?b:b.slice(0,z)}function k1(G,b,z){let Z=S0(G),J=Z&&L0(Z,[b]),$=J?.children??[],K=$[z];if(!K||!J)throw Error("Invalid plugin array edit.");let W=[{offset:K.offset,length:K.length,content:""}],j=(Q,D)=>{let U=T0(G.slice(Q,D),!0);if(U.scan(),G[Q+U.getTokenOffset()]===",")W.push({offset:Q+U.getTokenOffset(),length:1,content:""})};if(z===$.length-1){let Q=$[z-1];if(Q)j(Q.offset+Q.length,K.offset);j(K.offset+K.length,J.offset+J.length-1)}else j(K.offset+K.length,$[z+1]?.offset??K.offset+K.length);return s(G,W)}function C1(G,b,z,Z){let J=[],$=y0(G,J,{allowTrailingComma:!0});if(J.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");let K={formattingOptions:{insertSpaces:!/^\t+/m.test(G),tabSize:/^([ ]+)"/m.exec(G)?.[1]?.length??2,eol:G.includes(`\r
7
+ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=b,this.name="ProcessFenceViolationError"}}async function a(G=I,b={}){let z=(b.platform??process.platform)==="win32",Z=b.selfPid??process.pid,J={step:z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},$=async(K,x,W,Q)=>{let D=performance.now();J={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let X=await G.run(x,W,{env:b.env,timeoutMs:Q});return J={step:K,exitCode:X.exitCode,signal:X.signal??null,timedOut:X.timedOut??!1,durationMs:X.durationMs??performance.now()-D},X}finally{if(J.exitCode===null)J.durationMs=performance.now()-D;b.onStep?.({...J})}};try{if(z&&b.hostImagesOnly){let Q=await $("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",X1],Q0);if(Q.exitCode!==0)throw new H(J);let D=JSON.parse(Q.stdout);if(!D||typeof D!=="object"||!("complete"in D)||D.complete!==!0||!("processes"in D))throw new H(J);let X=D.processes,V=X===null?[]:Array.isArray(X)?X:[X],U=[];for(let j of V){if(!j||typeof j!=="object"||!("Name"in j)||typeof j.Name!=="string"||!("ProcessId"in j)||!Number.isSafeInteger(j.ProcessId)||j.ProcessId<0||!("CommandLine"in j))throw new H(J);let B=j.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(j.Name))U.push({pid:B,command:j.Name});else if(typeof j.CommandLine==="string")U.push({pid:B,command:j.CommandLine});else if(B!==Z)throw new H(J)}return U}let K=await $(z?"tasklist":"ps",z?"tasklist.exe":"ps",z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new H(J);let x=[];for(let Q of K.stdout.split(/\r?\n/)){let D=Q.trim();if(!D)continue;let X,V;if(z){let U=/^"([^"]+)","(\d+)"(?:,|$)/.exec(D);if(!U)throw new H(J);V=U[1]??"",X=Number(U[2])}else{let U=/^(\d+)\s+(.+)$/.exec(D);if(!U){if(/^PID\s+COMMAND$/i.test(D))continue;throw new H(J)}X=Number(U[1]),V=U[2]??""}if(!Number.isSafeInteger(X)||X<0)throw new H(J);x.push({pid:X,command:V})}if(!x.length)throw new H(J);let W=x.filter((Q)=>Q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(Q.command));if(z&&W.length&&b.inspectRuntimes!==!1){let Q=await $("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`],Q0);if(Q.exitCode!==0)throw new H(J);let D=JSON.parse(Q.stdout||"null"),X=D===null?[]:Array.isArray(D)?D:[D],V=new Map;for(let U of X){if(!U||typeof U!=="object"||!("ProcessId"in U)||!("CommandLine"in U)||!Number.isSafeInteger(U.ProcessId))throw new H(J);if(typeof U.CommandLine==="string")V.set(Number(U.ProcessId),U.CommandLine);else if(W.some((j)=>j.pid===U.ProcessId))throw new H(J)}for(let U of W)U.command=V.get(U.pid)??""}return x}catch(K){if(K instanceof H)throw K;throw new H(J)}}function P(G=I,b={}){let z=b.selfPid??process.pid,Z=(J)=>J.pid!==z&&x0(J.command)!==null;return{async listRunningHosts(J){return(await a(G,{...b,env:J,hostImagesOnly:!0})).filter(Z)},async previewRunningHosts(J){let $=await a(G,{...b,env:J,inspectRuntimes:!1}),K=(b.platform??process.platform)==="win32";return{hosts:$.filter(Z),uncheckedRuntimes:K?$.filter((x)=>x.pid!==z&&/^(?:node|bun)\.exe$/i.test(x.command)).length:0}}}}async function v(G,b){let z=await G.listRunningHosts(b);if(z.length)throw new L(z)}var O1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",V0='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.',F0=300000,U0=1000,W0=[1000,2000,4000,8000,16000,30000];function i(G){return G&&/^[a-z][a-z0-9_]{0,63}$/.test(G)?G:"unknown"}class A extends Error{reason;lastErrorCode;constructor(G,b){super(G);if(this.name="HostNotEnrolledError",this.reason=b.reason,b.lastErrorCode!==void 0)this.lastErrorCode=i(b.lastErrorCode)}}function X0(G,b){return`ck auth enroll approve --request-id ${G} --name ${b}`}async function Y0(G,b,z,Z,J){let{name:$,paths:K}=G.vault.hosts[b],x=_(K);await J();let W=await(z.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new A("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),Q=z.now??(()=>performance.now()),D=z.wait??B1;try{let X=new D0({proposedName:$,paths:x,client:W,writeTokenFile:async(q,O)=>{await J(),await H1(q,O)}});Y(Z,`Asking the vault to connect ${$}…`);let V=Q()+F0,U,j,B,F=0;for(;;){await J();let q=await X.reconcile();if(q.state==="approved"){Y(Z,`Connected ${b} to Claustrum.`);return}if(q.state==="unavailable"&&q.code===j0)throw new A(V0,{reason:"unsupported-vault",lastErrorCode:q.code});if(q.state!=="pending"&&q.state!=="busy")throw new A("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in q&&{lastErrorCode:q.code}});let O=U0;if(q.state==="busy")j="busy";else if(q.retryCode)j=q.retryCode;if(q.state==="pending"&&q.requestId){if(F=0,q.requestId!==U){if(!/^[a-zA-Z0-9_-]+$/.test(q.requestId))throw new A("Invalid enrollment request id.",{reason:"invalid-request"});U=q.requestId,Y(Z,"Waiting for approval. In another terminal, run:"),Y(Z,` ${X0(q.requestId,$)}`),Y(Z,`Enrollment files: ${x.statePath}, ${x.tokenPath}`)}}else if(q.state==="pending"&&q.retryCode){O=W0[Math.min(F,W0.length-1)]??U0,F++;let C=i(q.retryCode);if(C!==B)B=C,Y(Z,`The vault has not created the request yet (${C}); retrying.`)}let M=V-Q();if(M<=0)break;await D(Math.min(O,M))}if(U)throw new A(`Claustrum approval is still pending. In another terminal, run: ${X0(U,$)} and then rerun setup.`,{reason:"approval-pending",...j!==void 0&&{lastErrorCode:j}});let k=i(j);throw new A(`The vault never created the enrollment request (last error: ${k}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:k})}catch(X){if(X instanceof L||X instanceof H||X instanceof A)throw X;let V=X?.code;throw new A(O1,{reason:"incomplete",...typeof V==="string"&&{lastErrorCode:V}})}finally{W.close()}}async function B0(G,b){let z=new Set(b);for(;;){let Z=await E(G,[...["opencode","pi"].map((J)=>({value:J,label:`[${z.has(J)?"x":" "}] ${J==="opencode"?"OpenCode":"Pi"}`,hint:b.includes(J)?"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(Z===null)return null;if(Z==="done")return[...z];if(z.has(Z))z.delete(Z);else z.add(Z)}}import{applyEdits as s,createScanner as L1,findNodeAtLocation as y1,modify as O0,parse as S1,parseTree as P1}from"jsonc-parser";import{randomUUID as M1}from"node:crypto";import{mkdir as k1,open as C1,rename as R1,stat as N1,unlink as A1}from"node:fs/promises";import{basename as w1,dirname as I1,join as _1}from"node:path";import{setTimeout as T1}from"node:timers/promises";async function H0(G,b,z={}){let Z=(z.platform??process.platform)==="win32",J=I1(G);await k1(J,{recursive:!0});let $;if(!Z)try{$=(await N1(G)).mode&4095}catch(W){if(W.code!=="ENOENT")throw W}let K=_1(J,`.${w1(G)}.${(z.stageName??M1)()}.tmp`),x=!1;try{let W=await C1(K,"wx",$??438);x=!0;try{if(await W.writeFile(b,"utf8"),$!==void 0)await W.chmod($)}finally{await W.close()}let Q=z.now??(()=>performance.now()),D=Q();for(let X=0;;X++){await z.beforeRename?.();try{await(z.rename??R1)(K,G),x=!1;return}catch(V){let U=V.code,j=2000-(Q()-D);if(!Z||!["EPERM","EBUSY","EACCES"].includes(U??"")||j<=0||X>=40)throw Error(`Unable to replace host config ${G}. Close editors or other programs using the file, then rerun setup.`);await(z.wait??T1)(Math.min(j,25*2**Math.min(X,2)))}}}finally{if(x)await A1(K).catch(()=>{})}}function M0(G){let b=typeof G==="string"?G:Array.isArray(G)?G[0]:G&&typeof G==="object"&&("package"in G)?G.package:null;if(typeof b!=="string")return null;let z=b.indexOf("@",b.startsWith("@")?1:0);return z<0?b:b.slice(0,z)}function k0(G,b,z){let Z=P1(G),J=Z&&y1(Z,[b]),$=J?.children??[],K=$[z];if(!K||!J)throw Error("Invalid plugin array edit.");let x=[{offset:K.offset,length:K.length,content:""}],W=(Q,D)=>{let X=L1(G.slice(Q,D),!0);if(X.scan(),G[Q+X.getTokenOffset()]===",")x.push({offset:Q+X.getTokenOffset(),length:1,content:""})};if(z===$.length-1){let Q=$[z-1];if(Q)W(Q.offset+Q.length,K.offset);W(K.offset+K.length,J.offset+J.length-1)}else W(K.offset+K.length,$[z+1]?.offset??K.offset+K.length);return s(G,x)}function C0(G,b,z,Z){let J=[],$=S1(G,J,{allowTrailingComma:!0});if(J.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");let K={formattingOptions:{insertSpaces:!/^\t+/m.test(G),tabSize:/^([ ]+)"/m.exec(G)?.[1]?.length??2,eol:G.includes(`\r
8
8
  `)?`\r
9
9
  `:`
10
- `}},W=G,j=$[b];if(j!==void 0&&!Array.isArray(j))throw Error(`OpenCode ${b} must be an array.`);let Q=Array.isArray(j)?[...j]:[],D=Q.flatMap((x,X)=>M1(x)===z?[X]:[]),U=`${z}@${Z}`;if(!D.length)W=s(W,O1(W,j===void 0?[b]:[b,Q.length],j===void 0?[U]:U,K));else{let x=D[0],X=Q[x],B=Array.isArray(X)?[U,...X.slice(1)]:X&&typeof X==="object"?{...X,package:U}:U;if(JSON.stringify(X)!==JSON.stringify(B))W=s(W,O1(W,[b,x],B,K));for(let F of D.slice(1).reverse())W=k1(W,b,F)}let V=b==="plugin"?"plugins":"plugin";if(Array.isArray($[V])){let x=$[V];for(let X=x.length-1;X>=0;X--)if(M1(x[X])===z)W=k1(W,V,X)}return W}function r(G,b,z={}){let Z=z.fs??_,{path:J,opencode:$}=R(z),K=b==="2"?"plugins":"plugin";return(b==="2"?["opencode"]:["opencode","tui"]).map((j)=>{let Q=J.join($,`${j}.jsonc`),D=J.join($,`${j}.json`),U=Z.exists(Q)?Q:Z.exists(D)?D:Q,V=Z.exists(U),x=V?Z.readText(U):`${JSON.stringify({$schema:`https://opencode.ai/${j==="tui"?"tui":"config"}.json`},null,2)}
11
- `,X=C1(x,K,G.packages.opencode,G.version);return{path:U,content:X,changed:!V||X!==x}})}async function n(G,b){for(let z of G){if(!z.changed)continue;await b?.(),await H1(z.path,z.content,{beforeRename:b})}}async function o(G,b,z={}){let{platform:Z,env:J}=R(z),$=await g(z.runner??I,Z,b,["install",`npm:${G.packages.pi}@${G.version}`],J);if($.exitCode!==0||$.timedOut)throw new m({exitCode:$.spawnError?null:$.exitCode,signal:$.signal??null,stderrTail:$.stderr,stderrTruncated:$.stderrTruncated??!1})}var R1="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function P0(G){let b={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,opencode:void 0};for(let z of G)if(z==="--yes")b.yes=!0;else if(z==="--dry-run")b.dryRun=!0;else if(z==="--claustrum")b.claustrum=!0;else if(z==="--no-claustrum")b.noClaustrum=!0;else if(z==="--login")b.login=!0;else if(/^--opencode=(1|2|both)$/.test(z))b.opencode=z.slice(11);else throw Error(`Unknown setup argument: ${z}`);if(b.claustrum&&b.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(b.login&&b.claustrum)throw Error("--login and --claustrum cannot be used together.");return b}function v0(G){for(let b of Object.values(G.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(b))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(G.version))throw Error("Setup requires a concrete package version.");for(let b of Object.values(G.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(b.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function E0(G,b,z){let Z=[];for(let J of b){let $=z.get(J)??"not-enrolled";if($==="unknown"){let{name:K,paths:W}=G.vault.hosts[J],j=await d(L(W),K).catch(()=>"unreadable");if(j==="vault")$="enrolled";else if(j==="local")$="not-enrolled"}Z.push({host:J,outcome:$})}return Z}async function t(G,b=[],z={}){let Z=P0(b);v0(G);let J=z.terminal??N1(),$=await p(G,z);Y(J,`${G.displayName} setup`);for(let[q,O]of[["OpenCode",$.opencode],["Pi",$.pi]])Y(J,`${q}: ${O.installed?`found (version ${O.version??"unknown"})`:"not found"} — ${O.directory}`);Y(J,`Claustrum: ${$.claustrum.available?"available":"not available"}`);let K=$.pi.installed&&!$.pi.executable;if(K)Y(J,"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((q)=>$[q].installed&&!(q==="pi"&&K)),j=Z.yes||Z.dryRun&&!E(J);if(!j&&!E(J))throw Error("Setup requires a TTY or --yes.");let Q=j?W:await B1(J,W)??[],D=Z.opencode??($.opencode.generation==="ambiguous"?"1":$.opencode.generation);if(Q.includes("opencode")&&!Z.opencode&&$.opencode.generation==="ambiguous"){if(j||!E(J))throw Error(R1);let q=await v(J,[{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(q===null)return{hosts:[],dryRun:Z.dryRun,mode:"local",detection:$};D=q}if(!Q.length)return Y(J,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:Q,dryRun:Z.dryRun,mode:"local",detection:$};let{env:U,platform:V}=R(z),x=z.fence??S(z.runner??I,{platform:V}),X=async()=>{try{await P(x,U)}catch(q){if(q instanceof H)Y(J,q.refusalText);throw q}};if(Y(J,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let q=x.previewRunningHosts?await x.previewRunningHosts(U):{hosts:await x.listRunningHosts(U),uncheckedRuntimes:0},O=q.hosts;if(q.uncheckedRuntimes>0)Y(J,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let M=new Set(new T(O).activeHosts.map((C)=>C.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let C of M)Y(J,`${C} is running; setup will ask you to quit it.`)}catch(q){if(Y(J,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),q instanceof H)Y(J,q.refusalText)}else await X();if(Z.claustrum&&!$.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let B=Boolean(Z.claustrum);if(!B&&!Z.login&&!Z.noClaustrum&&!j&&$.claustrum.available&&E(J)){let q=await v(J,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(q===null)return Y(J,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:$};B=q===!0}let F=B?"claustrum":"local",k=Q.includes("opencode")?r(G,D,z):[];if(Z.dryRun){Y(J,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let q of Q){if(G.beforeSignIn)Y(J,`Would run beforeSignIn(${q}, ${F}).`);if(B){let O=L(G.vault.hosts[q].paths);Y(J,`Would Connect ${q}: write ${O.statePath} and ${O.tokenPath}; wait for ck auth enroll approve.`)}else Y(J,`Would sign in locally for ${q}.`);if(G.beforeRegister)Y(J,`Would run beforeRegister(${q}, ${F}).`)}for(let q of k)Y(J,`${q.changed?"Would write":"Unchanged"} ${q.path}:
12
- ${q.content}`);if(Q.includes("pi"))Y(J,`Would run ${$.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let q of Q)Y(J,`Would migrate ${q} using the plugin callback (provider-specific writes).`)}else{let q={opencodeGeneration:D,mode:F,hosts:Object.freeze([...Q]),piAgentDir:$.pi.directory},O=new Map;try{for(let M of Q){if(await X(),await G.beforeSignIn?.(M,q),await X(),B){O.set(M,"unknown");try{await Y1(G,M,z,J,X)}catch(C){if(C instanceof A)O.set(M,"not-enrolled");throw C}O.set(M,"enrolled")}else await G.signInLocal(M,q);if(await X(),await G.beforeRegister?.(M,F,q),await X(),M==="opencode")await n(k,X);else await o(G,$.pi.executable,z);await X(),await G.migrate(M,q)}}catch(M){if(O.size===0)throw M;try{let C=await E0(G,Q,O);J1(M,C);for(let m1 of C)Y(J,z1(m1))}catch{}throw M}}return Y(J,`${Z.dryRun?"Planned":"Configured"} ${G.displayName} for ${Q.join(", ")} (${F}).`),Y(J,`Next: ${Q.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`),{hosts:Q,dryRun:Z.dryRun,mode:F,detection:$}}import{basename as c0}from"node:path";import{resolveClaustrumConnectionPath as u0}from"@cortexkit/claustrum-client";var A1={name:"@cortexkit/pi-openai-auth",version:"1.6.1",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.26.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@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 g0}from"node:os";import{join as _1}from"node:path";function m0(){return process.env.PI_AGENT_DIR?.trim()||_1(g0(),".pi","agent")}function T1(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||_1(m0(),w1)}function h0(G=T1()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||I1(G)}function L1(G=T1()){return{configPath:G,statePath:h0(G)}}var y={name:"@cortexkit/opencode-openai-auth",version:"1.6.1",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.26.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.32"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.6.1","@opentui/solid":">=0.6.1",ai:"^7.0.143","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};function g1(G={}){let b=G.print??console.log,z=G.fence??S(),Z={opencode:{stateDir:e(v1().statePath),host:"opencode"},pi:{stateDir:e(L1().statePath),host:"pi"}},J=async($)=>{if(await d(L(Z[$]),f($))!=="local")throw Error(`${$} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:y.name,pi:A1.name},version:y.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:u0(),hosts:{opencode:{name:f("opencode"),paths:Z.opencode},pi:{name:f("pi"),paths:Z.pi}}},async beforeRegister($,K){if(K==="claustrum"){if(b(`Allow this host to read OpenAI accounts with:
13
- ck auth grant --principal enrolled:${f($)} --selector-kind category --selector ${S1.category} --operation read`),$==="opencode")b("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await J($)},async signInLocal($,K){if(await J($),$==="pi"){b("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let F=c0(w("opencode2",G.io)??w("opencode",G.io)??"opencode");b(`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(E1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let W=f1(),j={path:{id:"openai"}};if(await W.get(j)!==void 0){b("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let Q=G.beginLogin??y1,D=new AbortController,U=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),V={version:y.version,signal:D.signal},x,X=!U;try{x=await Q({...V,headless:U})}catch(F){if(U)throw F;X=!1,b("Browser callback unavailable; using device-code sign-in."),x=await Q({version:y.version,headless:!0})}if(X){if(!(G.openBrowser??P1)(x.url))D.abort(),await x.completion.catch(()=>{}),b("Browser unavailable; using device-code sign-in."),x=await Q({version:y.version,headless:!0})}b(`${x.url}
14
- ${x.instructions}`);let B=await x.completion;await P(z),await J($),await W.set({...j,body:{type:"oauth",access:B.access,refresh:B.refresh,expires:B.expires,...B.accountId?{accountId:B.accountId}:{}}}),b("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate($){b(`${$}: 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 t(g1(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}
10
+ `}},x=G,W=$[b];if(W!==void 0&&!Array.isArray(W))throw Error(`OpenCode ${b} must be an array.`);let Q=Array.isArray(W)?[...W]:[],D=Q.flatMap((U,j)=>M0(U)===z?[j]:[]),X=`${z}@${Z}`;if(!D.length)x=s(x,O0(x,W===void 0?[b]:[b,Q.length],W===void 0?[X]:X,K));else{let U=D[0],j=Q[U],B=Array.isArray(j)?[X,...j.slice(1)]:j&&typeof j==="object"?{...j,package:X}:X;if(JSON.stringify(j)!==JSON.stringify(B))x=s(x,O0(x,[b,U],B,K));for(let F of D.slice(1).reverse())x=k0(x,b,F)}let V=b==="plugin"?"plugins":"plugin";if(Array.isArray($[V])){let U=$[V];for(let j=U.length-1;j>=0;j--)if(M0(U[j])===z)x=k0(x,V,j)}return x}function r(G,b,z={}){let Z=z.fs??T,{path:J,opencode:$}=N(z),K=b==="2"?"plugins":"plugin";return(b==="2"?["opencode"]:["opencode","tui"]).map((W)=>{let Q=J.join($,`${W}.jsonc`),D=J.join($,`${W}.json`),X=Z.exists(Q)?Q:Z.exists(D)?D:Q,V=Z.exists(X),U=V?Z.readText(X):`${JSON.stringify({$schema:`https://opencode.ai/${W==="tui"?"tui":"config"}.json`},null,2)}
11
+ `,j=C0(U,K,G.packages.opencode,G.version);return{path:X,content:j,changed:!V||j!==U}})}async function n(G,b){for(let z of G){if(!z.changed)continue;await b?.(),await H0(z.path,z.content,{beforeRename:b})}}async function o(G,b,z={}){let{platform:Z,env:J}=N(z),$=await g(z.runner??I,Z,b,["install",`npm:${G.packages.pi}@${G.version}`],J);if($.exitCode!==0||$.timedOut)throw new m({exitCode:$.spawnError?null:$.exitCode,signal:$.signal??null,stderrTail:$.stderr,stderrTruncated:$.stderrTruncated??!1})}var N0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function v1(G){let b={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,opencode:void 0};for(let z of G)if(z==="--yes")b.yes=!0;else if(z==="--dry-run")b.dryRun=!0;else if(z==="--claustrum")b.claustrum=!0;else if(z==="--no-claustrum")b.noClaustrum=!0;else if(z==="--login")b.login=!0;else if(/^--opencode=(1|2|both)$/.test(z))b.opencode=z.slice(11);else throw Error(`Unknown setup argument: ${z}`);if(b.claustrum&&b.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(b.login&&b.claustrum)throw Error("--login and --claustrum cannot be used together.");return b}function E1(G){for(let b of Object.values(G.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(b))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(G.version))throw Error("Setup requires a concrete package version.");for(let b of Object.values(G.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(b.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function f1(G,b,z){let Z=[];for(let J of b){let $=z.get(J)??"not-enrolled";if($==="unknown"){let{name:K,paths:x}=G.vault.hosts[J],W=await h(_(x),K).catch(()=>"unreadable");if(W==="vault")$="enrolled";else if(W==="local")$="not-enrolled"}Z.push({host:J,outcome:$})}return Z}async function t(G,b=[],z={}){let Z=v1(b);E1(G);let J=z.terminal??R0(),$=await p(G,z);Y(J,`${G.displayName} setup`);for(let[q,O]of[["OpenCode",$.opencode],["Pi",$.pi]])Y(J,`${q}: ${O.installed?`found (version ${O.version??"unknown"})`:"not found"} — ${O.directory}`);Y(J,`Claustrum: ${$.claustrum.available?"available":"not available"}`);let K=$.pi.installed&&!$.pi.executable;if(K)Y(J,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let x=["opencode","pi"].filter((q)=>$[q].installed&&!(q==="pi"&&K)),W=Z.yes||Z.dryRun&&!f(J);if(!W&&!f(J))throw Error("Setup requires a TTY or --yes.");let Q=W?x:await B0(J,x)??[],D=Z.opencode??($.opencode.generation==="ambiguous"?"1":$.opencode.generation);if(Q.includes("opencode")&&!Z.opencode&&$.opencode.generation==="ambiguous"){if(W||!f(J))throw Error(N0);let q=await E(J,[{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(q===null)return{hosts:[],dryRun:Z.dryRun,mode:"local",detection:$};D=q}if(!Q.length)return Y(J,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:Q,dryRun:Z.dryRun,mode:"local",detection:$};let{env:X,platform:V}=N(z),U=z.fence??P(z.runner??I,{platform:V}),j=async()=>{try{await v(U,X)}catch(q){if(q instanceof H)Y(J,q.refusalText);throw q}};if(Y(J,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let q=U.previewRunningHosts?await U.previewRunningHosts(X):{hosts:await U.listRunningHosts(X),uncheckedRuntimes:0},O=q.hosts;if(q.uncheckedRuntimes>0)Y(J,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let M=new Set(new L(O).activeHosts.map((C)=>C.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let C of M)Y(J,`${C} is running; setup will ask you to quit it.`)}catch(q){if(Y(J,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),q instanceof H)Y(J,q.refusalText)}else await j();if(Z.claustrum&&!$.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let B=Boolean(Z.claustrum);if(!B&&!Z.login&&!Z.noClaustrum&&!W&&$.claustrum.available&&f(J)){let q=await E(J,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(q===null)return Y(J,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:$};B=q===!0}let F=B?"claustrum":"local",k=Q.includes("opencode")?r(G,D,z):[];if(Z.dryRun){Y(J,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let q of Q){if(G.beforeSignIn)Y(J,`Would run beforeSignIn(${q}, ${F}).`);if(B){let O=_(G.vault.hosts[q].paths);Y(J,`Would Connect ${q}: write ${O.statePath} and ${O.tokenPath}; wait for ck auth enroll approve.`)}else Y(J,`Would sign in locally for ${q}.`);if(G.beforeRegister)Y(J,`Would run beforeRegister(${q}, ${F}).`)}for(let q of k)Y(J,`${q.changed?"Would write":"Unchanged"} ${q.path}:
12
+ ${q.content}`);if(Q.includes("pi"))Y(J,`Would run ${$.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let q of Q)Y(J,`Would migrate ${q} using the plugin callback (provider-specific writes).`)}else{let q={opencodeGeneration:D,mode:F,hosts:Object.freeze([...Q]),piAgentDir:$.pi.directory},O=new Map;try{for(let M of Q){if(await j(),await G.beforeSignIn?.(M,q),await j(),B){O.set(M,"unknown");try{await Y0(G,M,z,J,j)}catch(C){if(C instanceof A)O.set(M,"not-enrolled");throw C}O.set(M,"enrolled")}else await G.signInLocal(M,q);if(await j(),await G.beforeRegister?.(M,F,q),await j(),M==="opencode")await n(k,j);else await o(G,$.pi.executable,z);await j(),await G.migrate(M,q)}}catch(M){if(O.size===0)throw M;try{let C=await f1(G,Q,O);J0(M,C);for(let d0 of C)Y(J,z0(d0))}catch{}throw M}}return Y(J,`${Z.dryRun?"Planned":"Configured"} ${G.displayName} for ${Q.join(", ")} (${F}).`),Y(J,`Next: ${Q.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`),{hosts:Q,dryRun:Z.dryRun,mode:F,detection:$}}import{basename as u1}from"node:path";import{resolveClaustrumConnectionPath as p1}from"@cortexkit/claustrum-client";var A0={name:"@cortexkit/pi-openai-auth",version:"1.7.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.26.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@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 m1}from"node:os";import{join as _0}from"node:path";function d1(){return process.env.PI_AGENT_DIR?.trim()||_0(m1(),".pi","agent")}function T0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||_0(d1(),w0)}function h1(G=T0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||I0(G)}function L0(G=T0()){return{configPath:G,statePath:h1(G)}}var y={name:"@cortexkit/opencode-openai-auth",version:"1.7.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.26.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.32"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.6.1","@opentui/solid":">=0.6.1",ai:"^7.0.143","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};function m0(G={}){let b=G.print??console.log,z=G.fence??P(),Z={opencode:{stateDir:e(E0().statePath),host:"opencode"},pi:{stateDir:e(L0().statePath),host:"pi"}},J=async($)=>{if(await h(_(Z[$]),S($))!=="local")throw Error(`${$} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:y.name,pi:A0.name},version:y.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:p1(),hosts:{opencode:{name:S("opencode"),paths:Z.opencode},pi:{name:S("pi"),paths:Z.pi}}},async beforeRegister($,K){if(K==="claustrum"){let x=await S0(_(Z[$]),S($)),W=x.state==="approved"?x.approvedName:void 0,Q=W??("proposedName"in x?x.proposedName:S($));if(!W)b("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(b(`Allow this host to read OpenAI accounts with:
13
+ ck auth grant --principal enrolled:${Q} --selector-kind category --selector ${P0.category} --operation read`),$==="opencode")b("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await J($)},async signInLocal($,K){if(await J($),$==="pi"){b("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let F=u1(w("opencode2",G.io)??w("opencode",G.io)??"opencode");b(`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(f0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let x=g0(),W={path:{id:"openai"}};if(await x.get(W)!==void 0){b("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let Q=G.beginLogin??y0,D=new AbortController,X=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),V={version:y.version,signal:D.signal},U,j=!X;try{U=await Q({...V,headless:X})}catch(F){if(X)throw F;j=!1,b("Browser callback unavailable; using device-code sign-in."),U=await Q({version:y.version,headless:!0})}if(j){if(!(G.openBrowser??v0)(U.url))D.abort(),await U.completion.catch(()=>{}),b("Browser unavailable; using device-code sign-in."),U=await Q({version:y.version,headless:!0})}b(`${U.url}
14
+ ${U.instructions}`);let B=await U.completion;await v(z),await J($),await x.set({...W,body:{type:"oauth",access:B.access,refresh:B.refresh,expires:B.expires,...B.accountId?{accountId:B.accountId}:{}}}),b("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate($){b(`${$}: 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 t(m0(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}