@cortexkit/opencode-openai-auth 1.6.2 → 1.8.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 (77) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-D_In8uaR.d.ts → codex-request-DohnbsFR.d.ts} +66 -848
  3. package/dist/index-3v868rnp.js +63 -0
  4. package/dist/{index-b0ty9qam.js → index-5d4y47h8.js} +2 -2
  5. package/dist/{index-7nmdsmpp.js → index-5dxpsa3t.js} +2 -2
  6. package/dist/{index-8xq099qf.js → index-8pk9savd.js} +6 -6
  7. package/dist/{index-jkpg9d1p.js → index-cbcka7sa.js} +1 -1
  8. package/dist/{index-79y7w9bz.js → index-cxstwq02.js} +1 -1
  9. package/dist/{index-x9nffaye.js → index-dtwgf694.js} +1 -1
  10. package/dist/index-dzaqj248.js +2 -0
  11. package/dist/index-g3d50jz0.js +74 -0
  12. package/dist/{index-1qxz4s8a.js → index-n7fxqgfb.js} +2 -2
  13. package/dist/{index-rf0ht3gc.js → index-th47aqez.js} +2 -2
  14. package/dist/index-tvban5vp.js +91 -0
  15. package/dist/{index-ya9c5e4m.js → index-x7jzcvqy.js} +1 -1
  16. package/dist/index.d.ts +6 -79
  17. package/dist/index.js +1 -1
  18. package/dist/{port-file-8ElfwDcq.d.ts → port-file-DQ7-ItDK.d.ts} +1 -1
  19. package/dist/{model-D22uj0OB.d.ts → protocol-CVQK-d3j.d.ts} +25 -67
  20. package/dist/rpc/port-file.d.ts +4 -2
  21. package/dist/rpc/port-file.js +1 -1
  22. package/dist/rpc/protocol.d.ts +1 -1
  23. package/dist/rpc/protocol.js +1 -1
  24. package/dist/rpc/rpc-client.d.ts +2 -12
  25. package/dist/rpc/rpc-client.js +1 -1
  26. package/dist/rpc/rpc-dir.js +1 -1
  27. package/dist/rpc-client-BQfIKrXI.d.ts +13 -0
  28. package/dist/{sidebar-state-Bb9L9oPq.d.ts → sidebar-state-B1cq68UB.d.ts} +5 -7
  29. package/dist/sidebar-state.d.ts +2 -2
  30. package/dist/sidebar-state.js +1 -1
  31. package/dist/{token-xtq3457d.js → token-gy442bba.js} +1 -1
  32. package/dist/token-util-rxy0p234.js +1 -0
  33. package/dist/tui-preferences.js +1 -1
  34. package/dist/tui.d.ts +11 -2
  35. package/dist/v2/server.d.ts +15 -7
  36. package/dist/v2/server.js +2 -2
  37. package/package.json +2 -2
  38. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +95 -11
  39. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +320 -35
  40. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +187 -12
  41. package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +988 -0
  42. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +4 -0
  43. package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +34 -12
  44. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +16 -6
  45. package/src/tui-compiled/raw/shared/88b7fc40900fb003-commit-interval.js +18 -0
  46. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +57 -0
  47. package/src/tui-compiled/raw/shared/a670cb7f5987bc1b-shutdown.js +42 -0
  48. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +37 -12
  49. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
  50. package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
  51. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
  52. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +37 -4
  53. package/src/tui-compiled/raw/tui/v2.tsx +88 -6
  54. package/src/tui-compiled/raw/tui.tsx +45 -3
  55. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +95 -11
  56. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +320 -35
  57. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +187 -12
  58. package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +988 -0
  59. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +4 -0
  60. package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +34 -12
  61. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +16 -6
  62. package/src/tui-compiled/runtime/shared/88b7fc40900fb003-commit-interval.js +18 -0
  63. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +57 -0
  64. package/src/tui-compiled/runtime/shared/a670cb7f5987bc1b-shutdown.js +42 -0
  65. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +37 -12
  66. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
  67. package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
  68. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
  69. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +37 -4
  70. package/src/tui-compiled/runtime/tui/v2.js +66 -5
  71. package/src/tui-compiled/runtime/tui.js +32 -3
  72. package/dist/index-ge60xry3.js +0 -90
  73. package/dist/index-k5anexvs.js +0 -69
  74. package/dist/index-xpc2hm9h.js +0 -65
  75. package/dist/index-z8bptbrk.js +0 -2
  76. package/dist/protocol-CK9guiFy.d.ts +0 -29
  77. 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 g0}from"./index-79y7w9bz.js";import{Db as f0,Ga as R0,Ha as f,Ia as Y,Ja as E,lb as E0,ua as P0,va as S,wa as e}from"./index-k5anexvs.js";import{dd as y0,jd as j0,ld as d,md as _,nd as S0,od as h,pd as D0}from"./index-ge60xry3.js";import"./index-8xq099qf.js";import{Le as b0,Re as w0,Se as I0,Ve as v0}from"./index-b0ty9qam.js";import"./index-7nmdsmpp.js";import"./index-ya9c5e4m.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 G2,existsSync as b2,readFileSync as z2,realpathSync as J2,statSync as Z2}from"node:fs";import{mkdtemp as $2,rm as Q2}from"node:fs/promises";import{tmpdir as K2}from"node:os";import{join as q2}from"node:path";import{parse as x2}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 Z2(G)[b]()}catch{return!1}}var T={exists:b2,isFile:(G)=>c(G,"isFile"),isDirectory:(G)=>c(G,"isDirectory"),isExecutable(G){try{return e0(G,G2.X_OK),c(G,"isFile")}catch{return!1}},readText:(G)=>z2(G,"utf8"),realpath:J2};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 U2(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(x2(J.readText(D))??{},"plugins"))x="2"}catch{}break}let W=b?U2(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 $2(q2(K2(),"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 Q2(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 B2}from"node:timers/promises";import{writeEnrollmentTokenFile as H2}from"@cortexkit/claustrum-client";var Q0=45000,l=new Set(["opencode","litecode","opencode2","pi"]),q0=new Set(["node","bun"]),W2=[...l,...q0].map((G)=>`Name LIKE '${G}%'`).join(" OR "),X2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${W2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,j2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function D2(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 V2=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"]),F2=new Set(["-e","--eval","-p","--print"]);function Y2(G,b){for(let z=0;z<b.length;z++){let Z=b[z]??"";if(Z==="--")return b[z+1];if(F2.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&V2.has(Z))z++;continue}if(G==="bun"&&Z==="run")continue;return Z}return}function x0(G){let[b,...z]=D2(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=Y2(Z,z);if(J===void 0)return null;let $=K0(J);if(l.has($))return $;return j2.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
- ${b.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
2
+ import{c as m0}from"./index-cxstwq02.js";import{Aa as f,Ba as B,Ca as E,Kb as u0,gb as h0,na as f0,oa as S,pa as G0,yb as d0,za as A0}from"./index-g3d50jz0.js";import{md as y0,sd as V0,ud as d,vd as w,wd as E0,xd as m,yd as U0}from"./index-tvban5vp.js";import"./index-8pk9savd.js";import"./index-dzaqj248.js";import"./index-th47aqez.js";import{Xe as J0,bf as w0,df as L0,gf as g0}from"./index-5d4y47h8.js";import"./index-5dxpsa3t.js";import"./index-dtwgf694.js";import"./index-x7jzcvqy.js";import{spawn as l0}from"node:child_process";var k=4096,a0=1048576;class z0{buffer=Buffer.alloc(k);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=k){if(G.length>k||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-k),this.start=0,this.length=k;return}let z=Math.max(0,this.length+G.length-k);if(z>0)this.truncated=!0;this.start=(this.start+z)%k,this.length-=z;let J=(this.start+this.length)%k,Z=Math.min(G.length,k-J);if(G.copy(this.buffer,J,0,Z),Z<G.length)G.copy(this.buffer,0,Z);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),z=Math.min(this.length,k-this.start);if(this.buffer.copy(G,0,this.start,this.start+z),z<this.length)this.buffer.copy(G,z,0,this.length-z);let J=0;while(J<G.length){let Z=G[J];if(Z===void 0||(Z&192)!==128)break;J++}return G.subarray(J).toString("utf8")}}var T={run(G,z,J={}){return new Promise((Z)=>{let $=performance.now(),Q=J.timeoutMs??15000,K=new z0,D=[],j=0,q=!1,x=!1,X=!1,V;try{V=l0(G,[...z],{env:J.env??process.env,windowsHide:!0,windowsVerbatimArguments:J.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-$});return}let W=Q>0?setTimeout(()=>{X=!0,V.kill("SIGTERM")},Q):void 0;V.stdout?.on("data",(Y)=>{let C=a0-j,b=Math.min(C,Y.length);if(b>0)D.push(Y.subarray(0,b)),j+=b;if(Y.length>C)q=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(Y)=>K.push(Y));let U=!1,F=(Y,C)=>{if(U)return;if(U=!0,W)clearTimeout(W);Z({exitCode:x?1:q?1:Y??1,stdout:Buffer.concat(D,j).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...x?{spawnError:!0}:{},signal:C??null,timedOut:X,durationMs:performance.now()-$})};V.once("error",()=>{if(x=!0,V.pid===void 0)F(null,null)}),V.once("close",(Y,C)=>F(Y,C))})}};function g(G,z,J,Z,$,Q=15000){if(z==="win32"&&/\.(cmd|bat)$/i.test(J)){if(/["%!\r\n]/.test(J)||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",`""${J}" ${Z.join(" ")}"`],{env:$,timeoutMs:Q,windowsVerbatimArguments:!0})}return G.run(J,Z,{env:$,timeoutMs:Q})}var i0="Pi install failed; run pi install after checking your npm connection.";function s0(G){let z=Buffer.from(G,"utf8");if(z.length<=k)return G;let J=z.length-k;while(J<z.length){let Z=z[J];if(Z===void 0||(Z&192)!==128)break;J++}return z.subarray(J).toString("utf8")}function r0(G){let z=G.indexOf(`
3
+ `);return z<0?"":G.slice(z+1)}class h extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(i0);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let z=G.stderrTruncated?r0(G.stderrTail):G.stderrTail,J=J0(z);this.stderrTail=s0(typeof J==="string"?J:"")}}var n0={opencode:"OpenCode",pi:"Pi"},o0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function Z0({host:G,outcome:z}){return`${n0[G]}: ${o0[z]}`}var t0=new WeakMap;function $0(G,z){if(typeof G!=="object"&&typeof G!=="function"||!G)return;t0.set(G,Object.freeze(z.map((J)=>Object.freeze({...J}))))}import{accessSync as Z1,constants as $1,existsSync as Q1,readFileSync as K1,realpathSync as b1,statSync as q1}from"node:fs";import{mkdtemp as W1,rm as X1}from"node:fs/promises";import{tmpdir as D1}from"node:os";import{join as j1}from"node:path";import{parse as x1}from"jsonc-parser";import{homedir as e0}from"node:os";import{posix as G1,win32 as z1}from"node:path";import{fileURLToPath as J1}from"node:url";function N(G={}){let z=G.env??process.env,J=G.platform??process.platform,Z=J==="win32"?z1:G1,$=G.home??(J==="win32"?z.USERPROFILE:z.HOME)??e0(),Q=G.cwd??process.cwd(),K=(x)=>Z.resolve(Q,x),D=z.OPENCODE_CONFIG_DIR?.trim(),j=z.XDG_CONFIG_HOME?.trim(),q=z.PI_CODING_AGENT_DIR?.trim()||Z.join($,".pi","agent");if(q==="~")q=$;else if(/^~[/\\]/.test(q))q=Z.join($,q.slice(2));if(q.startsWith("file://"))q=J1(q);return{env:z,platform:J,path:Z,home:$,cwd:Q,opencode:D?K(D):j?Z.join(K(j),"opencode"):Z.join($,".config","opencode"),pi:K(q)}}function c(G,z){try{return q1(G)[z]()}catch{return!1}}var _={exists:Q1,isFile:(G)=>c(G,"isFile"),isDirectory:(G)=>c(G,"isDirectory"),isExecutable(G){try{return Z1(G,$1.X_OK),c(G,"isFile")}catch{return!1}},readText:(G)=>K1(G,"utf8"),realpath:b1};function I(G,z={}){let{env:J,platform:Z,path:$,cwd:Q}=N(z),K=z.fs??_,D=Object.entries(J).find(([q])=>Z==="win32"?q.toUpperCase()==="PATH":q==="PATH")?.[1]??"",j=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let q of D.split(Z==="win32"?";":":")){let x=q.trim().replace(/^"|"$/g,"");if(!x)continue;for(let X of j){let V=$.resolve(Q,x,G+X);if(Z==="win32"?K.isFile(V):K.isExecutable(V))return V}}return null}function Q0(G={}){let{platform:z,home:J,env:Z,path:$}=N(G);if(z==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",$.join(J,"Applications","OpenCode.app"),$.join(J,"Applications","OpenCode Beta.app")];if(z==="win32"){let Q=Z.LOCALAPPDATA||$.join(J,"AppData","Local");return[$.join(Q,"Programs","opencode"),$.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",$.join(J,".local","share","applications","opencode.desktop")]}function u(G,z){let J=z.fs??_,{path:Z}=N(z);try{let $=J.readText(G);if($.length>65536)return G;let Q=[...$.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...$.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Q.at(-1)?.[1];if(K){let D=Z.join(Z.dirname(G),...K.split(/[/\\]+/));if(J.isFile(D))return J.realpath(D)}return J.realpath(G)}catch{return G}}function V1(G,z){let J=z.fs??_,{path:Z}=N(z),$=Z.dirname(u(G,z));for(;;){try{let K=JSON.parse(J.readText(Z.join($,"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=Z.dirname($);if(Q===$)return null;$=Q}}function K0(G={}){let z=I("opencode",G),J=I("opencode2",G),Z=z&&J&&u(z,G)===u(J,G),$=G.fs??_,{path:Q,opencode:K}=N(G),D="1";for(let q of["jsonc","json"]){let x=Q.join(K,`opencode.${q}`);if(!$.exists(x))continue;try{if(Object.hasOwn(x1($.readText(x))??{},"plugins"))D="2"}catch{}break}let j=z?V1(z,G)??(Z?"2":D):null;if(J&&j==="1"&&!Z)return"ambiguous";return J||Z?"2":j??D}async function p(G,z={}){let J=z.fs??_,{env:Z,platform:$,opencode:Q,pi:K}=N(z),D=z.runner??T,j=I("opencode",z)??I("opencode2",z),q=I("pi",z),x=I("ck",z),X=async(F)=>{if(!F)return null;let Y;try{Y=await W1(j1(D1(),"common-auth-setup-version-"));let C={...Z,HOME:Y,USERPROFILE:Y,XDG_CONFIG_HOME:Y,XDG_DATA_HOME:Y,XDG_STATE_HOME:Y,XDG_CACHE_HOME:Y,OPENCODE_CONFIG_DIR:Y,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:Y},b=await g(D,$,F,["--version"],C,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(Y)await X1(Y,{recursive:!0,force:!0}).catch(()=>{})}},V=!1;if(x&&J.exists(G.vault.connectionFile))try{(await(z.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),V=!0}catch{V=!1}let[W,U]=await Promise.all([X(j),X(q)]);return{opencode:{installed:J.isDirectory(Q)||Q0(z).some((F)=>J.exists(F))||j!==null,executable:j,version:W,directory:Q,generation:K0(z)},pi:{installed:q!==null||J.isDirectory(K),executable:q,version:U,directory:K},claustrum:{available:V,executable:x}}}import{setTimeout as C1}from"node:timers/promises";import{writeEnrollmentTokenFile as R1}from"@cortexkit/claustrum-client";var b0=45000,l=new Set(["opencode","litecode","opencode2","pi"]),W0=new Set(["node","bun"]),U1=[...l,...W0].map((G)=>`Name LIKE '${G}%'`).join(" OR "),Y1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${U1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,B1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function F1(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((z)=>z[1]??z[2]??"")}function q0(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var H1=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"]),O1=new Set(["-e","--eval","-p","--print"]);function M1(G,z){for(let J=0;J<z.length;J++){let Z=z[J]??"";if(Z==="--")return z[J+1];if(O1.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&H1.has(Z))J++;continue}if(G==="bun"&&Z==="run")continue;return Z}return}function X0(G){let[z,...J]=F1(G);if(z===void 0)return null;let Z=q0(z);if(l.has(Z))return Z;if(!W0.has(Z))return null;let $=M1(Z,J);if($===void 0)return null;let Q=q0($);if(l.has(Q))return Q;return B1.test($)?"pi":null}class M 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 P extends Error{activeHosts;constructor(G){let z=G.map((J)=>({pid:J.pid,command:X0(J.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
+ ${z.map((J)=>` - PID ${J.pid}: ${J.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,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",X2],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 O2="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??B2;try{let X=new D0({proposedName:$,paths:x,client:W,writeTokenFile:async(q,O)=>{await J(),await H2(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(O2,{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 L2,findNodeAtLocation as y2,modify as O0,parse as S2,parseTree as P2}from"jsonc-parser";import{randomUUID as M2}from"node:crypto";import{mkdir as k2,open as C2,rename as R2,stat as N2,unlink as A2}from"node:fs/promises";import{basename as w2,dirname as I2,join as _2}from"node:path";import{setTimeout as T2}from"node:timers/promises";async function H0(G,b,z={}){let Z=(z.platform??process.platform)==="win32",J=I2(G);await k2(J,{recursive:!0});let $;if(!Z)try{$=(await N2(G)).mode&4095}catch(W){if(W.code!=="ENOENT")throw W}let K=_2(J,`.${w2(G)}.${(z.stageName??M2)()}.tmp`),x=!1;try{let W=await C2(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??R2)(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??T2)(Math.min(j,25*2**Math.min(X,2)))}}}finally{if(x)await A2(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=P2(G),J=Z&&y2(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=L2(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=[],$=S2(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=z,this.name="ProcessFenceViolationError"}}async function a(G=T,z={}){let J=(z.platform??process.platform)==="win32",Z=z.selfPid??process.pid,$={step:J?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(K,D,j,q)=>{let x=performance.now();$={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let X=await G.run(D,j,{env:z.env,timeoutMs:q});return $={step:K,exitCode:X.exitCode,signal:X.signal??null,timedOut:X.timedOut??!1,durationMs:X.durationMs??performance.now()-x},X}finally{if($.exitCode===null)$.durationMs=performance.now()-x;z.onStep?.({...$})}};try{if(J&&z.hostImagesOnly){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",Y1],b0);if(q.exitCode!==0)throw new M($);let x=JSON.parse(q.stdout);if(!x||typeof x!=="object"||!("complete"in x)||x.complete!==!0||!("processes"in x))throw new M($);let X=x.processes,V=X===null?[]:Array.isArray(X)?X:[X],W=[];for(let U of V){if(!U||typeof U!=="object"||!("Name"in U)||typeof U.Name!=="string"||!("ProcessId"in U)||!Number.isSafeInteger(U.ProcessId)||U.ProcessId<0||!("CommandLine"in U))throw new M($);let F=U.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(U.Name))W.push({pid:F,command:U.Name});else if(typeof U.CommandLine==="string")W.push({pid:F,command:U.CommandLine});else if(F!==Z)throw new M($)}return W}let K=await Q(J?"tasklist":"ps",J?"tasklist.exe":"ps",J?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new M($);let D=[];for(let q of K.stdout.split(/\r?\n/)){let x=q.trim();if(!x)continue;let X,V;if(J){let W=/^"([^"]+)","(\d+)"(?:,|$)/.exec(x);if(!W)throw new M($);V=W[1]??"",X=Number(W[2])}else{let W=/^(\d+)\s+(.+)$/.exec(x);if(!W){if(/^PID\s+COMMAND$/i.test(x))continue;throw new M($)}X=Number(W[1]),V=W[2]??""}if(!Number.isSafeInteger(X)||X<0)throw new M($);D.push({pid:X,command:V})}if(!D.length)throw new M($);let j=D.filter((q)=>q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(q.command));if(J&&j.length&&z.inspectRuntimes!==!1){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],b0);if(q.exitCode!==0)throw new M($);let x=JSON.parse(q.stdout||"null"),X=x===null?[]:Array.isArray(x)?x:[x],V=new Map;for(let W of X){if(!W||typeof W!=="object"||!("ProcessId"in W)||!("CommandLine"in W)||!Number.isSafeInteger(W.ProcessId))throw new M($);if(typeof W.CommandLine==="string")V.set(Number(W.ProcessId),W.CommandLine);else if(j.some((U)=>U.pid===W.ProcessId))throw new M($)}for(let W of j)W.command=V.get(W.pid)??""}return D}catch(K){if(K instanceof M)throw K;throw new M($)}}function v(G=T,z={}){let J=z.selfPid??process.pid,Z=($)=>$.pid!==J&&X0($.command)!==null;return{async listRunningHosts($){return(await a(G,{...z,env:$,hostImagesOnly:!0})).filter(Z)},async previewRunningHosts($){let Q=await a(G,{...z,env:$,inspectRuntimes:!1}),K=(z.platform??process.platform)==="win32";return{hosts:Q.filter(Z),uncheckedRuntimes:K?Q.filter((D)=>D.pid!==J&&/^(?:node|bun)\.exe$/i.test(D.command)).length:0}}}}async function y(G,z){let J=await G.listRunningHosts(z);if(J.length)throw new P(J)}var k1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",Y0='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.',B0=300000,D0=1000,j0=[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,z){super(G);if(this.name="HostNotEnrolledError",this.reason=z.reason,z.lastErrorCode!==void 0)this.lastErrorCode=i(z.lastErrorCode)}}function x0(G,z){return`ck auth enroll approve --request-id ${G} --name ${z}`}async function F0(G,z,J,Z,$){let{name:Q,paths:K}=G.vault.hosts[z],D=w(K);await $();let j=await(J.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new A("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),q=J.now??(()=>performance.now()),x=J.wait??C1;try{let X=new U0({proposedName:Q,paths:D,client:j,writeTokenFile:async(b,H)=>{await $(),await R1(b,H)}});B(Z,`Asking the vault to connect ${Q}…`);let V=q()+B0,W,U,F,Y=0;for(;;){await $();let b=await X.reconcile();if(b.state==="approved"){B(Z,`Connected ${z} to Claustrum.`);return}if(b.state==="unavailable"&&b.code===V0)throw new A(Y0,{reason:"unsupported-vault",lastErrorCode:b.code});if(b.state!=="pending"&&b.state!=="busy")throw new A("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in b&&{lastErrorCode:b.code}});let H=D0;if(b.state==="busy")U="busy";else if(b.retryCode)U=b.retryCode;if(b.state==="pending"&&b.requestId){if(Y=0,b.requestId!==W){if(!/^[a-zA-Z0-9_-]+$/.test(b.requestId))throw new A("Invalid enrollment request id.",{reason:"invalid-request"});W=b.requestId,B(Z,"Waiting for approval. In another terminal, run:"),B(Z,` ${x0(b.requestId,Q)}`),B(Z,`Enrollment files: ${D.statePath}, ${D.tokenPath}`)}}else if(b.state==="pending"&&b.retryCode){H=j0[Math.min(Y,j0.length-1)]??D0,Y++;let R=i(b.retryCode);if(R!==F)F=R,B(Z,`The vault has not created the request yet (${R}); retrying.`)}let O=V-q();if(O<=0)break;await x(Math.min(H,O))}if(W)throw new A(`Claustrum approval is still pending. In another terminal, run: ${x0(W,Q)} and then rerun setup.`,{reason:"approval-pending",...U!==void 0&&{lastErrorCode:U}});let C=i(U);throw new A(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(X){if(X instanceof P||X instanceof M||X instanceof A)throw X;let V=X?.code;throw new A(k1,{reason:"incomplete",...typeof V==="string"&&{lastErrorCode:V}})}finally{j.close()}}async function H0(G,z){let J=new Set(z);for(;;){let Z=await E(G,[...["opencode","pi"].map(($)=>({value:$,label:`[${J.has($)?"x":" "}] ${$==="opencode"?"OpenCode":"Pi"}`,hint:z.includes($)?"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[...J];if(J.has(Z))J.delete(Z);else J.add(Z)}}import{domainToUnicode as y1}from"node:url";import{applyEdits as s,createScanner as E1,findNodeAtLocation as f1,modify as M0,parse as g1,parseTree as h1}from"jsonc-parser";import{randomUUID as N1}from"node:crypto";import{mkdir as A1,open as I1,rename as T1,stat as _1,unlink as w1}from"node:fs/promises";import{basename as L1,dirname as P1,join as S1}from"node:path";import{setTimeout as v1}from"node:timers/promises";async function O0(G,z,J={}){let Z=(J.platform??process.platform)==="win32",$=P1(G);await A1($,{recursive:!0});let Q;if(!Z)try{Q=(await _1(G)).mode&4095}catch(j){if(j.code!=="ENOENT")throw j}let K=S1($,`.${L1(G)}.${(J.stageName??N1)()}.tmp`),D=!1;try{let j=await I1(K,"wx",Q??438);D=!0;try{if(await j.writeFile(z,"utf8"),Q!==void 0)await j.chmod(Q)}finally{await j.close()}let q=J.now??(()=>performance.now()),x=q();for(let X=0;;X++){await J.beforeRename?.();try{await(J.rename??T1)(K,G),D=!1;return}catch(V){let W=V.code,U=2000-(q()-x);if(!Z||!["EPERM","EBUSY","EACCES"].includes(W??"")||U<=0||X>=40)throw Error(`Unable to replace host config ${G}. Close editors or other programs using the file, then rerun setup.`);await(J.wait??v1)(Math.min(U,25*2**Math.min(X,2)))}}}finally{if(D)await w1(K).catch(()=>{})}}function R0(G){let z=typeof G==="string"?G:Array.isArray(G)?G[0]:G&&typeof G==="object"&&("package"in G)?G.package:null;return typeof z==="string"?z:null}function r(G){let z=R0(G);if(z===null)return null;let J=z.indexOf("@",z.startsWith("@")?1:0);return J<0?z:z.slice(0,J)}function d1(G,z){let J=new URL(G);if(/%2f/i.test(J.pathname)||z&&/%5c/i.test(J.pathname))throw Error("Encoded path separators are not valid in a file URL.");let Z=decodeURIComponent(J.pathname);if(!z){if(J.hostname)throw Error("A POSIX file URL must be local.");return Z}let $=Z.replaceAll("/","\\");if(J.hostname)return`\\\\${y1(J.hostname)}${$}`;if(!/^\\[a-z]:/i.test($))throw Error("A Windows file URL must have an absolute drive path.");return $.slice(1)}function m1(G,z,J){let{path:Z,platform:$}=N(J);try{let Q=/^file:\/\//i.test(G)?d1(G,$==="win32"):Z.isAbsolute(G)||G.startsWith(".")?Z.resolve(Z.dirname(z),G):null;if(Q===null)return null;let K=JSON.parse((J.fs??_).readText(Z.join(Q,"package.json")));return K&&typeof K==="object"&&"name"in K&&typeof K.name==="string"?K.name:null}catch{return null}}function k0(G,z){let J=[],Z=g1(G,J,{allowTrailingComma:!0});if(J.length||!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid OpenCode config; refusing to overwrite it.");if(Z[z]!==void 0&&!Array.isArray(Z[z]))throw Error(`OpenCode ${z} must be an array.`);return Z}function C0(G,z,J){let Z=h1(G),$=Z&&f1(Z,[z]),Q=$?.children??[],K=Q[J];if(!K||!$)throw Error("Invalid plugin array edit.");let D=[{offset:K.offset,length:K.length,content:""}],j=(q,x)=>{let X=E1(G.slice(q,x),!0);if(X.scan(),G[q+X.getTokenOffset()]===",")D.push({offset:q+X.getTokenOffset(),length:1,content:""})};if(J===Q.length-1){let q=Q[J-1];if(q)j(q.offset+q.length,K.offset);j(K.offset+K.length,$.offset+$.length-1)}else j(K.offset+K.length,Q[J+1]?.offset??K.offset+K.length);return s(G,D)}function N0(G,z,J,Z){let $=k0(G,z),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(G),tabSize:/^([ ]+)"/m.exec(G)?.[1]?.length??2,eol:G.includes(`\r
8
8
  `)?`\r
9
9
  `:`
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 v2(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 E2(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 f2(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=v2(b);E2(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 f2(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 u2}from"node:path";import{resolveClaustrumConnectionPath as p2}from"@cortexkit/claustrum-client";var A0={name:"@cortexkit/pi-openai-auth",version:"1.6.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.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 m2}from"node:os";import{join as _0}from"node:path";function d2(){return process.env.PI_AGENT_DIR?.trim()||_0(m2(),".pi","agent")}function T0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||_0(d2(),w0)}function h2(G=T0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||I0(G)}function L0(G=T0()){return{configPath:G,statePath:h2(G)}}var y={name:"@cortexkit/opencode-openai-auth",version:"1.6.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.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:p2(),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=u2(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}
10
+ `}},K=G,D=$[z],j=Array.isArray(D)?[...D]:[],q=j.flatMap((V,W)=>r(V)===J?[W]:[]),x=`${J}@${Z}`;if(!q.length)K=s(K,M0(K,D===void 0?[z]:[z,j.length],D===void 0?[x]:x,Q));else{let V=q[0],W=j[V],U=Array.isArray(W)?[x,...W.slice(1)]:W&&typeof W==="object"?{...W,package:x}:x;if(JSON.stringify(W)!==JSON.stringify(U))K=s(K,M0(K,[z,V],U,Q));for(let F of q.slice(1).reverse())K=C0(K,z,F)}let X=z==="plugin"?"plugins":"plugin";if(Array.isArray($[X])){let V=$[X];for(let W=V.length-1;W>=0;W--)if(r(V[W])===J)K=C0(K,X,W)}return K}function n(G,z,J={}){let Z=J.fs??_,{path:$,opencode:Q}=N(J),K=z==="2"?"plugins":"plugin";return(z==="2"?["opencode"]:["opencode","tui"]).map((j)=>{let q=$.join(Q,`${j}.jsonc`),x=$.join(Q,`${j}.json`),X=Z.exists(q)?q:Z.exists(x)?x:q,V=Z.exists(X),W=V?Z.readText(X):`${JSON.stringify({$schema:`https://opencode.ai/${j==="tui"?"tui":"config"}.json`},null,2)}
11
+ `,U=k0(W,K),F=[],Y=[];for(let b of["plugin","plugins"]){if(!Array.isArray(U[b]))continue;for(let H of U[b]){let O=R0(H);if(O===null)continue;if(m1(O,X,J)===G.packages.opencode)F.push(JSON.stringify(H));else if(r(H)===G.packages.opencode)Y.push(JSON.stringify(H))}}if(F.length>0)return{path:X,content:W,changed:!1,existingLocalEntries:F,existingNpmEntries:Y};let C=N0(W,K,G.packages.opencode,G.version);return{path:X,content:C,changed:!V||C!==W}})}async function o(G,z){for(let J of G){if(!J.changed)continue;await z?.(),await O0(J.path,J.content,{beforeRename:z})}}async function t(G,z,J={}){let{platform:Z,env:$}=N(J),Q=await g(J.runner??T,Z,z,["install",`npm:${G.packages.pi}@${G.version}`],$);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 I0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.",T0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.";function c1(G){let z={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let J of G)if(J==="--yes")z.yes=!0;else if(J==="--dry-run")z.dryRun=!0;else if(J==="--claustrum")z.claustrum=!0;else if(J==="--no-claustrum")z.noClaustrum=!0;else if(J==="--login")z.login=!0;else if(J==="--enroll-only")z.enrollOnly=!0;else if(J.startsWith("--host=")){let Z=J.slice(7);if(Z!=="opencode"&&Z!=="pi")throw Error(T0);z.hosts.push(Z)}else if(/^--opencode=(1|2|both)$/.test(J))z.opencode=J.slice(11);else throw Error(`Unknown setup argument: ${J}`);if(z.claustrum&&z.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(z.login&&z.claustrum)throw Error("--login and --claustrum cannot be used together.");if(z.enrollOnly&&z.login)throw Error("--enroll-only and --login cannot be used together.");if(z.enrollOnly&&z.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return z}function u1(G){for(let z of Object.values(G.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(z))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 z of Object.values(G.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(z.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function p1(G,z,J){let Z=[];for(let $ of z){let Q=J.get($)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:D}=G.vault.hosts[$],j=await m(w(D),K).catch(()=>"unreadable");if(j==="vault")Q="enrolled";else if(j==="local")Q="not-enrolled"}Z.push({host:$,outcome:Q})}return Z}async function e(G,z=[],J={}){let Z=c1(z);u1(G);let $=J.terminal??A0(),Q=await p(G,J);B($,`${G.displayName} setup`);for(let[b,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])B($,`${b}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);B($,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)B($,"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(Z.hosts.some((b)=>!D.includes(b)))throw Error(T0);let j=Z.yes||Z.dryRun&&!f($);if(!j&&!f($))throw Error("Setup requires a TTY or --yes.");let q=Z.hosts.length?D.filter((b)=>Z.hosts.includes(b)):j?D:await H0($,D)??[],x=Z.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(q.includes("opencode")&&!Z.opencode&&Q.opencode.generation==="ambiguous"){if(j||!f($))throw Error(I0);let b=await E($,[{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:Z.dryRun,mode:"local",detection:Q};x=b}if(!q.length)return B($,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:q,dryRun:Z.dryRun,mode:"local",detection:Q};let{env:X,platform:V}=N(J),W=J.fence??v(J.runner??T,{platform:V}),U=async()=>{try{await y(W,X)}catch(b){if(b instanceof M)B($,b.refusalText);throw b}};if(B($,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let b=W.previewRunningHosts?await W.previewRunningHosts(X):{hosts:await W.listRunningHosts(X),uncheckedRuntimes:0},H=b.hosts;if(b.uncheckedRuntimes>0)B($,"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)B($,`${R} is running; setup will ask you to quit it.`)}catch(b){if(B($,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof M)B($,b.refusalText)}else await U();if((Z.claustrum||Z.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=Z.claustrum||Z.enrollOnly;if(!F&&!Z.login&&!Z.noClaustrum&&!j&&Q.claustrum.available&&f($)){let b=await E($,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(b===null)return B($,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:Q};F=b===!0}let Y=F?"claustrum":"local",C=!Z.enrollOnly&&q.includes("opencode")?n(G,x,J):[];for(let b of C){for(let O of b.existingLocalEntries??[])B($,`OpenCode: already registered from ${O} in ${b.path}.`);let H=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(H.length>1)B($,`Warning: ${G.displayName} may load twice in ${b.path}: ${H.join(", ")}. Entries were left unchanged.`)}if(Z.dryRun){B($,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of q){if(G.beforeSignIn)B($,`Would run beforeSignIn(${b}, ${Y}).`);if(F){let H=w(G.vault.hosts[b].paths);B($,`Would Connect ${b}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else B($,`Would sign in locally for ${b}.`);if(!Z.enrollOnly&&G.beforeRegister)B($,`Would run beforeRegister(${b}, ${Y}).`)}for(let b of C)B($,`${b.changed?"Would write":"Unchanged"} ${b.path}:
12
+ ${b.content}`);if(!Z.enrollOnly&&q.includes("pi"))B($,`Would run ${Q.pi.executable} install npm:${G.packages.pi}@${G.version}`);if(!Z.enrollOnly)for(let b of q)B($,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:x,mode:Y,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await U(),await G.beforeSignIn?.(O,b),await U(),F){H.set(O,"unknown");try{await F0(G,O,J,$,U)}catch(R){if(R instanceof A)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await G.signInLocal(O,b);if(await U(),Z.enrollOnly)continue;if(await G.beforeRegister?.(O,Y,b),await U(),O==="opencode")await o(C,U);else await t(G,Q.pi.executable,J);await U(),await G.migrate(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await p1(G,q,H);$0(O,R);for(let p0 of R)B($,Z0(p0))}catch{}throw O}}if(B($,`${Z.dryRun?"Planned":Z.enrollOnly?"Enrolled":"Configured"} ${G.displayName} for ${q.join(", ")} (${Y}).`),Z.enrollOnly)B($,`Enroll-only: no host config or plugin registration ${Z.dryRun?"will be":"was"} written.`),B($,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else B($,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`);return{hosts:q,dryRun:Z.dryRun,mode:Y,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.8.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.27.1","@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"}};import{basename as n1}from"node:path";import{resolveClaustrumConnectionPath as o1}from"@cortexkit/claustrum-client";var _0={name:"@cortexkit/pi-openai-auth",version:"1.8.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.27.1","@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 i1}from"node:os";import{join as P0}from"node:path";function s1(){return process.env.PI_AGENT_DIR?.trim()||P0(i1(),".pi","agent")}function S0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||P0(s1(),w0)}function r1(G=S0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||L0(G)}function v0(G=S0()){return{configPath:G,statePath:r1(G)}}function c0(G={}){let z=G.print??console.log,J=G.fence??v(),Z={opencode:{stateDir:G0(h0().statePath),host:"opencode"},pi:{stateDir:G0(v0().statePath),host:"pi"}},$=async(Q)=>{if(await m(w(Z[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:_0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:o1(),hosts:{opencode:{name:S("opencode"),paths:Z.opencode},pi:{name:S("pi"),paths:Z.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let D=await E0(w(Z[Q]),S(Q)),j=D.state==="approved"?D.approvedName:void 0,q=j??("proposedName"in D?D.proposedName:S(Q));if(!j)z("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(z(`Allow this host to read OpenAI accounts with:
13
+ ck auth grant --principal enrolled:${q} --selector-kind category --selector ${f0.category} --operation read`),Q==="opencode")z("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await $(Q)},async signInLocal(Q,K){if(await $(Q),Q==="pi"){z("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let Y=n1(I("opencode2",G.io)??I("opencode",G.io)??"opencode");z(`In OpenCode 2, run ${Y} 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(d0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let D=m0(),j={path:{id:"openai"}};if(await D.get(j)!==void 0){z("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let q=G.beginLogin??y0,x=new AbortController,X=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),V={version:L.version,signal:x.signal},W,U=!X;try{W=await q({...V,headless:X})}catch(Y){if(X)throw Y;U=!1,z("Browser callback unavailable; using device-code sign-in."),W=await q({version:L.version,headless:!0})}if(U){if(!(G.openBrowser??g0)(W.url))x.abort(),await W.completion.catch(()=>{}),z("Browser unavailable; using device-code sign-in."),W=await q({version:L.version,headless:!0})}z(`${W.url}
14
+ ${W.instructions}`);let F=await W.completion;await y(J),await $(Q),await D.set({...j,body:{type:"oauth",access:F.access,refresh:F.refresh,expires:F.expires,...F.accountId?{accountId:F.accountId}:{}}}),z("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){z(`${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 u0({version:L.version}),await e(c0(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}