@cortexkit/opencode-openai-auth 1.0.5 → 1.2.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 (104) hide show
  1. package/dist/bin.js +9 -8
  2. package/dist/{pool-lifecycle-C_6YRmsh.d.ts → codex-request-CjXETpTA.d.ts} +190 -27
  3. package/dist/index-03em8hv1.js +69 -0
  4. package/dist/index-6n4pnfkg.js +2 -0
  5. package/dist/{index-pg305s90.js → index-bc89akak.js} +1 -1
  6. package/dist/{index-y4gxyxqd.js → index-ehjj89rx.js} +2 -2
  7. package/dist/index-f21addzm.js +90 -0
  8. package/dist/{index-fsky1rsh.js → index-ffg0sgg5.js} +2 -2
  9. package/dist/{index-nx2qh047.js → index-ftkhhr6d.js} +1 -1
  10. package/dist/{index-826s1yxa.js → index-htvcmtcx.js} +2 -2
  11. package/dist/{index-fsxbncpw.js → index-qp5hdpw8.js} +1 -1
  12. package/dist/index-qxbchh2d.js +8 -0
  13. package/dist/{index-116q849r.js → index-r2s51ac1.js} +2 -2
  14. package/dist/index-rwbrhkse.js +65 -0
  15. package/dist/{index-66asrje2.js → index-xwvze96g.js} +1 -1
  16. package/dist/index.d.ts +18 -8
  17. package/dist/index.js +1 -1
  18. package/dist/{protocol-DctqemRI.d.ts → model-CQcw10oW.d.ts} +67 -25
  19. package/dist/{port-file-ZPlxXB4G.d.ts → port-file-BDJnzgHH.d.ts} +1 -1
  20. package/dist/protocol-C-kagE6O.d.ts +29 -0
  21. package/dist/rpc/port-file.d.ts +1 -1
  22. package/dist/rpc/port-file.js +1 -1
  23. package/dist/rpc/protocol.d.ts +1 -1
  24. package/dist/rpc/protocol.js +1 -1
  25. package/dist/rpc/rpc-client.d.ts +3 -3
  26. package/dist/rpc/rpc-client.js +1 -1
  27. package/dist/rpc/rpc-dir.js +1 -1
  28. package/dist/{sidebar-state-z_M7Trnd.d.ts → sidebar-state-BfQ4mpZO.d.ts} +109 -10
  29. package/dist/sidebar-state.d.ts +2 -2
  30. package/dist/sidebar-state.js +1 -1
  31. package/dist/token-util-cf0nyh7n.js +1 -0
  32. package/dist/{token-bzhkgc29.js → token-z6qq7a1d.js} +1 -1
  33. package/dist/tui-preferences.js +1 -1
  34. package/dist/tui.d.ts +20 -2
  35. package/dist/v2/server.d.ts +180 -1
  36. package/dist/v2/server.js +3 -3
  37. package/package.json +3 -3
  38. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +148 -26
  39. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +371 -0
  40. package/src/tui-compiled/raw/shared/134b008900698fe0-backoff.js +92 -0
  41. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +430 -0
  42. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
  43. package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +473 -0
  44. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +566 -0
  45. package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
  46. package/src/tui-compiled/raw/shared/4593a4d71edf69fd-tombstone.js +25 -0
  47. package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +500 -0
  48. package/src/tui-compiled/raw/shared/6371b24a0573d79e-any-signal.js +42 -0
  49. package/src/tui-compiled/raw/shared/7c140680fc81be92-interlock.js +29 -0
  50. package/src/tui-compiled/raw/shared/85512cc5263ba259-provider.js +87 -0
  51. package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +192 -0
  52. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +806 -0
  53. package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
  54. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +0 -1
  55. package/src/tui-compiled/raw/shared/ca0fccaba1d87af4-errors.js +8 -0
  56. package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +152 -0
  57. package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +1 -1
  58. package/src/tui-compiled/raw/shared/d9d2892a4c371301-host-slot.js +72 -0
  59. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +1470 -0
  60. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
  61. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +24 -0
  62. package/src/tui-compiled/raw/sidebar-state.js +103 -14
  63. package/src/tui-compiled/raw/tui/command-dialogs.tsx +3 -34
  64. package/src/tui-compiled/raw/tui/section-text.js +21 -0
  65. package/src/tui-compiled/raw/tui/v2-dialog.js +137 -0
  66. package/src/tui-compiled/raw/tui/v2.tsx +133 -0
  67. package/src/tui-compiled/raw/tui.tsx +228 -70
  68. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +148 -26
  69. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +371 -0
  70. package/src/tui-compiled/runtime/shared/134b008900698fe0-backoff.js +92 -0
  71. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +430 -0
  72. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
  73. package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +473 -0
  74. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +566 -0
  75. package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
  76. package/src/tui-compiled/runtime/shared/4593a4d71edf69fd-tombstone.js +25 -0
  77. package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +500 -0
  78. package/src/tui-compiled/runtime/shared/6371b24a0573d79e-any-signal.js +42 -0
  79. package/src/tui-compiled/runtime/shared/7c140680fc81be92-interlock.js +29 -0
  80. package/src/tui-compiled/runtime/shared/85512cc5263ba259-provider.js +87 -0
  81. package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +192 -0
  82. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +806 -0
  83. package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
  84. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +0 -1
  85. package/src/tui-compiled/runtime/shared/ca0fccaba1d87af4-errors.js +8 -0
  86. package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +152 -0
  87. package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +1 -1
  88. package/src/tui-compiled/runtime/shared/d9d2892a4c371301-host-slot.js +72 -0
  89. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +1470 -0
  90. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
  91. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +24 -0
  92. package/src/tui-compiled/runtime/sidebar-state.js +103 -14
  93. package/src/tui-compiled/runtime/tui/command-dialogs.js +3 -15
  94. package/src/tui-compiled/runtime/tui/section-text.js +21 -0
  95. package/src/tui-compiled/runtime/tui/v2-dialog.js +137 -0
  96. package/src/tui-compiled/runtime/tui/v2.js +95 -0
  97. package/src/tui-compiled/runtime/tui.js +351 -222
  98. package/dist/index-4fnghj9e.js +0 -65
  99. package/dist/index-a69gr76b.js +0 -2
  100. package/dist/index-h263aftt.js +0 -157
  101. package/dist/index-ssj7m2rd.js +0 -8
  102. package/dist/index-ydz3hbhc.js +0 -2
  103. package/dist/map-m6f5a_IA.d.ts +0 -56
  104. package/dist/token-util-4a2xxnpg.js +0 -1
