@cortexkit/opencode-openai-auth 1.14.1 → 1.15.1

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 (87) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-Cl6zEfsR.d.ts → codex-request-DYqSE0ti.d.ts} +373 -2
  3. package/dist/{index-wma2ggn9.js → index-14x5shtc.js} +2 -2
  4. package/dist/{index-gkye2xh1.js → index-1scvhkyy.js} +2 -2
  5. package/dist/index-1wcg7g9d.js +2 -0
  6. package/dist/index-50p400eg.js +8 -0
  7. package/dist/{index-k5av4j8p.js → index-dzpjz8hv.js} +2 -2
  8. package/dist/{index-cxnrd85v.js → index-f7kmsdfk.js} +1 -1
  9. package/dist/index-fkgd5yv6.js +76 -0
  10. package/dist/{index-z9cj13z7.js → index-hnfqppx9.js} +1 -1
  11. package/dist/index-j2qfnmth.js +64 -0
  12. package/dist/{index-2f330s35.js → index-m8m7rakq.js} +2 -2
  13. package/dist/{index-94b345dw.js → index-t65axpta.js} +1 -1
  14. package/dist/{index-yygzbxjk.js → index-tes6vn59.js} +1 -1
  15. package/dist/index-xjtbg7sx.js +101 -0
  16. package/dist/index.d.ts +1 -372
  17. package/dist/index.js +1 -1
  18. package/dist/openai-auth.schema.json +400 -0
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.js +1 -1
  21. package/dist/rpc/rpc-client.js +1 -1
  22. package/dist/rpc/rpc-dir.js +1 -1
  23. package/dist/sidebar-state.js +1 -1
  24. package/dist/{token-sgwxn4xg.js → token-j34j1zhm.js} +1 -1
  25. package/dist/token-util-bf619nmg.js +1 -0
  26. package/dist/tui-preferences.js +3 -3
  27. package/dist/v2/server.d.ts +1 -1
  28. package/dist/v2/server.js +2 -2
  29. package/package.json +3 -3
  30. package/src/tui-compiled/raw/logger.js +8 -1
  31. package/src/tui-compiled/raw/shared/061e741c052de9c1-paths.js +48 -0
  32. package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +41 -18
  33. package/src/tui-compiled/raw/shared/23300c068d0b2ffc-parse.js +65 -0
  34. package/src/tui-compiled/raw/shared/3000be4f79f20eb6-write.js +88 -0
  35. package/src/tui-compiled/raw/shared/44449e891fab9fbc-edit.js +229 -0
  36. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +1 -1
  37. package/src/tui-compiled/raw/shared/5803fadb30af0ec0-descriptors.js +81 -0
  38. package/src/tui-compiled/raw/shared/58bc35a3cd459085-define.js +52 -0
  39. package/src/tui-compiled/raw/shared/5f4bc45522ab9bc6-update.js +139 -0
  40. package/src/tui-compiled/raw/shared/6948d70969aa7a55-fs.js +19 -0
  41. package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +28 -12
  42. package/src/tui-compiled/raw/shared/81758f9fe7c2a576-handle.js +228 -0
  43. package/src/tui-compiled/raw/shared/87f6e22d4fc34918-resolve.js +51 -0
  44. package/src/tui-compiled/raw/shared/8a18abe4fa2977c8-menu.js +1 -0
  45. package/src/tui-compiled/raw/shared/8ab1f5794e677151-move.js +351 -0
  46. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +9 -5
  47. package/src/tui-compiled/raw/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
  48. package/src/tui-compiled/raw/shared/cc0f2d1963547799-index.js +7 -0
  49. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +48 -5
  50. package/src/tui-compiled/raw/shared/e0ed4a490e4eaa4f-schema.js +81 -0
  51. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
  52. package/src/tui-compiled/raw/shared/eac0bed49f3d4110-lock-errors.js +15 -0
  53. package/src/tui-compiled/raw/shared/facfd8afc431d68a-refusal.js +15 -0
  54. package/src/tui-compiled/raw/shared/fc7db0c5aa764565-settings-install.js +85 -0
  55. package/src/tui-compiled/raw/shared/fcd26e77bc538838-snapshot.js +150 -0
  56. package/src/tui-compiled/runtime/logger.js +8 -1
  57. package/src/tui-compiled/runtime/shared/061e741c052de9c1-paths.js +48 -0
  58. package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +41 -18
  59. package/src/tui-compiled/runtime/shared/23300c068d0b2ffc-parse.js +65 -0
  60. package/src/tui-compiled/runtime/shared/3000be4f79f20eb6-write.js +88 -0
  61. package/src/tui-compiled/runtime/shared/44449e891fab9fbc-edit.js +229 -0
  62. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +1 -1
  63. package/src/tui-compiled/runtime/shared/5803fadb30af0ec0-descriptors.js +81 -0
  64. package/src/tui-compiled/runtime/shared/58bc35a3cd459085-define.js +52 -0
  65. package/src/tui-compiled/runtime/shared/5f4bc45522ab9bc6-update.js +139 -0
  66. package/src/tui-compiled/runtime/shared/6948d70969aa7a55-fs.js +19 -0
  67. package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +28 -12
  68. package/src/tui-compiled/runtime/shared/81758f9fe7c2a576-handle.js +228 -0
  69. package/src/tui-compiled/runtime/shared/87f6e22d4fc34918-resolve.js +51 -0
  70. package/src/tui-compiled/runtime/shared/8a18abe4fa2977c8-menu.js +1 -0
  71. package/src/tui-compiled/runtime/shared/8ab1f5794e677151-move.js +351 -0
  72. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +9 -5
  73. package/src/tui-compiled/runtime/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
  74. package/src/tui-compiled/runtime/shared/cc0f2d1963547799-index.js +7 -0
  75. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +48 -5
  76. package/src/tui-compiled/runtime/shared/e0ed4a490e4eaa4f-schema.js +81 -0
  77. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
  78. package/src/tui-compiled/runtime/shared/eac0bed49f3d4110-lock-errors.js +15 -0
  79. package/src/tui-compiled/runtime/shared/facfd8afc431d68a-refusal.js +15 -0
  80. package/src/tui-compiled/runtime/shared/fc7db0c5aa764565-settings-install.js +85 -0
  81. package/src/tui-compiled/runtime/shared/fcd26e77bc538838-snapshot.js +150 -0
  82. package/dist/index-3mbw88h7.js +0 -91
  83. package/dist/index-999nwa9p.js +0 -76
  84. package/dist/index-pc4vrrex.js +0 -2
  85. package/dist/index-snq7bwr6.js +0 -8
  86. package/dist/index-xk7f1aef.js +0 -64
  87. package/dist/token-util-8mrnmkge.js +0 -1
package/dist/bin.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{c as Q1}from"./index-yygzbxjk.js";import{Ha as a0,Ia as d,Ja as U,Ka as m,Ub as $1,kc as K1,ta as j0,ua as c,va as V0,wa as u,xa as t0,xc as X1}from"./index-999nwa9p.js";import{Od as y,Pd as r,Rd as P0,Td as l0,Ud as s,Vd as A,Wd as i0,Xd as p,Yd as U0,Zd as L0,ve as J1}from"./index-3mbw88h7.js";import"./index-snq7bwr6.js";import"./index-gkye2xh1.js";import"./index-wma2ggn9.js";import{Uf as H0,_f as B0,ag as D0,dg as Z1}from"./index-pc4vrrex.js";import"./index-2f330s35.js";import"./index-94b345dw.js";import"./index-cxnrd85v.js";import{spawn as W1}from"node:child_process";var k=4096,q1=1048576;class x0{buffer=Buffer.alloc(k);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=k){if(z.length>k||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-k),this.start=0,this.length=k;return}let J=Math.max(0,this.length+z.length-k);if(J>0)this.truncated=!0;this.start=(this.start+J)%k,this.length-=J;let $=(this.start+this.length)%k,Z=Math.min(z.length,k-$);if(z.copy(this.buffer,$,0,Z),Z<z.length)z.copy(this.buffer,0,Z);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,k-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let $=0;while($<z.length){let Z=z[$];if(Z===void 0||(Z&192)!==128)break;$++}return z.subarray($).toString("utf8")}}var T={run(z,J,$={}){return new Promise((Z)=>{let K=performance.now(),Q=$.timeoutMs??15000,G=new x0,q=[],Y=0,X=!1,W=!1,B=!1,x;try{x=W1(z,[...J],{env:$.env??process.env,windowsHide:!0,windowsVerbatimArguments:$.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let b=Q>0?setTimeout(()=>{B=!0,x.kill("SIGTERM")},Q):void 0;x.stdout?.on("data",(F)=>{let O=q1-Y,D=Math.min(O,F.length);if(D>0)q.push(F.subarray(0,D)),Y+=D;if(F.length>O)X=!0,x.kill("SIGTERM")}),x.stderr?.on("data",(F)=>G.push(F));let j=!1,H=(F,O)=>{if(j)return;if(j=!0,b)clearTimeout(b);Z({exitCode:W?1:X?1:F??1,stdout:Buffer.concat(q,Y).toString("utf8"),stderr:G.toString(),stderrTruncated:G.didTruncate,...W?{spawnError:!0}:{},signal:O??null,timedOut:B,durationMs:performance.now()-K})};x.once("error",()=>{if(W=!0,x.pid===void 0)H(null,null)}),x.once("close",(F,O)=>H(F,O))})}};function i(z,J,$,Z,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test($)){if(/["%!\r\n]/.test($)||Z.some((G)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(G)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${$}" ${Z.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run($,Z,{env:K,timeoutMs:Q})}function F0(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function E(z,J,$,Z){let K=J.requestedGrants??Z;if(!K)return;let Q=K.map((G)=>({grant:G,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${F0(`enrolled:${J.approvedName}`)} --selector-kind ${G.selector.exact===void 0?"category":"exact"} --selector ${F0(G.selector.exact??G.selector.category)} --operation ${G.operation}`}}));if(J.requestedGrantsStatus==="dropped")return{state:"older-vault",grants:Q};try{if(!z.listScoped)return{state:"unconfirmed",grants:Q};let{token:G}=await U0($),q=await z.listScoped(G),Y=Q.map((X)=>({...X,reachableLogins:q.rows.filter((W)=>W.operations.includes(X.grant.operation)&&(X.grant.selector.exact!==void 0?W.id===X.grant.selector.exact:W.categories.includes(X.grant.selector.category))).length}));return{state:Y.every((X)=>X.reachableLogins>0)?"reachable":Y.some((X)=>X.reachableLogins>0)?"partial":"no-logins",grants:Y.map((X)=>{if(X.reachableLogins===0)return X;let{grantCommand:W,...B}=X;return B})}}catch{return{state:"unconfirmed",grants:Q}}}function f(z){let J=[],$=z.grants.some((Z)=>Z.grantCommand)?"run:":"check ck auth status for the approved name before granting access.";if(z.state==="older-vault")J.push(`Approved. This vault is too old to grant access with the approval; ${$}`);else if(z.state==="no-logins")J.push(`Approved, but no logins are reachable yet; ${$}`);else if(z.state==="partial")J.push(`Approved, but some requested access has no reachable logins yet; ${$}`);else if(z.state==="unconfirmed")J.push(`Approved, but access could not be confirmed; ${z.grants.some((Z)=>Z.grantCommand)?"check ck auth status or run:":$}`);for(let{grant:Z,reachableLogins:K,grantCommand:Q}of z.grants){if(K!==void 0&&K>0){let G=Z.selector.exact===void 0?`the vault's ${JSON.stringify(Z.selector.category)} accounts`:`credential ${JSON.stringify(Z.selector.exact)}`;J.push(`Confirmed ${Z.operation} access to ${G} (${K} reachable ${K===1?"login":"logins"}).`)}if(Q)J.push(` ${Q}`)}return J}var Y1="Pi install failed; run pi install after checking your npm connection.";function B1(z){let J=Buffer.from(z,"utf8");if(J.length<=k)return z;let $=J.length-k;while($<J.length){let Z=J[$];if(Z===void 0||(Z&192)!==128)break;$++}return J.subarray($).toString("utf8")}function D1(z){let J=z.indexOf(`
3
- `);return J<0?"":z.slice(J+1)}class a extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(Y1);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?D1(z.stderrTail):z.stderrTail,$=H0(J);this.stderrTail=B1(typeof $==="string"?$:"")}}var j1={opencode:"OpenCode",pi:"Pi"},V1={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function M0({host:z,outcome:J,access:$}){return`${j1[z]}: ${V1[J]}${$?` — ${f($).join(`
4
- `)}`:""}`}var x1=new WeakMap;function O0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;x1.set(z,Object.freeze(J.map(($)=>Object.freeze({...$}))))}import{accessSync as O1,constants as C1,existsSync as R1,readFileSync as k1,realpathSync as N1,statSync as I1}from"node:fs";import{mkdtemp as _1,rm as w1}from"node:fs/promises";import{tmpdir as A1}from"node:os";import{join as T1}from"node:path";import{parse as P1}from"jsonc-parser";import{homedir as F1}from"node:os";import{posix as U1,win32 as H1}from"node:path";import{fileURLToPath as M1}from"node:url";function N(z={}){let J=z.env??process.env,$=z.platform??process.platform,Z=$==="win32"?H1:U1,K=z.home??($==="win32"?J.USERPROFILE:J.HOME)??F1(),Q=z.cwd??process.cwd(),G=(W)=>Z.resolve(Q,W),q=J.OPENCODE_CONFIG_DIR?.trim(),Y=J.XDG_CONFIG_HOME?.trim(),X=J.PI_CODING_AGENT_DIR?.trim()||Z.join(K,".pi","agent");if(X==="~")X=K;else if(/^~[/\\]/.test(X))X=Z.join(K,X.slice(2));if(X.startsWith("file://"))X=M1(X);return{env:J,platform:$,path:Z,home:K,cwd:Q,opencode:q?G(q):Y?Z.join(G(Y),"opencode"):Z.join(K,".config","opencode"),pi:G(X)}}function z0(z,J){try{return I1(z)[J]()}catch{return!1}}var P={exists:R1,isFile:(z)=>z0(z,"isFile"),isDirectory:(z)=>z0(z,"isDirectory"),isExecutable(z){try{return O1(z,C1.X_OK),z0(z,"isFile")}catch{return!1}},readText:(z)=>k1(z,"utf8"),realpath:N1};function w(z,J={}){let{env:$,platform:Z,path:K,cwd:Q}=N(J),G=J.fs??P,q=Object.entries($).find(([X])=>Z==="win32"?X.toUpperCase()==="PATH":X==="PATH")?.[1]??"",Y=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let X of q.split(Z==="win32"?";":":")){let W=X.trim().replace(/^"|"$/g,"");if(!W)continue;for(let B of Y){let x=K.resolve(Q,W,z+B);if(Z==="win32"?G.isFile(x):G.isExecutable(x))return x}}return null}function C0(z={}){let{platform:J,home:$,env:Z,path:K}=N(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",K.join($,"Applications","OpenCode.app"),K.join($,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=Z.LOCALAPPDATA||K.join($,"AppData","Local");return[K.join(Q,"Programs","opencode"),K.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",K.join($,".local","share","applications","opencode.desktop")]}function J0(z,J){let $=J.fs??P,{path:Z}=N(J);try{let K=$.readText(z);if(K.length>65536)return z;let Q=[...K.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...K.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let G=Q.at(-1)?.[1];if(G){let q=Z.join(Z.dirname(z),...G.split(/[/\\]+/));if($.isFile(q))return $.realpath(q)}return $.realpath(z)}catch{return z}}function L1(z,J){let $=J.fs??P,{path:Z}=N(J),K=Z.dirname(J0(z,J));for(;;){try{let G=JSON.parse($.readText(Z.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(G.name))return"2";if(G.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(G.version??"")?"2":"1"}catch{}let Q=Z.dirname(K);if(Q===K)return null;K=Q}}function R0(z={}){let J=w("opencode",z),$=w("opencode2",z),Z=J&&$&&J0(J,z)===J0($,z),K=z.fs??P,{path:Q,opencode:G}=N(z),q="1";for(let X of["jsonc","json"]){let W=Q.join(G,`opencode.${X}`);if(!K.exists(W))continue;try{if(Object.hasOwn(P1(K.readText(W))??{},"plugins"))q="2"}catch{}break}let Y=J?L1(J,z)??(Z?"2":q):null;if($&&Y==="1"&&!Z)return"ambiguous";return $||Z?"2":Y??q}async function Z0(z,J={}){let $=J.fs??P,{env:Z,platform:K,opencode:Q,pi:G}=N(J),q=J.runner??T,Y=w("opencode",J)??w("opencode2",J),X=w("pi",J),W=w("ck",J),B=async(H)=>{if(!H)return null;let F;try{F=await _1(T1(A1(),"common-auth-setup-version-"));let O={...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},D=await i(q,K,H,["--version"],O,2000);return D.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(D.stdout)?.[0]??null:null}catch{return null}finally{if(F)await w1(F,{recursive:!0,force:!0}).catch(()=>{})}},x=!1;if(W&&$.exists(z.vault.connectionFile))try{(await(J.connect??s)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),x=!0}catch{x=!1}let[b,j]=await Promise.all([B(Y),B(X)]);return{opencode:{installed:$.isDirectory(Q)||C0(J).some((H)=>$.exists(H))||Y!==null,executable:Y,version:b,directory:Q,generation:R0(J)},pi:{installed:X!==null||$.isDirectory(G),executable:X,version:j,directory:G},claustrum:{available:x,executable:W}}}import{setTimeout as m1}from"node:timers/promises";import{writeEnrollmentTokenFile as d1}from"@cortexkit/claustrum-client";var k0=45000,$0=new Set(["opencode","litecode","opencode2","pi"]),I0=new Set(["node","bun"]),S1=[...$0,...I0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),v1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${S1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,y1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function E1(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function N0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var f1=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"]),g1=new Set(["-e","--eval","-p","--print"]);function h1(z,J){for(let $=0;$<J.length;$++){let Z=J[$]??"";if(Z==="--")return J[$+1];if(g1.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&f1.has(Z))$++;continue}if(z==="bun"&&Z==="run")continue;return Z}return}function _0(z){let[J,...$]=E1(z);if(J===void 0)return null;let Z=N0(J);if($0.has(Z))return Z;if(!I0.has(Z))return null;let K=h1(Z,$);if(K===void 0)return null;let Q=N0(K);if($0.has(Q))return Q;return y1.test(K)?"pi":null}class C extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.exitCode=z.exitCode,this.signal=z.signal,this.timedOut=z.timedOut,this.durationMs=z.durationMs}get refusalText(){let z=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${z} after ${Math.round(this.durationMs)} ms.`}}class v extends Error{activeHosts;constructor(z){let J=z.map(($)=>({pid:$.pid,command:_0($.command)??"host"}));super(`OpenCode or Pi processes are currently running:
5
- ${J.map(($)=>` - PID ${$.pid}: ${$.command}`).join(`
2
+ import{c as G1}from"./index-tes6vn59.js";import{Aa as c,Ba as e0,Dc as W1,La as s0,Ma as p,Na as H,Oa as d,Zb as K1,pc as Q1,xa as D0,ya as l,za as V0}from"./index-fkgd5yv6.js";import{$d as i0,De as Z1,Wd as E,Xd as r,Zd as L0,ae as s,be as A,ce as a0,de as u,ee as M0,fe as S0}from"./index-xjtbg7sx.js";import"./index-50p400eg.js";import"./index-1scvhkyy.js";import"./index-14x5shtc.js";import{Ag as b0,Cg as B0,Fg as $1,ug as F0}from"./index-1wcg7g9d.js";import"./index-m8m7rakq.js";import"./index-t65axpta.js";import"./index-f7kmsdfk.js";import{spawn as q1}from"node:child_process";var k=4096,Y1=1048576;class U0{buffer=Buffer.alloc(k);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=k){if(z.length>k||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-k),this.start=0,this.length=k;return}let J=Math.max(0,this.length+z.length-k);if(J>0)this.truncated=!0;this.start=(this.start+J)%k,this.length-=J;let Z=(this.start+this.length)%k,$=Math.min(z.length,k-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,k-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var P={run(z,J,Z={}){return new Promise(($)=>{let K=performance.now(),Q=Z.timeoutMs??15000,G=new U0,j=[],B=0,X=!1,W=!1,Y=!1,V;try{V=q1(z,[...J],{env:Z.env??process.env,windowsHide:!0,windowsVerbatimArguments:Z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{$({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let q=Q>0?setTimeout(()=>{Y=!0,V.kill("SIGTERM")},Q):void 0;V.stdout?.on("data",(U)=>{let R=Y1-B,b=Math.min(R,U.length);if(b>0)j.push(U.subarray(0,b)),B+=b;if(U.length>R)X=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(U)=>G.push(U));let D=!1,x=(U,R)=>{if(D)return;if(D=!0,q)clearTimeout(q);$({exitCode:W?1:X?1:U??1,stdout:Buffer.concat(j,B).toString("utf8"),stderr:G.toString(),stderrTruncated:G.didTruncate,...W?{spawnError:!0}:{},signal:R??null,timedOut:Y,durationMs:performance.now()-K})};V.once("error",()=>{if(W=!0,V.pid===void 0)x(null,null)}),V.once("close",(U,R)=>x(U,R))})}};function i(z,J,Z,$,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((G)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(G)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:K,timeoutMs:Q})}function H0(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function f(z,J,Z,$){let K=J.requestedGrants??$;if(!K)return;let Q=K.map((j)=>({grant:j,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${H0(`enrolled:${J.approvedName}`)} --selector-kind ${j.selector.exact===void 0?"category":"exact"} --selector ${H0(j.selector.exact??j.selector.category)} --operation ${j.operation}`}})),G={grants:Q,...J.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:J.requestedGrantsStatus}};if(J.requestedGrantsStatus==="dropped")return{...G,state:"older-vault"};try{if(!z.listScoped)return{...G,state:"unconfirmed"};let{token:j}=await M0(Z),B=await z.listScoped(j),X=Q.map((W)=>({...W,reachableLogins:B.rows.filter((Y)=>Y.operations.includes(W.grant.operation)&&(W.grant.selector.exact!==void 0?Y.id===W.grant.selector.exact:Y.categories.includes(W.grant.selector.category))).length}));return{...G,state:X.every((W)=>W.reachableLogins>0)?"reachable":X.some((W)=>W.reachableLogins>0)?"partial":"no-logins",grants:X.map((W)=>{if(W.reachableLogins===0)return W;let{grantCommand:Y,...V}=W;return V})}}catch{return{...G,state:"unconfirmed"}}}function g(z,J="setup"){if(J==="plugin"&&z.requestedGrantsStatus!=="sent")return[];let Z=[],$=z.grants.some((K)=>K.grantCommand)?"run:":"check ck auth status for the approved name before granting access.";if(z.state==="older-vault")Z.push(`Approved. This vault is too old to grant access with the approval; ${$}`);else if(z.state==="no-logins")Z.push(`Approved, but no logins are reachable yet; ${$}`);else if(z.state==="partial")Z.push(`Approved, but some requested access has no reachable logins yet; ${$}`);else if(z.state==="unconfirmed")Z.push(`Approved, but access could not be confirmed; ${z.grants.some((K)=>K.grantCommand)?"check ck auth status or run:":$}`);for(let{grant:K,reachableLogins:Q,grantCommand:G}of z.grants){if(Q!==void 0&&Q>0){let j=K.selector.exact===void 0?`the vault's ${JSON.stringify(K.selector.category)} accounts`:`credential ${JSON.stringify(K.selector.exact)}`;Z.push(`Confirmed ${K.operation} access to ${j} (${Q} reachable ${Q===1?"login":"logins"}).`)}if(G)Z.push(` ${G}`)}return Z}var b1="Pi install failed; run pi install after checking your npm connection.";function B1(z){let J=Buffer.from(z,"utf8");if(J.length<=k)return z;let Z=J.length-k;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function D1(z){let J=z.indexOf(`
3
+ `);return J<0?"":z.slice(J+1)}class a extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(b1);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?D1(z.stderrTail):z.stderrTail,Z=F0(J);this.stderrTail=B1(typeof Z==="string"?Z:"")}}var V1={opencode:"OpenCode",pi:"Pi"},x1={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function O0({host:z,outcome:J,access:Z},$="setup"){let K=Z?g(Z,$):[];return`${V1[z]}: ${x1[J]}${K.length?` — ${K.join(`
4
+ `)}`:""}`}var U1=new WeakMap;function C0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;U1.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as C1,constants as R1,existsSync as N1,readFileSync as k1,realpathSync as I1,statSync as _1}from"node:fs";import{mkdtemp as w1,rm as A1}from"node:fs/promises";import{tmpdir as T1}from"node:os";import{join as P1}from"node:path";import{parse as L1}from"jsonc-parser";import{homedir as H1}from"node:os";import{posix as M1,win32 as F1}from"node:path";import{fileURLToPath as O1}from"node:url";function I(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?F1:M1,K=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??H1(),Q=z.cwd??process.cwd(),G=(W)=>$.resolve(Q,W),j=J.OPENCODE_CONFIG_DIR?.trim(),B=J.XDG_CONFIG_HOME?.trim(),X=J.PI_CODING_AGENT_DIR?.trim()||$.join(K,".pi","agent");if(X==="~")X=K;else if(/^~[/\\]/.test(X))X=$.join(K,X.slice(2));if(X.startsWith("file://"))X=O1(X);return{env:J,platform:Z,path:$,home:K,cwd:Q,opencode:j?G(j):B?$.join(G(B),"opencode"):$.join(K,".config","opencode"),pi:G(X)}}function z0(z,J){try{return _1(z)[J]()}catch{return!1}}var L={exists:N1,isFile:(z)=>z0(z,"isFile"),isDirectory:(z)=>z0(z,"isDirectory"),isExecutable(z){try{return C1(z,R1.X_OK),z0(z,"isFile")}catch{return!1}},readText:(z)=>k1(z,"utf8"),realpath:I1};function w(z,J={}){let{env:Z,platform:$,path:K,cwd:Q}=I(J),G=J.fs??L,j=Object.entries(Z).find(([X])=>$==="win32"?X.toUpperCase()==="PATH":X==="PATH")?.[1]??"",B=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let X of j.split($==="win32"?";":":")){let W=X.trim().replace(/^"|"$/g,"");if(!W)continue;for(let Y of B){let V=K.resolve(Q,W,z+Y);if($==="win32"?G.isFile(V):G.isExecutable(V))return V}}return null}function R0(z={}){let{platform:J,home:Z,env:$,path:K}=I(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",K.join(Z,"Applications","OpenCode.app"),K.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.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 J0(z,J){let Z=J.fs??L,{path:$}=I(J);try{let K=Z.readText(z);if(K.length>65536)return z;let Q=[...K.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...K.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let G=Q.at(-1)?.[1];if(G){let j=$.join($.dirname(z),...G.split(/[/\\]+/));if(Z.isFile(j))return Z.realpath(j)}return Z.realpath(z)}catch{return z}}function S1(z,J){let Z=J.fs??L,{path:$}=I(J),K=$.dirname(J0(z,J));for(;;){try{let G=JSON.parse(Z.readText($.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(G.name))return"2";if(G.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(G.version??"")?"2":"1"}catch{}let Q=$.dirname(K);if(Q===K)return null;K=Q}}function N0(z={}){let J=w("opencode",z),Z=w("opencode2",z),$=J&&Z&&J0(J,z)===J0(Z,z),K=z.fs??L,{path:Q,opencode:G}=I(z),j="1";for(let X of["jsonc","json"]){let W=Q.join(G,`opencode.${X}`);if(!K.exists(W))continue;try{if(Object.hasOwn(L1(K.readText(W))??{},"plugins"))j="2"}catch{}break}let B=J?S1(J,z)??($?"2":j):null;if(Z&&B==="1"&&!$)return"ambiguous";return Z||$?"2":B??j}async function Z0(z,J={}){let Z=J.fs??L,{env:$,platform:K,opencode:Q,pi:G}=I(J),j=J.runner??P,B=w("opencode",J)??w("opencode2",J),X=w("pi",J),W=w("ck",J),Y=async(x)=>{if(!x)return null;let U;try{U=await w1(P1(T1(),"common-auth-setup-version-"));let R={...$,HOME:U,USERPROFILE:U,XDG_CONFIG_HOME:U,XDG_DATA_HOME:U,XDG_STATE_HOME:U,XDG_CACHE_HOME:U,OPENCODE_CONFIG_DIR:U,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:U},b=await i(j,K,x,["--version"],R,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(U)await A1(U,{recursive:!0,force:!0}).catch(()=>{})}},V=!1;if(W&&Z.exists(z.vault.connectionFile))try{(await(J.connect??s)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),V=!0}catch{V=!1}let[q,D]=await Promise.all([Y(B),Y(X)]);return{opencode:{installed:Z.isDirectory(Q)||R0(J).some((x)=>Z.exists(x))||B!==null,executable:B,version:q,directory:Q,generation:N0(J)},pi:{installed:X!==null||Z.isDirectory(G),executable:X,version:D,directory:G},claustrum:{available:V,executable:W}}}import{setTimeout as d1}from"node:timers/promises";import{writeEnrollmentTokenFile as p1}from"@cortexkit/claustrum-client";var k0=45000,$0=new Set(["opencode","litecode","opencode2","pi"]),_0=new Set(["node","bun"]),v1=[...$0,..._0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),y1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${v1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,E1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function f1(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function I0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var g1=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"]),h1=new Set(["-e","--eval","-p","--print"]);function m1(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(h1.has($))return;if($.startsWith("-")){if(!$.includes("=")&&g1.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function w0(z){let[J,...Z]=f1(z);if(J===void 0)return null;let $=I0(J);if($0.has($))return $;if(!_0.has($))return null;let K=m1($,Z);if(K===void 0)return null;let Q=I0(K);if($0.has(Q))return Q;return E1.test(K)?"pi":null}class C extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.exitCode=z.exitCode,this.signal=z.signal,this.timedOut=z.timedOut,this.durationMs=z.durationMs}get refusalText(){let z=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${z} after ${Math.round(this.durationMs)} ms.`}}class y extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:w0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
5
+ ${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
6
6
  `)}
7
7
 
8
- Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function K0(z=T,J={}){let $=(J.platform??process.platform)==="win32",Z=J.selfPid??process.pid,K={step:$?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(G,q,Y,X)=>{let W=performance.now();K={step:G,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let B=await z.run(q,Y,{env:J.env,timeoutMs:X});return K={step:G,exitCode:B.exitCode,signal:B.signal??null,timedOut:B.timedOut??!1,durationMs:B.durationMs??performance.now()-W},B}finally{if(K.exitCode===null)K.durationMs=performance.now()-W;J.onStep?.({...K})}};try{if($&&J.hostImagesOnly){let X=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",v1],k0);if(X.exitCode!==0)throw new C(K);let W=JSON.parse(X.stdout);if(!W||typeof W!=="object"||!("complete"in W)||W.complete!==!0||!("processes"in W))throw new C(K);let B=W.processes,x=B===null?[]:Array.isArray(B)?B:[B],b=[];for(let j of x){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 C(K);let H=j.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(j.Name))b.push({pid:H,command:j.Name});else if(typeof j.CommandLine==="string")b.push({pid:H,command:j.CommandLine});else if(H!==Z)throw new C(K)}return b}let G=await Q($?"tasklist":"ps",$?"tasklist.exe":"ps",$?["/fo","csv","/nh"]:["-eo","pid,command"]);if(G.exitCode!==0)throw new C(K);let q=[];for(let X of G.stdout.split(/\r?\n/)){let W=X.trim();if(!W)continue;let B,x;if($){let b=/^"([^"]+)","(\d+)"(?:,|$)/.exec(W);if(!b)throw new C(K);x=b[1]??"",B=Number(b[2])}else{let b=/^(\d+)\s+(.+)$/.exec(W);if(!b){if(/^PID\s+COMMAND$/i.test(W))continue;throw new C(K)}B=Number(b[1]),x=b[2]??""}if(!Number.isSafeInteger(B)||B<0)throw new C(K);q.push({pid:B,command:x})}if(!q.length)throw new C(K);let Y=q.filter((X)=>X.pid!==Z&&/^(?:node|bun)\.exe$/i.test(X.command));if($&&Y.length&&J.inspectRuntimes!==!1){let X=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`],k0);if(X.exitCode!==0)throw new C(K);let W=JSON.parse(X.stdout||"null"),B=W===null?[]:Array.isArray(W)?W:[W],x=new Map;for(let b of B){if(!b||typeof b!=="object"||!("ProcessId"in b)||!("CommandLine"in b)||!Number.isSafeInteger(b.ProcessId))throw new C(K);if(typeof b.CommandLine==="string")x.set(Number(b.ProcessId),b.CommandLine);else if(Y.some((j)=>j.pid===b.ProcessId))throw new C(K)}for(let b of Y)b.command=x.get(b.pid)??""}return q}catch(G){if(G instanceof C)throw G;throw new C(K)}}function g(z=T,J={}){let $=J.selfPid??process.pid,Z=(K)=>K.pid!==$&&_0(K.command)!==null;return{async listRunningHosts(K){return(await K0(z,{...J,env:K,hostImagesOnly:!0})).filter(Z)},async previewRunningHosts(K){let Q=await K0(z,{...J,env:K,inspectRuntimes:!1}),G=(J.platform??process.platform)==="win32";return{hosts:Q.filter(Z),uncheckedRuntimes:G?Q.filter((q)=>q.pid!==$&&/^(?:node|bun)\.exe$/i.test(q.command)).length:0}}}}async function h(z,J){let $=await z.listRunningHosts(J);if($.length)throw new v($)}var p1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",S0='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.',v0=300000,w0=1000,A0=[1000,2000,4000,8000,16000,30000];function Q0(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class _ extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=Q0(J.lastErrorCode)}}function T0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function y0(z,J,$,Z,K){if(r())throw Error(y);let{name:Q,displayName:G,requestedGrants:q,paths:Y}=z.vault.hosts[J],X=A(Y);await K();let W=await($.connect??s)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new _("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),B=$.now??(()=>performance.now()),x=$.wait??m1;try{let b=new L0({proposedName:Q,displayName:G,requestedGrants:q,paths:X,client:W,writeTokenFile:async(V,R)=>{await K(),await d1(V,R)}});await K();let j=await b.status();if(j.state==="approved"){U(Z,`Already connected as ${j.approvedName??j.proposedName}.`);let V=await E(W,j,X.tokenPath,q);if(V)for(let R of f(V))U(Z,R);return V}U(Z,`Asking the vault to connect ${Q}…`);let H=B()+v0,F,O,D,M=0;for(;;){let V=await b.reconcile();if(V.state==="approved"){U(Z,`Connected ${J} to Claustrum.`);let S=await E(W,V,X.tokenPath,q);if(S)for(let b1 of f(S))U(Z,b1);return S}if(V.state==="unavailable"&&V.code===P0)throw new _(S0,{reason:"unsupported-vault",lastErrorCode:V.code});if(V.state!=="pending"&&V.state!=="busy")throw new _("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in V&&{lastErrorCode:V.code}});let R=w0;if(V.state==="busy")O="busy";else if(V.retryCode)O=V.retryCode;if(V.state==="pending"&&V.requestId){if(M=0,V.requestId!==F){if(!/^[a-zA-Z0-9_-]+$/.test(V.requestId))throw new _("Invalid enrollment request id.",{reason:"invalid-request"});F=V.requestId,U(Z,"Waiting for approval. In another terminal, run:"),U(Z,` ${T0(V.requestId,Q)}`),U(Z,`Enrollment files: ${X.statePath}, ${X.tokenPath}`)}}else if(V.state==="pending"&&V.retryCode){R=A0[Math.min(M,A0.length-1)]??w0,M++;let S=Q0(V.retryCode);if(S!==D)D=S,U(Z,`The vault has not created the request yet (${S}); retrying.`)}let l=H-B();if(l<=0)break;await x(Math.min(R,l)),await K()}if(F)throw new _(`Claustrum approval is still pending. In another terminal, run: ${T0(F,Q)} and then rerun setup.`,{reason:"approval-pending",...O!==void 0&&{lastErrorCode:O}});let I=Q0(O);throw new _(`The vault never created the enrollment request (last error: ${I}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:I})}catch(b){if(b instanceof v||b instanceof C||b instanceof _)throw b;let j=b?.code;throw new _(p1,{reason:"incomplete",...typeof j==="string"&&{lastErrorCode:j}})}finally{W.close()}}var E0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",u1=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function o(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function f0(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let $=0;$<z.length;$++){let Z=z[$],K=Z.indexOf("="),Q=K===-1?Z:Z.slice(0,K),G=u1.find((Y)=>Y.name===Q);if(!G)throw o(Z);if(!("values"in G)){if(K!==-1)throw o(Z);J[G.key]=!0;continue}let q;if(K!==-1)q=Z.slice(K+1);else if(G.spaceForm)q=z[++$];else throw o(Z);if(q===void 0||!G.values.includes(q))throw G.invalid?Error(G.invalid):o(Z);if(G.key==="hosts")J.hosts.push(q);else J.opencode=q}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function g0(z,J){let $=new Set(J);for(;;){let Z=await m(z,[...["opencode","pi"].map((K)=>({value:K,label:`[${$.has(K)?"x":" "}] ${K==="opencode"?"OpenCode":"Pi"}`,hint:J.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(Z===null)return null;if(Z==="done")return[...$];if($.has(Z))$.delete(Z);else $.add(Z)}}import{domainToUnicode as z2}from"node:url";import{applyEdits as G0,createScanner as J2,findNodeAtLocation as Z2,modify as m0,parse as $2,parseTree as K2}from"jsonc-parser";import{randomUUID as c1}from"node:crypto";import{mkdir as l1,open as i1,rename as a1,stat as s1,unlink as r1}from"node:fs/promises";import{basename as o1,dirname as n1,join as t1}from"node:path";import{setTimeout as e1}from"node:timers/promises";async function h0(z,J,$={}){let Z=($.platform??process.platform)==="win32",K=n1(z);await l1(K,{recursive:!0});let Q;if(!Z)try{Q=(await s1(z)).mode&4095}catch(Y){if(Y.code!=="ENOENT")throw Y}let G=t1(K,`.${o1(z)}.${($.stageName??c1)()}.tmp`),q=!1;try{let Y=await i1(G,"wx",Q??438);q=!0;try{if(await Y.writeFile(J,"utf8"),Q!==void 0)await Y.chmod(Q)}finally{await Y.close()}let X=$.now??(()=>performance.now()),W=X();for(let B=0;;B++){await $.beforeRename?.();try{await($.rename??a1)(G,z),q=!1;return}catch(x){let b=x.code,j=2000-(X()-W);if(!Z||!["EPERM","EBUSY","EACCES"].includes(b??"")||j<=0||B>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await($.wait??e1)(Math.min(j,25*2**Math.min(B,2)))}}}finally{if(q)await r1(G).catch(()=>{})}}function p0(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function X0(z){let J=p0(z);if(J===null)return null;let $=J.indexOf("@",J.startsWith("@")?1:0);return $<0?J:J.slice(0,$)}function Q2(z,J){let $=new URL(z);if(/%2f/i.test($.pathname)||J&&/%5c/i.test($.pathname))throw Error("Encoded path separators are not valid in a file URL.");let Z=decodeURIComponent($.pathname);if(!J){if($.hostname)throw Error("A POSIX file URL must be local.");return Z}let K=Z.replaceAll("/","\\");if($.hostname)return`\\\\${z2($.hostname)}${K}`;if(!/^\\[a-z]:/i.test(K))throw Error("A Windows file URL must have an absolute drive path.");return K.slice(1)}function G2(z,J,$){let{path:Z,platform:K}=N($);try{let Q=/^file:\/\//i.test(z)?Q2(z,K==="win32"):Z.isAbsolute(z)||z.startsWith(".")?Z.resolve(Z.dirname(J),z):null;if(Q===null)return null;let G=JSON.parse(($.fs??P).readText(Z.join(Q,"package.json")));return G&&typeof G==="object"&&"name"in G&&typeof G.name==="string"?G.name:null}catch{return null}}function u0(z,J){let $=[],Z=$2(z,$,{allowTrailingComma:!0});if($.length||!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid OpenCode config; refusing to overwrite it.");if(Z[J]!==void 0&&!Array.isArray(Z[J]))throw Error(`OpenCode ${J} must be an array.`);return Z}function d0(z,J,$){let Z=K2(z),K=Z&&Z2(Z,[J]),Q=K?.children??[],G=Q[$];if(!G||!K)throw Error("Invalid plugin array edit.");let q=[{offset:G.offset,length:G.length,content:""}],Y=(X,W)=>{let B=J2(z.slice(X,W),!0);if(B.scan(),z[X+B.getTokenOffset()]===",")q.push({offset:X+B.getTokenOffset(),length:1,content:""})};if($===Q.length-1){let X=Q[$-1];if(X)Y(X.offset+X.length,G.offset);Y(G.offset+G.length,K.offset+K.length-1)}else Y(G.offset+G.length,Q[$+1]?.offset??G.offset+G.length);return G0(z,q)}function c0(z,J,$,Z){let K=u0(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
8
+ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function K0(z=P,J={}){let Z=(J.platform??process.platform)==="win32",$=J.selfPid??process.pid,K={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(G,j,B,X)=>{let W=performance.now();K={step:G,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let Y=await z.run(j,B,{env:J.env,timeoutMs:X});return K={step:G,exitCode:Y.exitCode,signal:Y.signal??null,timedOut:Y.timedOut??!1,durationMs:Y.durationMs??performance.now()-W},Y}finally{if(K.exitCode===null)K.durationMs=performance.now()-W;J.onStep?.({...K})}};try{if(Z&&J.hostImagesOnly){let X=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",y1],k0);if(X.exitCode!==0)throw new C(K);let W=JSON.parse(X.stdout);if(!W||typeof W!=="object"||!("complete"in W)||W.complete!==!0||!("processes"in W))throw new C(K);let Y=W.processes,V=Y===null?[]:Array.isArray(Y)?Y:[Y],q=[];for(let D of V){if(!D||typeof D!=="object"||!("Name"in D)||typeof D.Name!=="string"||!("ProcessId"in D)||!Number.isSafeInteger(D.ProcessId)||D.ProcessId<0||!("CommandLine"in D))throw new C(K);let x=D.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(D.Name))q.push({pid:x,command:D.Name});else if(typeof D.CommandLine==="string")q.push({pid:x,command:D.CommandLine});else if(x!==$)throw new C(K)}return q}let G=await Q(Z?"tasklist":"ps",Z?"tasklist.exe":"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(G.exitCode!==0)throw new C(K);let j=[];for(let X of G.stdout.split(/\r?\n/)){let W=X.trim();if(!W)continue;let Y,V;if(Z){let q=/^"([^"]+)","(\d+)"(?:,|$)/.exec(W);if(!q)throw new C(K);V=q[1]??"",Y=Number(q[2])}else{let q=/^(\d+)\s+(.+)$/.exec(W);if(!q){if(/^PID\s+COMMAND$/i.test(W))continue;throw new C(K)}Y=Number(q[1]),V=q[2]??""}if(!Number.isSafeInteger(Y)||Y<0)throw new C(K);j.push({pid:Y,command:V})}if(!j.length)throw new C(K);let B=j.filter((X)=>X.pid!==$&&/^(?:node|bun)\.exe$/i.test(X.command));if(Z&&B.length&&J.inspectRuntimes!==!1){let X=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`],k0);if(X.exitCode!==0)throw new C(K);let W=JSON.parse(X.stdout||"null"),Y=W===null?[]:Array.isArray(W)?W:[W],V=new Map;for(let q of Y){if(!q||typeof q!=="object"||!("ProcessId"in q)||!("CommandLine"in q)||!Number.isSafeInteger(q.ProcessId))throw new C(K);if(typeof q.CommandLine==="string")V.set(Number(q.ProcessId),q.CommandLine);else if(B.some((D)=>D.pid===q.ProcessId))throw new C(K)}for(let q of B)q.command=V.get(q.pid)??""}return j}catch(G){if(G instanceof C)throw G;throw new C(K)}}function h(z=P,J={}){let Z=J.selfPid??process.pid,$=(K)=>K.pid!==Z&&w0(K.command)!==null;return{async listRunningHosts(K){return(await K0(z,{...J,env:K,hostImagesOnly:!0})).filter($)},async previewRunningHosts(K){let Q=await K0(z,{...J,env:K,inspectRuntimes:!1}),G=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:G?Q.filter((j)=>j.pid!==Z&&/^(?:node|bun)\.exe$/i.test(j.command)).length:0}}}}async function m(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new y(Z)}var u1="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.',y0=300000,A0=1000,T0=[1000,2000,4000,8000,16000,30000];function Q0(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class _ extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=Q0(J.lastErrorCode)}}function P0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function E0(z,J,Z,$,K){if(r())throw Error(E);let{name:Q,displayName:G,requestedGrants:j,grantFallback:B,paths:X}=z.vault.hosts[J],W=A(X);await K();let Y=await(Z.connect??s)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new _("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),V=Z.now??(()=>performance.now()),q=Z.wait??d1;try{let D=new S0({proposedName:Q,displayName:G,requestedGrants:j,paths:W,client:Y,writeTokenFile:async(M,T)=>{await K(),await p1(M,T)}});await K();let x=await D.status();if(x.state==="approved"){H($,`Already connected as ${x.approvedName??x.proposedName}.`);let M=await f(Y,x,W.tokenPath,j);if(M)for(let T of g(M,B))H($,T);return M}H($,`Asking the vault to connect ${Q}…`);let U=V()+y0,R,b,F,N=0;for(;;){let M=await D.reconcile();if(M.state==="approved"){H($,`Connected ${J} to Claustrum.`);let v=await f(Y,M,W.tokenPath,j);if(v)for(let j1 of g(v,B))H($,j1);return v}if(M.state==="unavailable"&&M.code===L0)throw new _(v0,{reason:"unsupported-vault",lastErrorCode:M.code});if(M.state!=="pending"&&M.state!=="busy")throw new _("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in M&&{lastErrorCode:M.code}});let T=A0;if(M.state==="busy")b="busy";else if(M.retryCode)b=M.retryCode;if(M.state==="pending"&&M.requestId){if(N=0,M.requestId!==R){if(!/^[a-zA-Z0-9_-]+$/.test(M.requestId))throw new _("Invalid enrollment request id.",{reason:"invalid-request"});R=M.requestId,H($,"Waiting for approval. In another terminal, run:"),H($,` ${P0(M.requestId,Q)}`),H($,`Enrollment files: ${W.statePath}, ${W.tokenPath}`)}}else if(M.state==="pending"&&M.retryCode){T=T0[Math.min(N,T0.length-1)]??A0,N++;let v=Q0(M.retryCode);if(v!==F)F=v,H($,`The vault has not created the request yet (${v}); retrying.`)}let x0=U-V();if(x0<=0)break;await q(Math.min(T,x0)),await K()}if(R)throw new _(`Claustrum approval is still pending. In another terminal, run: ${P0(R,Q)} and then rerun setup.`,{reason:"approval-pending",...b!==void 0&&{lastErrorCode:b}});let O=Q0(b);throw new _(`The vault never created the enrollment request (last error: ${O}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:O})}catch(D){if(D instanceof y||D instanceof C||D instanceof _)throw D;let x=D?.code;throw new _(u1,{reason:"incomplete",...typeof x==="string"&&{lastErrorCode:x}})}finally{Y.close()}}var f0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",c1=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function o(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function g0(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let Z=0;Z<z.length;Z++){let $=z[Z],K=$.indexOf("="),Q=K===-1?$:$.slice(0,K),G=c1.find((B)=>B.name===Q);if(!G)throw o($);if(!("values"in G)){if(K!==-1)throw o($);J[G.key]=!0;continue}let j;if(K!==-1)j=$.slice(K+1);else if(G.spaceForm)j=z[++Z];else throw o($);if(j===void 0||!G.values.includes(j))throw G.invalid?Error(G.invalid):o($);if(G.key==="hosts")J.hosts.push(j);else J.opencode=j}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function h0(z,J){let Z=new Set(J);for(;;){let $=await d(z,[...["opencode","pi"].map((K)=>({value:K,label:`[${Z.has(K)?"x":" "}] ${K==="opencode"?"OpenCode":"Pi"}`,hint:J.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($===null)return null;if($==="done")return[...Z];if(Z.has($))Z.delete($);else Z.add($)}}import{domainToUnicode as J2}from"node:url";import{applyEdits as G0,createScanner as Z2,findNodeAtLocation as $2,modify as d0,parse as K2,parseTree as Q2}from"jsonc-parser";import{randomUUID as l1}from"node:crypto";import{mkdir as i1,open as a1,rename as s1,stat as r1,unlink as o1}from"node:fs/promises";import{basename as n1,dirname as t1,join as e1}from"node:path";import{setTimeout as z2}from"node:timers/promises";async function m0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",K=t1(z);await i1(K,{recursive:!0});let Q;if(!$)try{Q=(await r1(z)).mode&4095}catch(B){if(B.code!=="ENOENT")throw B}let G=e1(K,`.${n1(z)}.${(Z.stageName??l1)()}.tmp`),j=!1;try{let B=await a1(G,"wx",Q??438);j=!0;try{if(await B.writeFile(J,"utf8"),Q!==void 0)await B.chmod(Q)}finally{await B.close()}let X=Z.now??(()=>performance.now()),W=X();for(let Y=0;;Y++){await Z.beforeRename?.();try{await(Z.rename??s1)(G,z),j=!1;return}catch(V){let q=V.code,D=2000-(X()-W);if(!$||!["EPERM","EBUSY","EACCES"].includes(q??"")||D<=0||Y>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??z2)(Math.min(D,25*2**Math.min(Y,2)))}}}finally{if(j)await o1(G).catch(()=>{})}}function u0(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function X0(z){let J=u0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function G2(z,J){let Z=new URL(z);if(/%2f/i.test(Z.pathname)||J&&/%5c/i.test(Z.pathname))throw Error("Encoded path separators are not valid in a file URL.");let $=decodeURIComponent(Z.pathname);if(!J){if(Z.hostname)throw Error("A POSIX file URL must be local.");return $}let K=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${J2(Z.hostname)}${K}`;if(!/^\\[a-z]:/i.test(K))throw Error("A Windows file URL must have an absolute drive path.");return K.slice(1)}function X2(z,J,Z){let{path:$,platform:K}=I(Z);try{let Q=/^file:\/\//i.test(z)?G2(z,K==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let G=JSON.parse((Z.fs??L).readText($.join(Q,"package.json")));return G&&typeof G==="object"&&"name"in G&&typeof G.name==="string"?G.name:null}catch{return null}}function c0(z,J){let Z=[],$=K2(z,Z,{allowTrailingComma:!0});if(Z.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");if($[J]!==void 0&&!Array.isArray($[J]))throw Error(`OpenCode ${J} must be an array.`);return $}function p0(z,J,Z){let $=Q2(z),K=$&&$2($,[J]),Q=K?.children??[],G=Q[Z];if(!G||!K)throw Error("Invalid plugin array edit.");let j=[{offset:G.offset,length:G.length,content:""}],B=(X,W)=>{let Y=Z2(z.slice(X,W),!0);if(Y.scan(),z[X+Y.getTokenOffset()]===",")j.push({offset:X+Y.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let X=Q[Z-1];if(X)B(X.offset+X.length,G.offset);B(G.offset+G.length,K.offset+K.length-1)}else B(G.offset+G.length,Q[Z+1]?.offset??G.offset+G.length);return G0(z,j)}function l0(z,J,Z,$){let K=c0(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
9
9
  `)?`\r
10
10
  `:`
11
- `}},G=z,q=K[J],Y=Array.isArray(q)?[...q]:[],X=Y.flatMap((x,b)=>X0(x)===$?[b]:[]),W=`${$}@${Z}`;if(!X.length)G=G0(G,m0(G,q===void 0?[J]:[J,Y.length],q===void 0?[W]:W,Q));else{let x=X[0],b=Y[x],j=Array.isArray(b)?[W,...b.slice(1)]:b&&typeof b==="object"?{...b,package:W}:W;if(JSON.stringify(b)!==JSON.stringify(j))G=G0(G,m0(G,[J,x],j,Q));for(let H of X.slice(1).reverse())G=d0(G,J,H)}let B=J==="plugin"?"plugins":"plugin";if(Array.isArray(K[B])){let x=K[B];for(let b=x.length-1;b>=0;b--)if(X0(x[b])===$)G=d0(G,B,b)}return G}function b0(z,J,$={}){let Z=$.fs??P,{path:K,opencode:Q}=N($),G=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((Y)=>{let X=K.join(Q,`${Y}.jsonc`),W=K.join(Q,`${Y}.json`),B=Z.exists(X)?X:Z.exists(W)?W:X,x=Z.exists(B),b=x?Z.readText(B):`${JSON.stringify({$schema:`https://opencode.ai/${Y==="tui"?"tui":"config"}.json`},null,2)}
12
- `,j=u0(b,G),H=[],F=[];for(let D of["plugin","plugins"]){if(!Array.isArray(j[D]))continue;for(let M of j[D]){let I=p0(M);if(I===null)continue;if(G2(I,B,$)===z.packages.opencode)H.push(JSON.stringify(M));else if(X0(M)===z.packages.opencode)F.push(JSON.stringify(M))}}if(H.length>0)return{path:B,content:b,changed:!1,existingLocalEntries:H,existingNpmEntries:F};let O=c0(b,G,z.packages.opencode,z.version);return{path:B,content:O,changed:!x||O!==b}})}async function W0(z,J){for(let $ of z){if(!$.changed)continue;await J?.(),await h0($.path,$.content,{beforeRename:J})}}async function q0(z,J,$={}){let{platform:Z,env:K}=N($),Q=await i($.runner??T,Z,J,["install",`npm:${z.packages.pi}@${z.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new a({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var s0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function X2(z){for(let J of Object.values(z.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(J))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(z.version))throw Error("Setup requires a concrete package version.");for(let J of Object.values(z.vault.hosts)){if(!/^[a-z0-9][a-z0-9-]*$/.test(J.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.");if(J.requestedGrants!==void 0&&!l0(J.requestedGrants))throw Error("invalid Claustrum enrollment requested grants")}}async function b2(z,J,$,Z){let K=[];for(let Q of J){let G=$.get(Q)??"not-enrolled",q=Z.get(Q);if(G==="unknown"){let{name:Y,paths:X}=z.vault.hosts[Q],W=await p(A(X),Y).catch(()=>"unreadable");if(W==="vault"||W==="host")G="enrolled";else if(W==="local")G="not-enrolled";if(G==="enrolled"){let B=await i0(A(X),Y).catch(()=>{return});if(B?.state==="approved")q=await E({},B,A(X).tokenPath,z.vault.hosts[Q].requestedGrants)}}K.push({host:Q,outcome:G,...q&&{access:q}})}return K}async function Y0(z,J=[],$={}){let Z=f0(J);if(r())throw Error(y);X2(z);let K=$.terminal??a0(),Q=await Z0(z,$);U(K,`${z.displayName} setup`);for(let[D,M]of[["OpenCode",Q.opencode],["Pi",Q.pi]])U(K,`${D}: ${M.installed?`found (version ${M.version??"unknown"})`:"not found"} — ${M.directory}`);U(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let G=Q.pi.installed&&!Q.pi.executable;if(G)U(K,"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((D)=>Q[D].installed&&!(D==="pi"&&G));if(Z.hosts.some((D)=>!q.includes(D)))throw Error(E0);let Y=Z.yes||Z.dryRun&&!d(K);if(!Y&&!d(K))throw Error("Setup requires a TTY or --yes.");let X=Z.hosts.length?q.filter((D)=>Z.hosts.includes(D)):Y?q:await g0(K,q)??[],W=Z.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(X.includes("opencode")&&!Z.opencode&&Q.opencode.generation==="ambiguous"){if(Y||!d(K))throw Error(s0);let D=await m(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(D===null)return{hosts:[],dryRun:Z.dryRun,mode:"local",detection:Q};W=D}if(!X.length)return U(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:X,dryRun:Z.dryRun,mode:"local",detection:Q};let{env:B,platform:x}=N($),b=$.fence??g($.runner??T,{platform:x}),j=async()=>{try{await h(b,B)}catch(D){if(D instanceof C)U(K,D.refusalText);throw D}};if(U(K,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let D=b.previewRunningHosts?await b.previewRunningHosts(B):{hosts:await b.listRunningHosts(B),uncheckedRuntimes:0},M=D.hosts;if(D.uncheckedRuntimes>0)U(K,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let I=new Set(new v(M).activeHosts.map((V)=>V.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let V of I)U(K,`${V} is running; setup will ask you to quit it.`)}catch(D){if(U(K,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),D instanceof C)U(K,D.refusalText)}else await j();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 H=Z.claustrum||Z.enrollOnly;if(!H&&!Z.login&&!Z.noClaustrum&&!Y&&Q.claustrum.available&&d(K)){let D=await m(K,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(D===null)return U(K,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:Q};H=D===!0}let F=H?"claustrum":"local",O=!Z.enrollOnly&&X.includes("opencode")?b0(z,W,$):[];for(let D of O){for(let I of D.existingLocalEntries??[])U(K,`OpenCode: already registered from ${I} in ${D.path}.`);let M=[...D.existingLocalEntries??[],...D.existingNpmEntries??[]];if(M.length>1)U(K,`Warning: ${z.displayName} may load twice in ${D.path}: ${M.join(", ")}. Entries were left unchanged.`)}if(Z.dryRun){U(K,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let D of X){if(z.beforeSignIn)U(K,`Would run beforeSignIn(${D}, ${F}).`);if(H){let M=A(z.vault.hosts[D].paths);U(K,`Would Connect ${D}: write ${M.statePath} and ${M.tokenPath}; wait for ck auth enroll approve.`)}else U(K,`Would sign in locally for ${D}.`);if(!Z.enrollOnly&&z.beforeRegister)U(K,`Would run beforeRegister(${D}, ${F}).`)}for(let D of O)U(K,`${D.changed?"Would write":"Unchanged"} ${D.path}:
13
- ${D.content}`);if(!Z.enrollOnly&&X.includes("pi"))U(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!Z.enrollOnly&&z.migrate)for(let D of X)U(K,`Would migrate ${D} using the plugin callback (provider-specific writes).`)}else{let D={opencodeGeneration:W,mode:F,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},M=new Map,I=new Map;try{for(let V of X){if(await j(),await z.beforeSignIn?.(V,D),await j(),H){M.set(V,"unknown");try{let R=await y0(z,V,$,K,j);if(R)I.set(V,R)}catch(R){if(R instanceof _)M.set(V,"not-enrolled");throw R}M.set(V,"enrolled")}else await z.signInLocal(V,D);if(await j(),Z.enrollOnly)continue;if(await z.beforeRegister?.(V,F,D),await j(),V==="opencode")await W0(O,j);else await q0(z,Q.pi.executable,$);await j(),await z.migrate?.(V,D)}}catch(V){if(M.size===0)throw V;try{let R=await b2(z,X,M,I);O0(V,R);for(let l of R)U(K,M0(l))}catch{}throw V}}if(U(K,`${Z.dryRun?"Planned":Z.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${F}).`),Z.enrollOnly)U(K,`Enroll-only: no host config or plugin registration ${Z.dryRun?"will be":"was"} written.`),U(K,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else U(K,`Next: ${X.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:X,dryRun:Z.dryRun,mode:F,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.14.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.44.0","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.1.0","@opencode/plugin":"2.2.6"},dependencies:{"@cortexkit/claustrum-client":"^0.18.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.8.3","@opentui/solid":">=0.8.3",ai:"^7.0.165","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as j2}from"node:path";import{resolveClaustrumConnectionPath as V2}from"@cortexkit/claustrum-client";var r0={name:"@cortexkit/pi-openai-auth",version:"1.14.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.44.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.18.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as n}from"node:fs";import{homedir as t}from"node:os";import{join as e,resolve as o0}from"node:path";import{fileURLToPath as Y2}from"node:url";var n0=new Set;function B2(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return e(t(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return t();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return e(t(),z.slice(2));return z.startsWith("file://")?Y2(z):z}function e0(z=B2()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let $=e(z,B0),Z=e(t(),".pi","agent",B0),K=(G)=>{let q=D0(G),Y=t0(u(q),"pi");return n(G)||n(q)||n(Y.tokenPath)||n(Y.statePath)};if(o0($)===o0(Z)||K($)||!K(Z))return $;let Q=`${$}\x00${Z}`;if(!n0.has(Q))n0.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${Z} (${$} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return Z}function D2(z=e0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||D0(z)}function z1(z=e0()){return{configPath:z,statePath:D2(z)}}function G1(z={}){let J=z.print??console.log,$=z.fence??g(),Z={opencode:{stateDir:u($1().statePath),host:"opencode"},pi:{stateDir:u(z1().statePath),host:"pi"}},K=async(Q)=>{let G=await p(A(Z[Q]),c(Q));if(G==="host")throw Error(y);if(G!=="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:r0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:V2(),hosts:{opencode:{name:c("opencode"),displayName:V0("opencode"),requestedGrants:j0,paths:Z.opencode},pi:{name:c("pi"),displayName:V0("pi"),requestedGrants:j0,paths:Z.pi}}},async beforeRegister(Q,G){if(await p(A(Z[Q]),c(Q))==="host")throw Error(y);if(G==="claustrum"){if(Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,G){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(G.opencodeGeneration!=="1"){let F=j2(w("opencode2",z.io)??w("opencode",z.io)??"opencode");J(`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(G.opencodeGeneration==="2")return;if(K1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let q=Q1(),Y={path:{id:"openai"}};if(await q.get(Y)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??J1,W=new AbortController,B=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),x={version:L.version,signal:W.signal},b,j=!B;try{b=await X({...x,headless:B})}catch(F){if(B)throw F;j=!1,J("Browser callback unavailable; using device-code sign-in."),b=await X({version:L.version,headless:!0})}if(j){if(!(z.openBrowser??Z1)(b.url))W.abort(),await b.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),b=await X({version:L.version,headless:!0})}J(`${b.url}
14
- ${b.instructions}`);let H=await b.completion;await h($),await K(Q),await q.set({...Y,body:{type:"oauth",access:H.access,refresh:H.refresh,expires:H.expires,...H.accountId?{accountId:H.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await X1({version:L.version}),await Y0(G1(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
11
+ `}},G=z,j=K[J],B=Array.isArray(j)?[...j]:[],X=B.flatMap((V,q)=>X0(V)===Z?[q]:[]),W=`${Z}@${$}`;if(!X.length)G=G0(G,d0(G,j===void 0?[J]:[J,B.length],j===void 0?[W]:W,Q));else{let V=X[0],q=B[V],D=Array.isArray(q)?[W,...q.slice(1)]:q&&typeof q==="object"?{...q,package:W}:W;if(JSON.stringify(q)!==JSON.stringify(D))G=G0(G,d0(G,[J,V],D,Q));for(let x of X.slice(1).reverse())G=p0(G,J,x)}let Y=J==="plugin"?"plugins":"plugin";if(Array.isArray(K[Y])){let V=K[Y];for(let q=V.length-1;q>=0;q--)if(X0(V[q])===Z)G=p0(G,Y,q)}return G}function W0(z,J,Z={}){let $=Z.fs??L,{path:K,opencode:Q}=I(Z),G=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((B)=>{let X=K.join(Q,`${B}.jsonc`),W=K.join(Q,`${B}.json`),Y=$.exists(X)?X:$.exists(W)?W:X,V=$.exists(Y),q=V?$.readText(Y):`${JSON.stringify({$schema:`https://opencode.ai/${B==="tui"?"tui":"config"}.json`},null,2)}
12
+ `,D=c0(q,G),x=[],U=[];for(let b of["plugin","plugins"]){if(!Array.isArray(D[b]))continue;for(let F of D[b]){let N=u0(F);if(N===null)continue;if(X2(N,Y,Z)===z.packages.opencode)x.push(JSON.stringify(F));else if(X0(F)===z.packages.opencode)U.push(JSON.stringify(F))}}if(x.length>0)return{path:Y,content:q,changed:!1,existingLocalEntries:x,existingNpmEntries:U};let R=l0(q,G,z.packages.opencode,z.version);return{path:Y,content:R,changed:!V||R!==q}})}async function j0(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await m0(Z.path,Z.content,{beforeRename:J})}}async function q0(z,J,Z={}){let{platform:$,env:K}=I(Z),Q=await i(Z.runner??P,$,J,["install",`npm:${z.packages.pi}@${z.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new a({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var r0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function W2(z){for(let J of Object.values(z.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(J))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(z.version))throw Error("Setup requires a concrete package version.");for(let J of Object.values(z.vault.hosts)){if(!/^[a-z0-9][a-z0-9-]*$/.test(J.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.");if(J.requestedGrants!==void 0&&!i0(J.requestedGrants))throw Error("invalid Claustrum enrollment requested grants");if(J.grantFallback!==void 0&&J.grantFallback!=="setup"&&J.grantFallback!=="plugin")throw Error("invalid Claustrum enrollment grant fallback")}}async function j2(z,J,Z,$){let K=[];for(let Q of J){let G=Z.get(Q)??"not-enrolled",j=$.get(Q);if(G==="unknown"){let{name:B,paths:X}=z.vault.hosts[Q],W=await u(A(X),B).catch(()=>"unreadable");if(W==="vault"||W==="host")G="enrolled";else if(W==="local")G="not-enrolled";if(G==="enrolled"){let Y=await a0(A(X),B).catch(()=>{return});if(Y?.state==="approved")j=await f({},Y,A(X).tokenPath,z.vault.hosts[Q].requestedGrants)}}K.push({host:Q,outcome:G,...j&&{access:j}})}return K}async function Y0(z,J=[],Z={}){let $=g0(J);if(r())throw Error(E);W2(z);let K=Z.terminal??s0(),Q=await Z0(z,Z);H(K,`${z.displayName} setup`);for(let[b,F]of[["OpenCode",Q.opencode],["Pi",Q.pi]])H(K,`${b}: ${F.installed?`found (version ${F.version??"unknown"})`:"not found"} — ${F.directory}`);H(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let G=Q.pi.installed&&!Q.pi.executable;if(G)H(K,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let j=["opencode","pi"].filter((b)=>Q[b].installed&&!(b==="pi"&&G));if($.hosts.some((b)=>!j.includes(b)))throw Error(f0);let B=$.yes||$.dryRun&&!p(K);if(!B&&!p(K))throw Error("Setup requires a TTY or --yes.");let X=$.hosts.length?j.filter((b)=>$.hosts.includes(b)):B?j:await h0(K,j)??[],W=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(X.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(B||!p(K))throw Error(r0);let b=await d(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(b===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};W=b}if(!X.length)return H(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:X,dryRun:$.dryRun,mode:"local",detection:Q};let{env:Y,platform:V}=I(Z),q=Z.fence??h(Z.runner??P,{platform:V}),D=async()=>{try{await m(q,Y)}catch(b){if(b instanceof C)H(K,b.refusalText);throw b}};if(H(K,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let b=q.previewRunningHosts?await q.previewRunningHosts(Y):{hosts:await q.listRunningHosts(Y),uncheckedRuntimes:0},F=b.hosts;if(b.uncheckedRuntimes>0)H(K,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let N=new Set(new y(F).activeHosts.map((O)=>O.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let O of N)H(K,`${O} is running; setup will ask you to quit it.`)}catch(b){if(H(K,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof C)H(K,b.refusalText)}else await D();if(($.claustrum||$.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let x=$.claustrum||$.enrollOnly;if(!x&&!$.login&&!$.noClaustrum&&!B&&Q.claustrum.available&&p(K)){let b=await d(K,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(b===null)return H(K,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};x=b===!0}let U=x?"claustrum":"local",R=!$.enrollOnly&&X.includes("opencode")?W0(z,W,Z):[];for(let b of R){for(let N of b.existingLocalEntries??[])H(K,`OpenCode: already registered from ${N} in ${b.path}.`);let F=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(F.length>1)H(K,`Warning: ${z.displayName} may load twice in ${b.path}: ${F.join(", ")}. Entries were left unchanged.`)}if($.dryRun){H(K,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of X){if(z.beforeSignIn)H(K,`Would run beforeSignIn(${b}, ${U}).`);if(x){let F=A(z.vault.hosts[b].paths);H(K,`Would Connect ${b}: write ${F.statePath} and ${F.tokenPath}; wait for ck auth enroll approve.`)}else H(K,`Would sign in locally for ${b}.`);if(!$.enrollOnly&&z.beforeRegister)H(K,`Would run beforeRegister(${b}, ${U}).`)}for(let b of R)H(K,`${b.changed?"Would write":"Unchanged"} ${b.path}:
13
+ ${b.content}`);if(!$.enrollOnly&&X.includes("pi"))H(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let b of X)H(K,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:W,mode:U,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},F=new Map,N=new Map;try{for(let O of X){if(await D(),await z.beforeSignIn?.(O,b),await D(),x){F.set(O,"unknown");try{let M=await E0(z,O,Z,K,D);if(M)N.set(O,M)}catch(M){if(M instanceof _)F.set(O,"not-enrolled");throw M}F.set(O,"enrolled")}else await z.signInLocal(O,b);if(await D(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,U,b),await D(),O==="opencode")await j0(R,D);else await q0(z,Q.pi.executable,Z);await D(),await z.migrate?.(O,b)}}catch(O){if(F.size===0)throw O;try{let M=await j2(z,X,F,N);C0(O,M);for(let T of M)H(K,O0(T,z.vault.hosts[T.host].grantFallback))}catch{}throw O}}if(H(K,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${U}).`),$.enrollOnly)H(K,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),H(K,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else H(K,`Next: ${X.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:X,dryRun:$.dryRun,mode:U,detection:Q}}var S={name:"@cortexkit/opencode-openai-auth",version:"1.15.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","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.45.0","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.1.0","@opencode/plugin":"2.2.6"},dependencies:{"@cortexkit/claustrum-client":"^0.18.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.8.3","@opentui/solid":">=0.8.3",ai:"^7.0.165","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as V2}from"node:path";import{resolveClaustrumConnectionPath as x2}from"@cortexkit/claustrum-client";var o0={name:"@cortexkit/pi-openai-auth",version:"1.15.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","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.45.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.18.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","jsonc-parser":"^3.3.1"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as n}from"node:fs";import{homedir as t}from"node:os";import{join as e,resolve as n0}from"node:path";import{fileURLToPath as b2}from"node:url";var t0=new Set;function B2(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return e(t(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return t();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return e(t(),z.slice(2));return z.startsWith("file://")?b2(z):z}function z1(z=B2()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=e(z,b0),$=e(t(),".pi","agent",b0),K=(G)=>{let j=B0(G),B=e0(c(j),"pi");return n(G)||n(j)||n(B.tokenPath)||n(B.statePath)};if(n0(Z)===n0($)||K(Z)||!K($))return Z;let Q=`${Z}\x00${$}`;if(!t0.has(Q))t0.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${$} (${Z} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return $}function D2(z=z1()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||B0(z)}function J1(z=z1()){return{configPath:z,statePath:D2(z)}}function X1(z={}){let J=z.print??console.log,Z=z.fence??h(),$={opencode:{stateDir:c(K1().statePath),host:"opencode"},pi:{stateDir:c(J1().statePath),host:"pi"}},K=async(Q)=>{let G=await u(A($[Q]),l(Q));if(G==="host")throw Error(E);if(G!=="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:S.name,pi:o0.name},version:S.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:x2(),hosts:{opencode:{name:l("opencode"),displayName:V0("opencode"),requestedGrants:D0,paths:$.opencode},pi:{name:l("pi"),displayName:V0("pi"),requestedGrants:D0,paths:$.pi}}},async beforeRegister(Q,G){if(await u(A($[Q]),l(Q))==="host")throw Error(E);if(G==="claustrum"){if(Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,G){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(G.opencodeGeneration!=="1"){let U=V2(w("opencode2",z.io)??w("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${U} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(G.opencodeGeneration==="2")return;if(Q1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let j=G1(),B={path:{id:"openai"}};if(await j.get(B)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??Z1,W=new AbortController,Y=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),V={version:S.version,signal:W.signal},q,D=!Y;try{q=await X({...V,headless:Y})}catch(U){if(Y)throw U;D=!1,J("Browser callback unavailable; using device-code sign-in."),q=await X({version:S.version,headless:!0})}if(D){if(!(z.openBrowser??$1)(q.url))W.abort(),await q.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),q=await X({version:S.version,headless:!0})}J(`${q.url}
14
+ ${q.instructions}`);let x=await q.completion;await m(Z),await K(Q),await j.set({...B,body:{type:"oauth",access:x.access,refresh:x.refresh,expires:x.expires,...x.accountId?{accountId:x.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await W1({version:S.version}),await Y0(X1(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}