package/dist/bin.js CHANGED
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{c as M1}from"./index-fsxbncpw.js";import{Ba as U1,Ga as P,Ha as N,Ia as Y1,Ja as t,bc as x1,mb as R1,nb as E,ob as a,tc as j1,wb as K1,xb as S,yb as R,zb as L}from"./index-h263aftt.js";import"./index-a69gr76b.js";import"./index-ssj7m2rd.js";import{$d as W1,Xd as $1,Yd as q1}from"./index-y4gxyxqd.js";import"./index-116q849r.js";import"./index-66asrje2.js";import{execFile as F1}from"node:child_process";var F={run(b,G,D={}){return new Promise((X)=>{let z=performance.now(),J=D.timeoutMs??15000;F1(b,[...G],{env:D.env??process.env,timeout:J,windowsHide:!0,windowsVerbatimArguments:D.windowsVerbatimArguments,maxBuffer:1048576},(Q,q,Z)=>{let K=performance.now()-z;X({exitCode:Q?typeof Q.code==="number"?Q.code:1:0,stdout:String(q??""),stderr:String(Z??""),signal:Q?.signal??null,timedOut:Q?.killed===!0&&typeof Q.code!=="string"&&Q.signal==="SIGTERM"&&K>=J&&J>0,durationMs:K})})})}};function y(b,G,D,X,z,J=15000){if(G==="win32"&&/\.(cmd|bat)$/i.test(D)){if(/["%!\r\n]/.test(D)||X.some((Q)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(Q)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return b.run("cmd.exe",["/d","/s","/c",`""${D}" ${X.join(" ")}"`],{env:z,timeoutMs:J,windowsVerbatimArguments:!0})}return b.run(D,X,{env:z,timeoutMs:J})}import{accessSync as C1,constants as w1,existsSync as L1,readFileSync as S1,realpathSync as E1,statSync as I1}from"node:fs";import{mkdtemp as y1,rm as P1}from"node:fs/promises";import{tmpdir as v1}from"node:os";import{join as f1}from"node:path";import{parse as g1}from"jsonc-parser";import{homedir as V1}from"node:os";import{posix as k1,win32 as N1}from"node:path";import{fileURLToPath as A1}from"node:url";function T(b={}){let G=b.env??process.env,D=b.platform??process.platform,X=D==="win32"?N1:k1,z=b.home??(D==="win32"?G.USERPROFILE:G.HOME)??V1(),J=b.cwd??process.cwd(),Q=(O)=>X.resolve(J,O),q=G.OPENCODE_CONFIG_DIR?.trim(),Z=G.XDG_CONFIG_HOME?.trim(),K=G.PI_CODING_AGENT_DIR?.trim()||X.join(z,".pi","agent");if(K==="~")K=z;else if(/^~[/\\]/.test(K))K=X.join(z,K.slice(2));if(K.startsWith("file://"))K=A1(K);return{env:G,platform:D,path:X,home:z,cwd:J,opencode:q?Q(q):Z?X.join(Q(Z),"opencode"):X.join(z,".config","opencode"),pi:Q(K)}}function f(b,G){try{return I1(b)[G]()}catch{return!1}}var V={exists:L1,isFile:(b)=>f(b,"isFile"),isDirectory:(b)=>f(b,"isDirectory"),isExecutable(b){try{return C1(b,w1.X_OK),f(b,"isFile")}catch{return!1}},readText:(b)=>S1(b,"utf8"),realpath:E1};function H(b,G={}){let{env:D,platform:X,path:z,cwd:J}=T(G),Q=G.fs??V,q=Object.entries(D).find(([K])=>X==="win32"?K.toUpperCase()==="PATH":K==="PATH")?.[1]??"",Z=X==="win32"?[".exe",".cmd",".bat",""]:[""];for(let K of q.split(X==="win32"?";":":")){let O=K.trim().replace(/^"|"$/g,"");if(!O)continue;for(let B of Z){let $=z.resolve(J,O,b+B);if(X==="win32"?Q.isFile($):Q.isExecutable($))return $}}return null}function s(b={}){let{platform:G,home:D,env:X,path:z}=T(b);if(G==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",z.join(D,"Applications","OpenCode.app"),z.join(D,"Applications","OpenCode Beta.app")];if(G==="win32"){let J=X.LOCALAPPDATA||z.join(D,"AppData","Local");return[z.join(J,"Programs","opencode"),z.join(J,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",z.join(D,".local","share","applications","opencode.desktop")]}function g(b,G){let D=G.fs??V,{path:X}=T(G);try{let z=D.readText(b);if(z.length>65536)return b;let J=[...z.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!J.length)J.push(...z.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let Q=J.at(-1)?.[1];if(Q){let q=X.join(X.dirname(b),...Q.split(/[/\\]+/));if(D.isFile(q))return D.realpath(q)}return D.realpath(b)}catch{return b}}function d1(b,G){let D=G.fs??V,{path:X}=T(G),z=X.dirname(g(b,G));for(;;){try{let Q=JSON.parse(D.readText(X.join(z,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(Q.name))return"2";if(Q.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(Q.version??"")?"2":"1"}catch{}let J=X.dirname(z);if(J===z)return null;z=J}}function i(b={}){let G=H("opencode",b),D=H("opencode2",b),X=G&&D&&g(G,b)===g(D,b),z=b.fs??V,{path:J,opencode:Q}=T(b),q="1";for(let K of["jsonc","json"]){let O=J.join(Q,`opencode.${K}`);if(!z.exists(O))continue;try{if(Object.hasOwn(g1(z.readText(O))??{},"plugins"))q="2"}catch{}break}let Z=G?d1(G,b)??(X?"2":q):null;if(D&&Z==="1"&&!X)return"ambiguous";return D||X?"2":Z??q}async function d(b,G={}){let D=G.fs??V,{env:X,platform:z,opencode:J,pi:Q}=T(G),q=G.runner??F,Z=H("opencode",G)??H("opencode2",G),K=H("pi",G),O=H("ck",G),B=async(x)=>{if(!x)return null;let W;try{W=await y1(f1(v1(),"common-auth-setup-version-"));let I={...X,HOME:W,USERPROFILE:W,XDG_CONFIG_HOME:W,XDG_DATA_HOME:W,XDG_STATE_HOME:W,XDG_CACHE_HOME:W,OPENCODE_CONFIG_DIR:W,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:W},_=await y(q,z,x,["--version"],I,2000);return _.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(_.stdout)?.[0]??null:null}catch{return null}finally{if(W)await P1(W,{recursive:!0,force:!0}).catch(()=>{})}},$=!1;if(O&&D.exists(b.vault.connectionFile))try{(await(G.connect??P)({connectionFile:b.vault.connectionFile,handshakeTimeoutMs:2000})).close(),$=!0}catch{$=!1}let[Y,U]=await Promise.all([B(Z),B(K)]);return{opencode:{installed:D.isDirectory(J)||s(G).some((x)=>D.exists(x))||Z!==null,executable:Z,version:Y,directory:J,generation:i(G)},pi:{installed:K!==null||D.isDirectory(Q),executable:K,version:U,directory:Q},claustrum:{available:$,executable:O}}}import{setTimeout as s1}from"node:timers/promises";import{writeEnrollmentTokenFile as i1}from"@cortexkit/claustrum-client";var c1=45000,r=new Set(["opencode","litecode","opencode2","pi"]),h1=new Set(["node","bun"]),u1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function m1(b){return[...b.matchAll(/"([^"]*)"|(\S+)/g)].map((G)=>G[1]??G[2]??"")}function n(b){return(b.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var p1=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"]),l1=new Set(["-e","--eval","-p","--print"]);function a1(b,G){for(let D=0;D<G.length;D++){let X=G[D]??"";if(X==="--")return G[D+1];if(l1.has(X))return;if(X.startsWith("-")){if(!X.includes("=")&&p1.has(X))D++;continue}if(b==="bun"&&X==="run")continue;return X}return}function o(b){let[G,...D]=m1(b);if(G===void 0)return null;let X=n(G);if(r.has(X))return X;if(!h1.has(X))return null;let z=a1(X,D);if(z===void 0)return null;let J=n(z);if(r.has(J))return J;return u1.test(z)?"pi":null}class j extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(b){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=b.step,this.exitCode=b.exitCode,this.signal=b.signal,this.timedOut=b.timedOut,this.durationMs=b.durationMs}get refusalText(){let b=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}: ${b} after ${Math.round(this.durationMs)} ms.`}}class k extends Error{activeHosts;constructor(b){let G=b.map((D)=>({pid:D.pid,command:o(D.command)??"host"}));super(`OpenCode or Pi processes are currently running:
3
- ${G.map((D)=>` - PID ${D.pid}: ${D.command}`).join(`
2
+ import{c as _0}from"./index-qp5hdpw8.js";import{Cb as I0,Fa as j0,Ga as E,Ha as O,Ia as v,kb as A0,ta as k0,ua as f,va as o}from"./index-03em8hv1.js";import{$c as R0,gd as m,hd as P,jd as c,kd as q0}from"./index-f21addzm.js";import"./index-qxbchh2d.js";import{Ee as e,Ke as Y0,Le as C0,Oe as w0}from"./index-ehjj89rx.js";import"./index-r2s51ac1.js";import"./index-xwvze96g.js";import{spawn as L0}from"node:child_process";var M=4096,S0=1048576;class t{buffer=Buffer.alloc(M);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=M){if(G.length>M||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-M),this.start=0,this.length=M;return}let b=Math.max(0,this.length+G.length-M);if(b>0)this.truncated=!0;this.start=(this.start+b)%M,this.length-=b;let z=(this.start+this.length)%M,J=Math.min(G.length,M-z);if(G.copy(this.buffer,z,0,J),J<G.length)G.copy(this.buffer,0,J);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),b=Math.min(this.length,M-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 J=G[z];if(J===void 0||(J&192)!==128)break;z++}return G.subarray(z).toString("utf8")}}var A={run(G,b,z={}){return new Promise((J)=>{let K=performance.now(),Q=z.timeoutMs??15000,$=new t,W=[],q=0,Z=!1,x=!1,D=!1,U;try{U=L0(G,[...b],{env:z.env??process.env,windowsHide:!0,windowsVerbatimArguments:z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{J({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let j=Q>0?setTimeout(()=>{D=!0,U.kill("SIGTERM")},Q):void 0;U.stdout?.on("data",(X)=>{let R=S0-q,F=Math.min(R,X.length);if(F>0)W.push(X.subarray(0,F)),q+=F;if(X.length>R)Z=!0,U.kill("SIGTERM")}),U.stderr?.on("data",(X)=>$.push(X));let V=!1,B=(X,R)=>{if(V)return;if(V=!0,j)clearTimeout(j);J({exitCode:x?1:Z?1:X??1,stdout:Buffer.concat(W,q).toString("utf8"),stderr:$.toString(),stderrTruncated:$.didTruncate,...x?{spawnError:!0}:{},signal:R??null,timedOut:D,durationMs:performance.now()-K})};U.once("error",()=>{if(x=!0,U.pid===void 0)B(null,null)}),U.once("close",(X,R)=>B(X,R))})}};function g(G,b,z,J,K,Q=15000){if(b==="win32"&&/\.(cmd|bat)$/i.test(z)){if(/["%!\r\n]/.test(z)||J.some(($)=>!/^[a-zA-Z0-9@:/._+-]+$/.test($)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${z}" ${J.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return G.run(z,J,{env:K,timeoutMs:Q})}var y0="Pi install failed; run pi install after checking your npm connection.";function v0(G){let b=Buffer.from(G,"utf8");if(b.length<=M)return G;let z=b.length-M;while(z<b.length){let J=b[z];if(J===void 0||(J&192)!==128)break;z++}return b.subarray(z).toString("utf8")}function E0(G){let b=G.indexOf(`
3
+ `);return b<0?"":G.slice(b+1)}class d extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(y0);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let b=G.stderrTruncated?E0(G.stderrTail):G.stderrTail,z=e(b);this.stderrTail=v0(typeof z==="string"?z:"")}}var f0={opencode:"OpenCode",pi:"Pi"},g0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function G0({host:G,outcome:b}){return`${f0[G]}: ${g0[b]}`}var d0=new WeakMap;function b0(G,b){if(typeof G!=="object"&&typeof G!=="function"||!G)return;d0.set(G,Object.freeze(b.map((z)=>Object.freeze({...z}))))}import{accessSync as p0,constants as l0,existsSync as a0,readFileSync as i0,realpathSync as s0,statSync as r0}from"node:fs";import{mkdtemp as n0,rm as o0}from"node:fs/promises";import{tmpdir as t0}from"node:os";import{join as e0}from"node:path";import{parse as G1}from"jsonc-parser";import{homedir as m0}from"node:os";import{posix as c0,win32 as h0}from"node:path";import{fileURLToPath as u0}from"node:url";function N(G={}){let b=G.env??process.env,z=G.platform??process.platform,J=z==="win32"?h0:c0,K=G.home??(z==="win32"?b.USERPROFILE:b.HOME)??m0(),Q=G.cwd??process.cwd(),$=(x)=>J.resolve(Q,x),W=b.OPENCODE_CONFIG_DIR?.trim(),q=b.XDG_CONFIG_HOME?.trim(),Z=b.PI_CODING_AGENT_DIR?.trim()||J.join(K,".pi","agent");if(Z==="~")Z=K;else if(/^~[/\\]/.test(Z))Z=J.join(K,Z.slice(2));if(Z.startsWith("file://"))Z=u0(Z);return{env:b,platform:z,path:J,home:K,cwd:Q,opencode:W?$(W):q?J.join($(q),"opencode"):J.join(K,".config","opencode"),pi:$(Z)}}function h(G,b){try{return r0(G)[b]()}catch{return!1}}var _={exists:a0,isFile:(G)=>h(G,"isFile"),isDirectory:(G)=>h(G,"isDirectory"),isExecutable(G){try{return p0(G,l0.X_OK),h(G,"isFile")}catch{return!1}},readText:(G)=>i0(G,"utf8"),realpath:s0};function k(G,b={}){let{env:z,platform:J,path:K,cwd:Q}=N(b),$=b.fs??_,W=Object.entries(z).find(([Z])=>J==="win32"?Z.toUpperCase()==="PATH":Z==="PATH")?.[1]??"",q=J==="win32"?[".exe",".cmd",".bat",""]:[""];for(let Z of W.split(J==="win32"?";":":")){let x=Z.trim().replace(/^"|"$/g,"");if(!x)continue;for(let D of q){let U=K.resolve(Q,x,G+D);if(J==="win32"?$.isFile(U):$.isExecutable(U))return U}}return null}function z0(G={}){let{platform:b,home:z,env:J,path:K}=N(G);if(b==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",K.join(z,"Applications","OpenCode.app"),K.join(z,"Applications","OpenCode Beta.app")];if(b==="win32"){let Q=J.LOCALAPPDATA||K.join(z,"AppData","Local");return[K.join(Q,"Programs","opencode"),K.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",K.join(z,".local","share","applications","opencode.desktop")]}function u(G,b){let z=b.fs??_,{path:J}=N(b);try{let K=z.readText(G);if(K.length>65536)return G;let Q=[...K.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...K.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let $=Q.at(-1)?.[1];if($){let W=J.join(J.dirname(G),...$.split(/[/\\]+/));if(z.isFile(W))return z.realpath(W)}return z.realpath(G)}catch{return G}}function b1(G,b){let z=b.fs??_,{path:J}=N(b),K=J.dirname(u(G,b));for(;;){try{let $=JSON.parse(z.readText(J.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes($.name))return"2";if($.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test($.version??"")?"2":"1"}catch{}let Q=J.dirname(K);if(Q===K)return null;K=Q}}function J0(G={}){let b=k("opencode",G),z=k("opencode2",G),J=b&&z&&u(b,G)===u(z,G),K=G.fs??_,{path:Q,opencode:$}=N(G),W="1";for(let Z of["jsonc","json"]){let x=Q.join($,`opencode.${Z}`);if(!K.exists(x))continue;try{if(Object.hasOwn(G1(K.readText(x))??{},"plugins"))W="2"}catch{}break}let q=b?b1(b,G)??(J?"2":W):null;if(z&&q==="1"&&!J)return"ambiguous";return z||J?"2":q??W}async function p(G,b={}){let z=b.fs??_,{env:J,platform:K,opencode:Q,pi:$}=N(b),W=b.runner??A,q=k("opencode",b)??k("opencode2",b),Z=k("pi",b),x=k("ck",b),D=async(B)=>{if(!B)return null;let X;try{X=await n0(e0(t0(),"common-auth-setup-version-"));let R={...J,HOME:X,USERPROFILE:X,XDG_CONFIG_HOME:X,XDG_DATA_HOME:X,XDG_STATE_HOME:X,XDG_CACHE_HOME:X,OPENCODE_CONFIG_DIR:X,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:X},F=await g(W,K,B,["--version"],R,2000);return F.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(F.stdout)?.[0]??null:null}catch{return null}finally{if(X)await o0(X,{recursive:!0,force:!0}).catch(()=>{})}},U=!1;if(x&&z.exists(G.vault.connectionFile))try{(await(b.connect??m)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),U=!0}catch{U=!1}let[j,V]=await Promise.all([D(q),D(Z)]);return{opencode:{installed:z.isDirectory(Q)||z0(b).some((B)=>z.exists(B))||q!==null,executable:q,version:j,directory:Q,generation:J0(b)},pi:{installed:Z!==null||z.isDirectory($),executable:Z,version:V,directory:$},claustrum:{available:U,executable:x}}}import{setTimeout as U1}from"node:timers/promises";import{writeEnrollmentTokenFile as W1}from"@cortexkit/claustrum-client";var z1=45000,K0=new Set(["opencode","litecode","opencode2","pi"]),J1=new Set(["node","bun"]),K1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function Q1(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((b)=>b[1]??b[2]??"")}function Q0(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var Z1=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"]),$1=new Set(["-e","--eval","-p","--print"]);function q1(G,b){for(let z=0;z<b.length;z++){let J=b[z]??"";if(J==="--")return b[z+1];if($1.has(J))return;if(J.startsWith("-")){if(!J.includes("=")&&Z1.has(J))z++;continue}if(G==="bun"&&J==="run")continue;return J}return}function Z0(G){let[b,...z]=Q1(G);if(b===void 0)return null;let J=Q0(b);if(K0.has(J))return J;if(!J1.has(J))return null;let K=q1(J,z);if(K===void 0)return null;let Q=Q0(K);if(K0.has(Q))return Q;return K1.test(K)?"pi":null}class Y 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:Z0(z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
+ ${b.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
4
5
  `)}
5
6
 
6
- Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=G,this.name="ProcessFenceViolationError"}}async function c(b=F,G={}){let D=(G.platform??process.platform)==="win32",X={step:D?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},z=async(J,Q,q,Z)=>{let K=performance.now();X={step:J,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let O=await b.run(Q,q,{env:G.env,timeoutMs:Z});return X={step:J,exitCode:O.exitCode,signal:O.signal??null,timedOut:O.timedOut??!1,durationMs:O.durationMs??performance.now()-K},O}finally{if(X.exitCode===null)X.durationMs=performance.now()-K;G.onStep?.({...X})}};try{let J=await z(D?"tasklist":"ps",D?"tasklist.exe":"ps",D?["/fo","csv","/nh"]:["-eo","pid,command"]);if(J.exitCode!==0)throw new j(X);let Q=[];for(let Z of J.stdout.split(/\r?\n/)){let K=Z.trim();if(!K)continue;let O,B;if(D){let $=/^"([^"]+)","(\d+)"(?:,|$)/.exec(K);if(!$)throw new j(X);B=$[1]??"",O=Number($[2])}else{let $=/^(\d+)\s+(.+)$/.exec(K);if(!$){if(/^PID\s+COMMAND$/i.test(K))continue;throw new j(X)}O=Number($[1]),B=$[2]??""}if(!Number.isSafeInteger(O)||O<0)throw new j(X);Q.push({pid:O,command:B})}if(!Q.length)throw new j(X);let q=Q.filter((Z)=>Z.pid!==process.pid&&/^(?:node|bun)\.exe$/i.test(Z.command));if(D&&q.length&&G.inspectRuntimes!==!1){let Z=await z("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`],c1);if(Z.exitCode!==0)throw new j(X);let K=JSON.parse(Z.stdout||"null"),O=K===null?[]:Array.isArray(K)?K:[K],B=new Map;for(let $ of O){if(!$||typeof $!=="object"||!("ProcessId"in $)||!("CommandLine"in $)||!Number.isSafeInteger($.ProcessId))throw new j(X);if(typeof $.CommandLine==="string")B.set(Number($.ProcessId),$.CommandLine);else if(q.some((Y)=>Y.pid===$.ProcessId))throw new j(X)}for(let $ of q)$.command=B.get($.pid)??""}return Q}catch(J){if(J instanceof j)throw J;throw new j(X)}}function C(b=F,G={}){let D=(X)=>X.pid!==process.pid&&o(X.command)!==null;return{async listRunningHosts(X){return(await c(b,{...G,env:X})).filter(D)},async previewRunningHosts(X){let z=await c(b,{...G,env:X,inspectRuntimes:!1}),J=(G.platform??process.platform)==="win32";return{hosts:z.filter(D),uncheckedRuntimes:J?z.filter((Q)=>Q.pid!==process.pid&&/^(?:node|bun)\.exe$/i.test(Q.command)).length:0}}}}async function w(b,G){let D=await b.listRunningHosts(G);if(D.length)throw new k(D)}async function e(b,G,D,X,z){let{name:J,paths:Q}=b.vault.hosts[G],q=N(Q);await z();let Z=await(D.connect??P)({connectionFile:b.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw Error("Claustrum connection failed; start ck and rerun setup.")});try{let K=new t({proposedName:J,paths:q,client:{enrollPropose:async(B)=>{return await z(),Z.enrollPropose(B)},enrollPoll:async(B)=>{return await z(),Z.enrollPoll(B)}},writeTokenFile:async(B,$)=>{await z(),await i1(B,$)}}),O;for(let B=0;B<300;B++){await z();let $=await K.reconcile();if($.state==="approved"){R(X,`Connected ${G} to Claustrum.`);return}if($.state!=="pending"&&$.state!=="busy")throw Error("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");if($.state==="pending"&&$.requestId&&$.requestId!==O){if(!/^[a-zA-Z0-9_-]+$/.test($.requestId))throw Error("Invalid enrollment request id.");O=$.requestId,R(X,"Waiting for approval. In another terminal, run:"),R(X,` ck auth enroll approve --request-id ${$.requestId} --name ${J}`),R(X,`Enrollment files: ${q.statePath}, ${q.tokenPath}`)}await(D.wait??s1)(1000)}throw Error("Claustrum approval is still pending; approve with ck and rerun setup.")}catch(K){if(K instanceof k||K instanceof j)throw K;throw Error("Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.")}finally{Z.close()}}async function b1(b,G){let D=new Set(G);for(;;){let X=await L(b,[...["opencode","pi"].map((z)=>({value:z,label:`[${D.has(z)?"x":" "}] ${z==="opencode"?"OpenCode":"Pi"}`,hint:G.includes(z)?"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(X===null)return null;if(X==="done")return[...D];if(D.has(X))D.delete(X);else D.add(X)}}import{applyEdits as h,createScanner as J0,findNodeAtLocation as K0,modify as D1,parse as Q0,parseTree as Z0}from"jsonc-parser";import{randomUUID as r1}from"node:crypto";import{mkdir as n1,open as o1,rename as t1,stat as e1,unlink as b0}from"node:fs/promises";import{basename as G0,dirname as D0,join as X0}from"node:path";import{setTimeout as z0}from"node:timers/promises";async function G1(b,G,D={}){let X=(D.platform??process.platform)==="win32",z=D0(b);await n1(z,{recursive:!0});let J;if(!X)try{J=(await e1(b)).mode&4095}catch(Z){if(Z.code!=="ENOENT")throw Z}let Q=X0(z,`.${G0(b)}.${(D.stageName??r1)()}.tmp`),q=!1;try{let Z=await o1(Q,"wx",J??438);q=!0;try{if(await Z.writeFile(G,"utf8"),J!==void 0)await Z.chmod(J)}finally{await Z.close()}let K=D.now??(()=>performance.now()),O=K();for(let B=0;;B++){await D.beforeRename?.();try{await(D.rename??t1)(Q,b),q=!1;return}catch($){let Y=$.code,U=2000-(K()-O);if(!X||!["EPERM","EBUSY","EACCES"].includes(Y??"")||U<=0||B>=40)throw Error(`Unable to replace host config ${b}. Close editors or other programs using the file, then rerun setup.`);await(D.wait??z0)(Math.min(U,25*2**Math.min(B,2)))}}}finally{if(q)await b0(Q).catch(()=>{})}}function X1(b){let G=typeof b==="string"?b:Array.isArray(b)?b[0]:b&&typeof b==="object"&&("package"in b)?b.package:null;if(typeof G!=="string")return null;let D=G.indexOf("@",G.startsWith("@")?1:0);return D<0?G:G.slice(0,D)}function z1(b,G,D){let X=Z0(b),z=X&&K0(X,[G]),J=z?.children??[],Q=J[D];if(!Q||!z)throw Error("Invalid plugin array edit.");let q=[{offset:Q.offset,length:Q.length,content:""}],Z=(K,O)=>{let B=J0(b.slice(K,O),!0);if(B.scan(),b[K+B.getTokenOffset()]===",")q.push({offset:K+B.getTokenOffset(),length:1,content:""})};if(D===J.length-1){let K=J[D-1];if(K)Z(K.offset+K.length,Q.offset);Z(Q.offset+Q.length,z.offset+z.length-1)}else Z(Q.offset+Q.length,J[D+1]?.offset??Q.offset+Q.length);return h(b,q)}function J1(b,G,D,X){let z=[],J=Q0(b,z,{allowTrailingComma:!0});if(z.length||!J||typeof J!=="object"||Array.isArray(J))throw Error("Invalid OpenCode config; refusing to overwrite it.");let Q={formattingOptions:{insertSpaces:!/^\t+/m.test(b),tabSize:/^([ ]+)"/m.exec(b)?.[1]?.length??2,eol:b.includes(`\r
7
+ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=b,this.name="ProcessFenceViolationError"}}async function l(G=A,b={}){let z=(b.platform??process.platform)==="win32",J={step:z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},K=async(Q,$,W,q)=>{let Z=performance.now();J={step:Q,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let x=await G.run($,W,{env:b.env,timeoutMs:q});return J={step:Q,exitCode:x.exitCode,signal:x.signal??null,timedOut:x.timedOut??!1,durationMs:x.durationMs??performance.now()-Z},x}finally{if(J.exitCode===null)J.durationMs=performance.now()-Z;b.onStep?.({...J})}};try{let Q=await K(z?"tasklist":"ps",z?"tasklist.exe":"ps",z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(Q.exitCode!==0)throw new Y(J);let $=[];for(let q of Q.stdout.split(/\r?\n/)){let Z=q.trim();if(!Z)continue;let x,D;if(z){let U=/^"([^"]+)","(\d+)"(?:,|$)/.exec(Z);if(!U)throw new Y(J);D=U[1]??"",x=Number(U[2])}else{let U=/^(\d+)\s+(.+)$/.exec(Z);if(!U){if(/^PID\s+COMMAND$/i.test(Z))continue;throw new Y(J)}x=Number(U[1]),D=U[2]??""}if(!Number.isSafeInteger(x)||x<0)throw new Y(J);$.push({pid:x,command:D})}if(!$.length)throw new Y(J);let W=$.filter((q)=>q.pid!==process.pid&&/^(?:node|bun)\.exe$/i.test(q.command));if(z&&W.length&&b.inspectRuntimes!==!1){let q=await K("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`],z1);if(q.exitCode!==0)throw new Y(J);let Z=JSON.parse(q.stdout||"null"),x=Z===null?[]:Array.isArray(Z)?Z:[Z],D=new Map;for(let U of x){if(!U||typeof U!=="object"||!("ProcessId"in U)||!("CommandLine"in U)||!Number.isSafeInteger(U.ProcessId))throw new Y(J);if(typeof U.CommandLine==="string")D.set(Number(U.ProcessId),U.CommandLine);else if(W.some((j)=>j.pid===U.ProcessId))throw new Y(J)}for(let U of W)U.command=D.get(U.pid)??""}return $}catch(Q){if(Q instanceof Y)throw Q;throw new Y(J)}}function S(G=A,b={}){let z=(J)=>J.pid!==process.pid&&Z0(J.command)!==null;return{async listRunningHosts(J){return(await l(G,{...b,env:J})).filter(z)},async previewRunningHosts(J){let K=await l(G,{...b,env:J,inspectRuntimes:!1}),Q=(b.platform??process.platform)==="win32";return{hosts:K.filter(z),uncheckedRuntimes:Q?K.filter(($)=>$.pid!==process.pid&&/^(?:node|bun)\.exe$/i.test($.command)).length:0}}}}async function y(G,b){let z=await G.listRunningHosts(b);if(z.length)throw new T(z)}var $0="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";class I extends Error{}async function U0(G,b,z,J,K){let{name:Q,paths:$}=G.vault.hosts[b],W=P($);await K();let q=await(z.connect??m)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new I("Claustrum connection failed; start ck and rerun setup.")});try{let Z=new q0({proposedName:Q,paths:W,client:{enrollPropose:async(D)=>{return await K(),q.enrollPropose(D)},enrollPoll:async(D)=>{return await K(),q.enrollPoll(D)}},writeTokenFile:async(D,U)=>{await K(),await W1(D,U)}}),x;for(let D=0;D<300;D++){await K();let U=await Z.reconcile();if(U.state==="approved"){O(J,`Connected ${b} to Claustrum.`);return}if(U.state!=="pending"&&U.state!=="busy")throw new I("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");if(U.state==="pending"&&U.requestId&&U.requestId!==x){if(!/^[a-zA-Z0-9_-]+$/.test(U.requestId))throw new I("Invalid enrollment request id.");x=U.requestId,O(J,"Waiting for approval. In another terminal, run:"),O(J,` ck auth enroll approve --request-id ${U.requestId} --name ${Q}`),O(J,`Enrollment files: ${W.statePath}, ${W.tokenPath}`)}await(z.wait??U1)(1000)}throw new I("Claustrum approval is still pending; approve with ck and rerun setup.")}catch(Z){if(Z instanceof T||Z instanceof Y)throw Z;if(Z instanceof I)throw new I($0);throw Error($0)}finally{q.close()}}async function W0(G,b){let z=new Set(b);for(;;){let J=await v(G,[...["opencode","pi"].map((K)=>({value:K,label:`[${z.has(K)?"x":" "}] ${K==="opencode"?"OpenCode":"Pi"}`,hint:b.includes(K)?"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(J===null)return null;if(J==="done")return[...z];if(z.has(J))z.delete(J);else z.add(J)}}import{applyEdits as a,createScanner as H1,findNodeAtLocation as M1,modify as D0,parse as N1,parseTree as R1}from"jsonc-parser";import{randomUUID as x1}from"node:crypto";import{mkdir as D1,open as F1,rename as V1,stat as X1,unlink as j1}from"node:fs/promises";import{basename as O1,dirname as B1,join as Y1}from"node:path";import{setTimeout as C1}from"node:timers/promises";async function x0(G,b,z={}){let J=(z.platform??process.platform)==="win32",K=B1(G);await D1(K,{recursive:!0});let Q;if(!J)try{Q=(await X1(G)).mode&4095}catch(q){if(q.code!=="ENOENT")throw q}let $=Y1(K,`.${O1(G)}.${(z.stageName??x1)()}.tmp`),W=!1;try{let q=await F1($,"wx",Q??438);W=!0;try{if(await q.writeFile(b,"utf8"),Q!==void 0)await q.chmod(Q)}finally{await q.close()}let Z=z.now??(()=>performance.now()),x=Z();for(let D=0;;D++){await z.beforeRename?.();try{await(z.rename??V1)($,G),W=!1;return}catch(U){let j=U.code,V=2000-(Z()-x);if(!J||!["EPERM","EBUSY","EACCES"].includes(j??"")||V<=0||D>=40)throw Error(`Unable to replace host config ${G}. Close editors or other programs using the file, then rerun setup.`);await(z.wait??C1)(Math.min(V,25*2**Math.min(D,2)))}}}finally{if(W)await j1($).catch(()=>{})}}function F0(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 V0(G,b,z){let J=R1(G),K=J&&M1(J,[b]),Q=K?.children??[],$=Q[z];if(!$||!K)throw Error("Invalid plugin array edit.");let W=[{offset:$.offset,length:$.length,content:""}],q=(Z,x)=>{let D=H1(G.slice(Z,x),!0);if(D.scan(),G[Z+D.getTokenOffset()]===",")W.push({offset:Z+D.getTokenOffset(),length:1,content:""})};if(z===Q.length-1){let Z=Q[z-1];if(Z)q(Z.offset+Z.length,$.offset);q($.offset+$.length,K.offset+K.length-1)}else q($.offset+$.length,Q[z+1]?.offset??$.offset+$.length);return a(G,W)}function X0(G,b,z,J){let K=[],Q=N1(G,K,{allowTrailingComma:!0});if(K.length||!Q||typeof Q!=="object"||Array.isArray(Q))throw Error("Invalid OpenCode config; refusing to overwrite it.");let $={formattingOptions:{insertSpaces:!/^\t+/m.test(G),tabSize:/^([ ]+)"/m.exec(G)?.[1]?.length??2,eol:G.includes(`\r
7
8
  `)?`\r
8
9
  `:`
9
- `}},q=b,Z=J[G];if(Z!==void 0&&!Array.isArray(Z))throw Error(`OpenCode ${G} must be an array.`);let K=Array.isArray(Z)?[...Z]:[],O=K.flatMap((Y,U)=>X1(Y)===D?[U]:[]),B=`${D}@${X}`;if(!O.length)q=h(q,D1(q,Z===void 0?[G]:[G,K.length],Z===void 0?[B]:B,Q));else{let Y=O[0],U=K[Y],x=Array.isArray(U)?[B,...U.slice(1)]:U&&typeof U==="object"?{...U,package:B}:B;if(JSON.stringify(U)!==JSON.stringify(x))q=h(q,D1(q,[G,Y],x,Q));for(let W of O.slice(1).reverse())q=z1(q,G,W)}let $=G==="plugin"?"plugins":"plugin";if(Array.isArray(J[$])){let Y=J[$];for(let U=Y.length-1;U>=0;U--)if(X1(Y[U])===D)q=z1(q,$,U)}return q}function u(b,G,D={}){let X=D.fs??V,{path:z,opencode:J}=T(D),Q=G==="2"?"plugins":"plugin";return(G==="2"?["opencode"]:["opencode","tui"]).map((Z)=>{let K=z.join(J,`${Z}.jsonc`),O=z.join(J,`${Z}.json`),B=X.exists(K)?K:X.exists(O)?O:K,$=X.exists(B),Y=$?X.readText(B):`${JSON.stringify({$schema:`https://opencode.ai/${Z==="tui"?"tui":"config"}.json`},null,2)}
10
- `,U=J1(Y,Q,b.packages.opencode,b.version);return{path:B,content:U,changed:!$||U!==Y}})}async function m(b,G){for(let D of b){if(!D.changed)continue;await G?.(),await G1(D.path,D.content,{beforeRename:G})}}async function p(b,G,D={}){let{platform:X,env:z}=T(D);if((await y(D.runner??F,X,G,["install",`npm:${b.packages.pi}@${b.version}`],z)).exitCode!==0)throw Error("Pi install failed; run pi install after checking your npm connection.")}var Q1="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function $0(b){let G={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,opencode:void 0};for(let D of b)if(D==="--yes")G.yes=!0;else if(D==="--dry-run")G.dryRun=!0;else if(D==="--claustrum")G.claustrum=!0;else if(D==="--no-claustrum")G.noClaustrum=!0;else if(D==="--login")G.login=!0;else if(/^--opencode=(1|2|both)$/.test(D))G.opencode=D.slice(11);else throw Error(`Unknown setup argument: ${D}`);if(G.claustrum&&G.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(G.login&&G.claustrum)throw Error("--login and --claustrum cannot be used together.");return G}function q0(b){for(let G of Object.values(b.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(G))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(b.version))throw Error("Setup requires a concrete package version.");for(let G of Object.values(b.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(G.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function l(b,G=[],D={}){let X=$0(G);q0(b);let z=D.terminal??K1(),J=await d(b,D);R(z,`${b.displayName} setup`);for(let[_,M]of[["OpenCode",J.opencode],["Pi",J.pi]])R(z,`${_}: ${M.installed?`found (version ${M.version??"unknown"})`:"not found"} — ${M.directory}`);R(z,`Claustrum: ${J.claustrum.available?"available":"not available"}`);let Q=J.pi.installed&&!J.pi.executable;if(Q)R(z,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let q=["opencode","pi"].filter((_)=>J[_].installed&&!(_==="pi"&&Q)),Z=X.yes||X.dryRun&&!S(z);if(!Z&&!S(z))throw Error("Setup requires a TTY or --yes.");let K=Z?q:await b1(z,q)??[],O=X.opencode??(J.opencode.generation==="ambiguous"?"1":J.opencode.generation);if(K.includes("opencode")&&!X.opencode&&J.opencode.generation==="ambiguous"){if(Z||!S(z))throw Error(Q1);let _=await L(z,[{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(_===null)return{hosts:[],dryRun:X.dryRun,mode:"local",detection:J};O=_}if(!K.length)return R(z,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:K,dryRun:X.dryRun,mode:"local",detection:J};let{env:B,platform:$}=T(D),Y=D.fence??C(D.runner??F,{platform:$}),U=async()=>{try{await w(Y,B)}catch(_){if(_ instanceof j)R(z,_.refusalText);throw _}};if(R(z,"Checking that OpenCode and Pi are not running…"),X.dryRun)try{let _=Y.previewRunningHosts?await Y.previewRunningHosts(B):{hosts:await Y.listRunningHosts(B),uncheckedRuntimes:0},M=_.hosts;if(_.uncheckedRuntimes>0)R(z,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let H1=new Set(new k(M).activeHosts.map((v)=>v.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let v of H1)R(z,`${v} is running; setup will ask you to quit it.`)}catch(_){if(R(z,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),_ instanceof j)R(z,_.refusalText)}else await U();if(X.claustrum&&!J.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let x=Boolean(X.claustrum);if(!x&&!X.login&&!X.noClaustrum&&!Z&&J.claustrum.available&&S(z)){let _=await L(z,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(_===null)return R(z,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:X.dryRun,mode:"local",detection:J};x=_===!0}let W=x?"claustrum":"local",I=K.includes("opencode")?u(b,O,D):[];if(X.dryRun){R(z,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let _ of K){if(b.beforeSignIn)R(z,`Would run beforeSignIn(${_}, ${W}).`);if(x){let M=N(b.vault.hosts[_].paths);R(z,`Would Connect ${_}: write ${M.statePath} and ${M.tokenPath}; wait for ck auth enroll approve.`)}else R(z,`Would sign in locally for ${_}.`);if(b.beforeRegister)R(z,`Would run beforeRegister(${_}, ${W}).`)}for(let _ of I)R(z,`${_.changed?"Would write":"Unchanged"} ${_.path}:
11
- ${_.content}`);if(K.includes("pi"))R(z,`Would run ${J.pi.executable} install npm:${b.packages.pi}@${b.version}`);for(let _ of K)R(z,`Would migrate ${_} using the plugin callback (provider-specific writes).`)}else{let _={opencodeGeneration:O,mode:W,hosts:Object.freeze([...K]),piAgentDir:J.pi.directory};for(let M of K){if(await U(),await b.beforeSignIn?.(M,_),await U(),x)await e(b,M,D,z,U);else await b.signInLocal(M,_);if(await U(),await b.beforeRegister?.(M,W,_),await U(),M==="opencode")await m(I,U);else await p(b,J.pi.executable,D);await U(),await b.migrate(M,_)}}return R(z,`${X.dryRun?"Planned":"Configured"} ${b.displayName} for ${K.join(", ")} (${W}).`),R(z,`Next: ${K.includes("opencode")?"start OpenCode":"start Pi"} and run ${b.slashCommand}.`),{hosts:K,dryRun:X.dryRun,mode:W,detection:J}}import{basename as R0}from"node:path";import{resolveClaustrumConnectionPath as W0}from"@cortexkit/claustrum-client";var Z1={name:"@cortexkit/pi-openai-auth",version:"1.0.5",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.17.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.9.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.16.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 O0}from"node:os";import{join as B1}from"node:path";function _0(){return process.env.PI_AGENT_DIR?.trim()||B1(O0(),".pi","agent")}function O1(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||B1(_0(),$1)}function U0(b=O1()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||q1(b)}function _1(b=O1()){return{configPath:b,statePath:U0(b)}}var A={name:"@cortexkit/opencode-openai-auth",version:"1.0.5",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.17.1","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.27"},dependencies:{"@cortexkit/claustrum-client":"^0.9.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.16.0","@opentui/core":">=0.6.1","@opentui/solid":">=0.6.1",ai:"^7.0.137","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};function T1(b={}){let G=b.print??console.log,D=b.fence??C(),X={opencode:{stateDir:a(x1().statePath),host:"opencode"},pi:{stateDir:a(_1().statePath),host:"pi"}},z=async(J)=>{if(await Y1(N(X[J]),E(J))!=="local")throw Error(`${J} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:A.name,pi:Z1.name},version:A.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:W0(),hosts:{opencode:{name:E("opencode"),paths:X.opencode},pi:{name:E("pi"),paths:X.pi}}},async beforeRegister(J,Q){if(Q==="claustrum"){if(G(`Allow this host to read OpenAI accounts with:
12
- ck auth grant --principal enrolled:${E(J)} --selector-kind category --selector ${R1.category} --operation read`),J==="opencode")G("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await z(J)},async signInLocal(J,Q){if(await z(J),J==="pi"){G("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(Q.opencodeGeneration!=="1"){let W=R0(H("opencode2",b.io)??H("opencode",b.io)??"opencode");G(`In OpenCode 2, run ${W} 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(Q.opencodeGeneration==="2")return;if(j1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let q=M1(),Z={path:{id:"openai"}};if(await q.get(Z)!==void 0){G("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let K=b.beginLogin??U1,O=new AbortController,B=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),$={version:A.version,signal:O.signal},Y,U=!B;try{Y=await K({...$,headless:B})}catch(W){if(B)throw W;U=!1,G("Browser callback unavailable; using device-code sign-in."),Y=await K({version:A.version,headless:!0})}if(U){if(!(b.openBrowser??W1)(Y.url))O.abort(),await Y.completion.catch(()=>{}),G("Browser unavailable; using device-code sign-in."),Y=await K({version:A.version,headless:!0})}G(`${Y.url}
13
- ${Y.instructions}`);let x=await Y.completion;await w(D),await z(J),await q.set({...Z,body:{type:"oauth",access:x.access,refresh:x.refresh,expires:x.expires,...x.accountId?{accountId:x.accountId}:{}}}),G("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(J){G(`${J}: 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 l(T1(),process.argv.slice(3))}catch(b){console.error(b instanceof Error?b.message:String(b)),process.exitCode=1}
10
+ `}},W=G,q=Q[b];if(q!==void 0&&!Array.isArray(q))throw Error(`OpenCode ${b} must be an array.`);let Z=Array.isArray(q)?[...q]:[],x=Z.flatMap((j,V)=>F0(j)===z?[V]:[]),D=`${z}@${J}`;if(!x.length)W=a(W,D0(W,q===void 0?[b]:[b,Z.length],q===void 0?[D]:D,$));else{let j=x[0],V=Z[j],B=Array.isArray(V)?[D,...V.slice(1)]:V&&typeof V==="object"?{...V,package:D}:D;if(JSON.stringify(V)!==JSON.stringify(B))W=a(W,D0(W,[b,j],B,$));for(let X of x.slice(1).reverse())W=V0(W,b,X)}let U=b==="plugin"?"plugins":"plugin";if(Array.isArray(Q[U])){let j=Q[U];for(let V=j.length-1;V>=0;V--)if(F0(j[V])===z)W=V0(W,U,V)}return W}function i(G,b,z={}){let J=z.fs??_,{path:K,opencode:Q}=N(z),$=b==="2"?"plugins":"plugin";return(b==="2"?["opencode"]:["opencode","tui"]).map((q)=>{let Z=K.join(Q,`${q}.jsonc`),x=K.join(Q,`${q}.json`),D=J.exists(Z)?Z:J.exists(x)?x:Z,U=J.exists(D),j=U?J.readText(D):`${JSON.stringify({$schema:`https://opencode.ai/${q==="tui"?"tui":"config"}.json`},null,2)}
11
+ `,V=X0(j,$,G.packages.opencode,G.version);return{path:D,content:V,changed:!U||V!==j}})}async function s(G,b){for(let z of G){if(!z.changed)continue;await b?.(),await x0(z.path,z.content,{beforeRename:b})}}async function r(G,b,z={}){let{platform:J,env:K}=N(z),Q=await g(z.runner??A,J,b,["install",`npm:${G.packages.pi}@${G.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new d({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var O0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function k1(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 w1(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 A1(G,b,z){let J=[];for(let K of b){let Q=z.get(K)??"not-enrolled";if(Q==="unknown"){let{name:$,paths:W}=G.vault.hosts[K],q=await c(P(W),$).catch(()=>"unreadable");if(q==="vault")Q="enrolled";else if(q==="local")Q="not-enrolled"}J.push({host:K,outcome:Q})}return J}async function n(G,b=[],z={}){let J=k1(b);w1(G);let K=z.terminal??j0(),Q=await p(G,z);O(K,`${G.displayName} setup`);for(let[F,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])O(K,`${F}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);O(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let $=Q.pi.installed&&!Q.pi.executable;if($)O(K,"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((F)=>Q[F].installed&&!(F==="pi"&&$)),q=J.yes||J.dryRun&&!E(K);if(!q&&!E(K))throw Error("Setup requires a TTY or --yes.");let Z=q?W:await W0(K,W)??[],x=J.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(Z.includes("opencode")&&!J.opencode&&Q.opencode.generation==="ambiguous"){if(q||!E(K))throw Error(O0);let F=await v(K,[{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(F===null)return{hosts:[],dryRun:J.dryRun,mode:"local",detection:Q};x=F}if(!Z.length)return O(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:Z,dryRun:J.dryRun,mode:"local",detection:Q};let{env:D,platform:U}=N(z),j=z.fence??S(z.runner??A,{platform:U}),V=async()=>{try{await y(j,D)}catch(F){if(F instanceof Y)O(K,F.refusalText);throw F}};if(O(K,"Checking that OpenCode and Pi are not running…"),J.dryRun)try{let F=j.previewRunningHosts?await j.previewRunningHosts(D):{hosts:await j.listRunningHosts(D),uncheckedRuntimes:0},H=F.hosts;if(F.uncheckedRuntimes>0)O(K,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let C=new Set(new T(H).activeHosts.map((w)=>w.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let w of C)O(K,`${w} is running; setup will ask you to quit it.`)}catch(F){if(O(K,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),F instanceof Y)O(K,F.refusalText)}else await V();if(J.claustrum&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let B=Boolean(J.claustrum);if(!B&&!J.login&&!J.noClaustrum&&!q&&Q.claustrum.available&&E(K)){let F=await v(K,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(F===null)return O(K,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:J.dryRun,mode:"local",detection:Q};B=F===!0}let X=B?"claustrum":"local",R=Z.includes("opencode")?i(G,x,z):[];if(J.dryRun){O(K,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let F of Z){if(G.beforeSignIn)O(K,`Would run beforeSignIn(${F}, ${X}).`);if(B){let H=P(G.vault.hosts[F].paths);O(K,`Would Connect ${F}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else O(K,`Would sign in locally for ${F}.`);if(G.beforeRegister)O(K,`Would run beforeRegister(${F}, ${X}).`)}for(let F of R)O(K,`${F.changed?"Would write":"Unchanged"} ${F.path}:
12
+ ${F.content}`);if(Z.includes("pi"))O(K,`Would run ${Q.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let F of Z)O(K,`Would migrate ${F} using the plugin callback (provider-specific writes).`)}else{let F={opencodeGeneration:x,mode:X,hosts:Object.freeze([...Z]),piAgentDir:Q.pi.directory},H=new Map;try{for(let C of Z){if(await V(),await G.beforeSignIn?.(C,F),await V(),B){H.set(C,"unknown");try{await U0(G,C,z,K,V)}catch(w){if(w instanceof I)H.set(C,"not-enrolled");throw w}H.set(C,"enrolled")}else await G.signInLocal(C,F);if(await V(),await G.beforeRegister?.(C,X,F),await V(),C==="opencode")await s(R,V);else await r(G,Q.pi.executable,z);await V(),await G.migrate(C,F)}}catch(C){if(H.size===0)throw C;try{let w=await A1(G,Z,H);b0(C,w);for(let P0 of w)O(K,G0(P0))}catch{}throw C}}return O(K,`${J.dryRun?"Planned":"Configured"} ${G.displayName} for ${Z.join(", ")} (${X}).`),O(K,`Next: ${Z.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`),{hosts:Z,dryRun:J.dryRun,mode:X,detection:Q}}import{basename as S1}from"node:path";import{resolveClaustrumConnectionPath as y1}from"@cortexkit/claustrum-client";var B0={name:"@cortexkit/pi-openai-auth",version:"1.2.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.19.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.10.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.16.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 _1}from"node:os";import{join as H0}from"node:path";function T1(){return process.env.PI_AGENT_DIR?.trim()||H0(_1(),".pi","agent")}function M0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||H0(T1(),Y0)}function P1(G=M0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||C0(G)}function N0(G=M0()){return{configPath:G,statePath:P1(G)}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.2.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.19.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.27"},dependencies:{"@cortexkit/claustrum-client":"^0.10.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.16.0","@opentui/core":">=0.6.1","@opentui/solid":">=0.6.1",ai:"^7.0.137","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};function T0(G={}){let b=G.print??console.log,z=G.fence??S(),J={opencode:{stateDir:o(A0().statePath),host:"opencode"},pi:{stateDir:o(N0().statePath),host:"pi"}},K=async(Q)=>{if(await c(P(J[Q]),f(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:B0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:y1(),hosts:{opencode:{name:f("opencode"),paths:J.opencode},pi:{name:f("pi"),paths:J.pi}}},async beforeRegister(Q,$){if($==="claustrum"){if(b(`Allow this host to read OpenAI accounts with:
13
+ ck auth grant --principal enrolled:${f(Q)} --selector-kind category --selector ${k0.category} --operation read`),Q==="opencode")b("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,$){if(await K(Q),Q==="pi"){b("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if($.opencodeGeneration!=="1"){let X=S1(k("opencode2",G.io)??k("opencode",G.io)??"opencode");b(`In OpenCode 2, run ${X} 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($.opencodeGeneration==="2")return;if(I0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let W=_0(),q={path:{id:"openai"}};if(await W.get(q)!==void 0){b("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let Z=G.beginLogin??R0,x=new AbortController,D=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),U={version:L.version,signal:x.signal},j,V=!D;try{j=await Z({...U,headless:D})}catch(X){if(D)throw X;V=!1,b("Browser callback unavailable; using device-code sign-in."),j=await Z({version:L.version,headless:!0})}if(V){if(!(G.openBrowser??w0)(j.url))x.abort(),await j.completion.catch(()=>{}),b("Browser unavailable; using device-code sign-in."),j=await Z({version:L.version,headless:!0})}b(`${j.url}
14
+ ${j.instructions}`);let B=await j.completion;await y(z),await K(Q),await W.set({...q,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(Q){b(`${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 n(T0(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}