@cortexkit/opencode-openai-auth 1.17.0 → 1.18.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.
- package/dist/bin.js +8 -8
- package/dist/{codex-request-DYqSE0ti.d.ts → codex-request-CTIOw2EZ.d.ts} +322 -322
- package/dist/index-177kc3f1.js +64 -0
- package/dist/{index-k2f9vrcr.js → index-1r7zznds.js} +1 -1
- package/dist/{index-0mhdyzax.js → index-2ecf254a.js} +21 -21
- package/dist/index-5czcaan0.js +101 -0
- package/dist/index-5vh4jgb7.js +12 -0
- package/dist/index-96p0myg1.js +2 -0
- package/dist/{index-1m3vv9rh.js → index-9sh2xnwr.js} +2 -2
- package/dist/{index-d7bsrp0m.js → index-h7xxfm12.js} +1 -1
- package/dist/{index-vmcmpezd.js → index-hrv1msdb.js} +1 -1
- package/dist/index-m6sq5g7q.js +8 -0
- package/dist/{index-99c2fepe.js → index-nkgxq9a6.js} +1 -1
- package/dist/{index-fxqghceg.js → index-raj3tyyz.js} +1 -1
- package/dist/{index-6ts9w66n.js → index-rs8z3per.js} +1 -1
- package/dist/index-smekt6zv.js +2 -0
- package/dist/index.d.ts +24 -24
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-r3vbz9pw.js → token-kdjmv82a.js} +1 -1
- package/dist/token-util-71r7z2vr.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +3 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +9 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +1 -1
- package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +3 -1
- package/src/tui-compiled/raw/shared/44449e891fab9fbc-edit.js +48 -2
- package/src/tui-compiled/raw/shared/54eba94fd64c8c3c-index.js +1 -1
- package/src/tui-compiled/raw/shared/5f4bc45522ab9bc6-update.js +19 -18
- package/src/tui-compiled/raw/shared/6948d70969aa7a55-fs.js +1 -0
- package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +14 -4
- package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +1 -1
- package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +55 -49
- package/src/tui-compiled/raw/shared/cf4c37f3975c3a8d-canonical-file-path.js +57 -0
- package/src/tui-compiled/raw/shared/ec971142548df90e-index.js +3 -0
- package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +9 -2
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +1 -1
- package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +3 -1
- package/src/tui-compiled/runtime/shared/44449e891fab9fbc-edit.js +48 -2
- package/src/tui-compiled/runtime/shared/54eba94fd64c8c3c-index.js +1 -1
- package/src/tui-compiled/runtime/shared/5f4bc45522ab9bc6-update.js +19 -18
- package/src/tui-compiled/runtime/shared/6948d70969aa7a55-fs.js +1 -0
- package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +14 -4
- package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +1 -1
- package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +55 -49
- package/src/tui-compiled/runtime/shared/cf4c37f3975c3a8d-canonical-file-path.js +57 -0
- package/src/tui-compiled/runtime/shared/ec971142548df90e-index.js +3 -0
- package/dist/index-3dv16qvb.js +0 -101
- package/dist/index-dqxk628t.js +0 -12
- package/dist/index-rm4zt5dv.js +0 -64
- package/dist/index-v9p38mg5.js +0 -2
- package/dist/index-xx2z6bs3.js +0 -2
- package/dist/index-ydtpn6ma.js +0 -8
- package/dist/token-util-vks3kgse.js +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
3
|
-
`);return J<0?"":z.slice(J+1)}class
|
|
4
|
-
`)}`:""}`}var
|
|
2
|
+
import{c as j1}from"./index-rs8z3per.js";import{$b as X1,Aa as a,Ba as Z1,Fc as Y1,La as n0,Ma as l,Na as U,Oa as u,rc as G1,xa as F0,ya as s,za as M0}from"./index-2ecf254a.js";import{$d as E0,Fe as Q1,Yd as g,Zd as e,be as o0,ce as n,de as A,ee as r0,fe as i,ge as C0,he as y0}from"./index-5czcaan0.js";import"./index-m6sq5g7q.js";import"./index-smekt6zv.js";import"./index-5vh4jgb7.js";import{Ag as x0,Cg as U0,Fg as W1}from"./index-1r7zznds.js";import{Hg as R0}from"./index-9sh2xnwr.js";import"./index-96p0myg1.js";import"./index-hrv1msdb.js";import"./index-h7xxfm12.js";import{spawn as b1}from"node:child_process";var N=4096,B1=1048576;class O0{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=N){if(z.length>N||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-N),this.start=0,this.length=N;return}let J=Math.max(0,this.length+z.length-N);if(J>0)this.truncated=!0;this.start=(this.start+J)%N,this.length-=J;let Z=(this.start+this.length)%N,$=Math.min(z.length,N-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,N-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var w={run(z,J,Z={}){return new Promise(($)=>{let K=performance.now(),Q=Z.timeoutMs??15000,W=new O0,G=[],V=0,X=!1,j=!1,b=!1,x;try{x=b1(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 Y=Q>0?setTimeout(()=>{b=!0,x.kill("SIGTERM")},Q):void 0;x.stdout?.on("data",(q)=>{let F=B1-V,I=Math.min(F,q.length);if(I>0)G.push(q.subarray(0,I)),V+=I;if(q.length>F)X=!0,x.kill("SIGTERM")}),x.stderr?.on("data",(q)=>W.push(q));let H=!1,B=(q,F)=>{if(H)return;if(H=!0,Y)clearTimeout(Y);$({exitCode:j?1:X?1:q??1,stdout:Buffer.concat(G,V).toString("utf8"),stderr:W.toString(),stderrTruncated:W.didTruncate,...j?{spawnError:!0}:{},signal:F??null,timedOut:b,durationMs:performance.now()-K})};x.once("error",()=>{if(j=!0,x.pid===void 0)B(null,null)}),x.once("close",(q,F)=>B(q,F))})}};function o(z,J,Z,$,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((W)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(W)))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 I0(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function h(z,J,Z,$){let K=J.requestedGrants??$;if(!K)return;let Q=K.map((G)=>({grant:G,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${I0(`enrolled:${J.approvedName}`)} --selector-kind ${G.selector.exact===void 0?"category":"exact"} --selector ${I0(G.selector.exact??G.selector.category)} --operation ${G.operation}`}})),W={grants:Q,...J.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:J.requestedGrantsStatus}};if(J.requestedGrantsStatus==="dropped")return{...W,state:"older-vault"};try{if(!z.listScoped)return{...W,state:"unconfirmed"};let{token:G}=await C0(Z),V=await z.listScoped(G),X=Q.map((j)=>({...j,reachableLogins:V.rows.filter((b)=>b.operations.includes(j.grant.operation)&&(j.grant.selector.exact!==void 0?b.id===j.grant.selector.exact:b.categories.includes(j.grant.selector.category))).length}));return{...W,state:X.every((j)=>j.reachableLogins>0)?"reachable":X.some((j)=>j.reachableLogins>0)?"partial":"no-logins",grants:X.map((j)=>{if(j.reachableLogins===0)return j;let{grantCommand:b,...x}=j;return x})}}catch{return{...W,state:"unconfirmed"}}}function m(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:W}of z.grants){if(Q!==void 0&&Q>0){let G=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 ${G} (${Q} reachable ${Q===1?"login":"logins"}).`)}if(W)Z.push(` ${W}`)}return Z}var V1="Pi install failed; run pi install after checking your npm connection.";function x1(z){let J=Buffer.from(z,"utf8");if(J.length<=N)return z;let Z=J.length-N;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function U1(z){let J=z.indexOf(`
|
|
3
|
+
`);return J<0?"":z.slice(J+1)}class r extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(V1);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?U1(z.stderrTail):z.stderrTail,Z=R0(J);this.stderrTail=x1(typeof Z==="string"?Z:"")}}var F1={opencode:"OpenCode",pi:"Pi"},M1={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function N0({host:z,outcome:J,access:Z},$="setup"){let K=Z?m(Z,$):[];return`${F1[z]}: ${M1[J]}${K.length?` — ${K.join(`
|
|
4
|
+
`)}`:""}`}var H1=new WeakMap;function k0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;H1.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as N1,constants as k1,existsSync as _1,readFileSync as T1,realpathSync as P1,statSync as A1}from"node:fs";import{mkdtemp as L1,rm as w1}from"node:fs/promises";import{tmpdir as S1}from"node:os";import{join as v1}from"node:path";import{parse as E1}from"jsonc-parser";import{homedir as O1}from"node:os";import{posix as I1,win32 as C1}from"node:path";import{fileURLToPath as R1}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?C1:I1,K=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??O1(),Q=z.cwd??process.cwd(),W=(j)=>$.resolve(Q,j),G=J.OPENCODE_CONFIG_DIR?.trim(),V=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=R1(X);return{env:J,platform:Z,path:$,home:K,cwd:Q,opencode:G?W(G):V?$.join(W(V),"opencode"):$.join(K,".config","opencode"),pi:W(X)}}function K0(z,J){try{return A1(z)[J]()}catch{return!1}}var S={exists:_1,isFile:(z)=>K0(z,"isFile"),isDirectory:(z)=>K0(z,"isDirectory"),isExecutable(z){try{return N1(z,k1.X_OK),K0(z,"isFile")}catch{return!1}},readText:(z)=>T1(z,"utf8"),realpath:P1};function P(z,J={}){let{env:Z,platform:$,path:K,cwd:Q}=k(J),W=J.fs??S,G=Object.entries(Z).find(([X])=>$==="win32"?X.toUpperCase()==="PATH":X==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let X of G.split($==="win32"?";":":")){let j=X.trim().replace(/^"|"$/g,"");if(!j)continue;for(let b of V){let x=K.resolve(Q,j,z+b);if($==="win32"?W.isFile(x):W.isExecutable(x))return x}}return null}function _0(z={}){let{platform:J,home:Z,env:$,path:K}=k(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 Q0(z,J){let Z=J.fs??S,{path:$}=k(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 W=Q.at(-1)?.[1];if(W){let G=$.join($.dirname(z),...W.split(/[/\\]+/));if(Z.isFile(G))return Z.realpath(G)}return Z.realpath(z)}catch{return z}}function y1(z,J){let Z=J.fs??S,{path:$}=k(J),K=$.dirname(Q0(z,J));for(;;){try{let W=JSON.parse(Z.readText($.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(W.name))return"2";if(W.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(W.version??"")?"2":"1"}catch{}let Q=$.dirname(K);if(Q===K)return null;K=Q}}function T0(z={}){let J=P("opencode",z),Z=P("opencode2",z),$=J&&Z&&Q0(J,z)===Q0(Z,z),K=z.fs??S,{path:Q,opencode:W}=k(z),G="1";for(let X of["jsonc","json"]){let j=Q.join(W,`opencode.${X}`);if(!K.exists(j))continue;try{if(Object.hasOwn(E1(K.readText(j))??{},"plugins"))G="2"}catch{}break}let V=J?y1(J,z)??($?"2":G):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??G}async function W0(z,J={}){let Z=J.fs??S,{env:$,platform:K,opencode:Q,pi:W}=k(J),G=J.runner??w,V=P("opencode",J)??P("opencode2",J),X=P("pi",J),j=P("ck",J),b=async(B)=>{if(!B)return null;let q;try{q=await L1(v1(S1(),"common-auth-setup-version-"));let F={...$,HOME:q,USERPROFILE:q,XDG_CONFIG_HOME:q,XDG_DATA_HOME:q,XDG_STATE_HOME:q,XDG_CACHE_HOME:q,OPENCODE_CONFIG_DIR:q,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:q},I=await o(G,K,B,["--version"],F,2000);return I.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(I.stdout)?.[0]??null:null}catch{return null}finally{if(q)await w1(q,{recursive:!0,force:!0}).catch(()=>{})}},x=!1;if(j&&Z.exists(z.vault.connectionFile))try{(await(J.connect??n)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),x=!0}catch{x=!1}let[Y,H]=await Promise.all([b(V),b(X)]);return{opencode:{installed:Z.isDirectory(Q)||_0(J).some((B)=>Z.exists(B))||V!==null,executable:V,version:Y,directory:Q,generation:T0(J)},pi:{installed:X!==null||Z.isDirectory(W),executable:X,version:H,directory:W},claustrum:{available:x,executable:j}}}import{setTimeout as s1}from"node:timers/promises";import{writeEnrollmentTokenFile as o1}from"@cortexkit/claustrum-client";import{statSync as f1}from"node:fs";import{win32 as t}from"node:path";var g1=45000,h1=90000;function m1(z){try{return f1(z).isFile()}catch{return!1}}function d(z,J){return Object.entries(z).find(([Z])=>Z.toUpperCase()===J.toUpperCase())?.[1]}var X0=new Set(["opencode","litecode","opencode2","pi"]),A0=new Set(["node","bun"]),d1=[...X0,...A0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),p1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${d1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,c1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function u1(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function P0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var l1=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"]),i1=new Set(["-e","--eval","-p","--print"]);function a1(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(i1.has($))return;if($.startsWith("-")){if(!$.includes("=")&&l1.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function L0(z){let[J,...Z]=u1(z);if(J===void 0)return null;let $=P0(J);if(X0.has($))return $;if(!A0.has($))return null;let K=a1($,Z);if(K===void 0)return null;let Q=P0(K);if(X0.has(Q))return Q;return c1.test(K)?"pi":null}class R extends Error{code="process-inspection-failed";step;program;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.program=z.program,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:L0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
|
|
5
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=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
|
|
8
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function G0(z=w,J={}){let Z=(J.platform??process.platform)==="win32",$=J.env??process.env,K=Z?t.resolve(d($,"SystemRoot")??d($,"windir")??"C:\\Windows","System32"):"",Q=J.selfPid??process.pid,W={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},G=async(X,j,b,x,Y)=>{let H=performance.now();W={step:X,...Y&&{program:Y},exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let B=await z.run(j,b,{env:J.env,timeoutMs:x});return W={step:X,...Y&&{program:Y},exitCode:B.exitCode,signal:B.signal??null,timedOut:B.timedOut??!1,durationMs:B.durationMs??performance.now()-H},B}finally{if(W.exitCode===null)W.durationMs=performance.now()-H;J.onStep?.({...W})}},V=(X)=>{let j=t.resolve(d($,"ProgramFiles")??"C:\\Program Files","PowerShell","7","pwsh.exe"),b=(J.isFile??m1)(j)?"pwsh":"powershell",x=(d($,"PROCESSOR_ARCHITEW6432")??d($,"PROCESSOR_ARCHITECTURE"))?.toUpperCase()==="ARM64",Y=b==="powershell"&&x;if(Y)J.onProgress?.("Checking that OpenCode and Pi are not running. Without PowerShell 7 this can take up to a minute on Windows ARM; installing PowerShell 7 makes it fast.");return G("CIM",b==="pwsh"?j:t.resolve(K,"WindowsPowerShell","v1.0","powershell.exe"),X,Y?h1:g1,b)};try{if(Z&&J.hostImagesOnly){let x=await V(["-NoProfile","-NonInteractive","-Command",p1]);if(x.exitCode!==0)throw new R(W);let Y=JSON.parse(x.stdout);if(!Y||typeof Y!=="object"||!("complete"in Y)||Y.complete!==!0||!("processes"in Y))throw new R(W);let H=Y.processes,B=H===null?[]:Array.isArray(H)?H:[H],q=[];for(let F of B){if(!F||typeof F!=="object"||!("Name"in F)||typeof F.Name!=="string"||!("ProcessId"in F)||!Number.isSafeInteger(F.ProcessId)||F.ProcessId<0||!("CommandLine"in F))throw new R(W);let I=F.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(F.Name))q.push({pid:I,command:F.Name});else if(typeof F.CommandLine==="string")q.push({pid:I,command:F.CommandLine});else if(I!==Q)throw new R(W)}return q}let X=await G(Z?"tasklist":"ps",Z?t.resolve(K,"tasklist.exe"):"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(X.exitCode!==0)throw new R(W);let j=[];for(let x of X.stdout.split(/\r?\n/)){let Y=x.trim();if(!Y)continue;let H,B;if(Z){let q=/^"([^"]+)","(\d+)"(?:,|$)/.exec(Y);if(!q)throw new R(W);B=q[1]??"",H=Number(q[2])}else{let q=/^(\d+)\s+(.+)$/.exec(Y);if(!q){if(/^PID\s+COMMAND$/i.test(Y))continue;throw new R(W)}H=Number(q[1]),B=q[2]??""}if(!Number.isSafeInteger(H)||H<0)throw new R(W);j.push({pid:H,command:B})}if(!j.length)throw new R(W);let b=j.filter((x)=>x.pid!==Q&&/^(?:node|bun)\.exe$/i.test(x.command));if(Z&&b.length&&J.inspectRuntimes!==!1){let x=await V(["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`]);if(x.exitCode!==0)throw new R(W);let Y=JSON.parse(x.stdout||"null"),H=Y===null?[]:Array.isArray(Y)?Y:[Y],B=new Map;for(let q of H){if(!q||typeof q!=="object"||!("ProcessId"in q)||!("CommandLine"in q)||!Number.isSafeInteger(q.ProcessId))throw new R(W);if(typeof q.CommandLine==="string")B.set(Number(q.ProcessId),q.CommandLine);else if(b.some((F)=>F.pid===q.ProcessId))throw new R(W)}for(let q of b)q.command=B.get(q.pid)??""}return j}catch(X){if(X instanceof R)throw X;throw new R(W)}}function p(z=w,J={}){let Z=J.selfPid??process.pid,$=(K)=>K.pid!==Z&&L0(K.command)!==null;return{async listRunningHosts(K){return(await G0(z,{...J,env:K,hostImagesOnly:!0})).filter($)},async previewRunningHosts(K){let Q=await G0(z,{...J,env:K,inspectRuntimes:!1}),W=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:W?Q.filter((G)=>G.pid!==Z&&/^(?:node|bun)\.exe$/i.test(G.command)).length:0}}}}async function c(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new y(Z)}class f{inspect;now;#z;constructor(z,J=()=>performance.now()){this.inspect=z,this.now=J}async check(z={}){if(z.reuse&&this.#z!==void 0){let J=this.now()-this.#z;if(J>=0&&J<5000)return}this.#z=void 0,await this.inspect(),this.#z=this.now()}async step(z){this.#z=void 0;try{return await z()}finally{this.#z=void 0}}}var r1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",f0='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.',g0=300000,w0=1000,S0=[1000,2000,4000,8000,16000,30000];function j0(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=j0(J.lastErrorCode)}}function v0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function h0(z,J,Z,$,K){if(e())throw Error(g);let{name:Q,displayName:W,requestedGrants:G,grantFallback:V,paths:X}=z.vault.hosts[J],j=A(X),b=typeof K==="function"?new f(K,Z.now):K;await b.check({reuse:!0});let x=await(Z.connect??n)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new _("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),Y=Z.now??(()=>performance.now()),H=Z.wait??s1;try{let B=new y0({proposedName:Q,displayName:W,requestedGrants:G,paths:j,client:x,writeTokenFile:async(M,L)=>{await b.check(),await b.step(()=>o1(M,L))}}),q=await B.status();if(q.state==="approved"){U($,`Already connected as ${q.approvedName??q.proposedName}.`);let M=await h(x,q,j.tokenPath,G);if(M)for(let L of m(M,V))U($,L);return M}U($,`Asking the vault to connect ${Q}…`);let F=Y()+g0,I,D,O,T=0;for(;;){await b.check({reuse:!0});let M=await b.step(()=>B.reconcile());if(M.state==="approved"){U($,`Connected ${J} to Claustrum.`);let E=await h(x,M,j.tokenPath,G);if(E)for(let D1 of m(E,V))U($,D1);return E}if(M.state==="unavailable"&&M.code===E0)throw new _(f0,{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 L=w0;if(M.state==="busy")D="busy";else if(M.retryCode)D=M.retryCode;if(M.state==="pending"&&M.requestId){if(T=0,M.requestId!==I){if(!/^[a-zA-Z0-9_-]+$/.test(M.requestId))throw new _("Invalid enrollment request id.",{reason:"invalid-request"});I=M.requestId,U($,"Waiting for approval. In another terminal, run:"),U($,` ${v0(M.requestId,Q)}`),U($,`Enrollment files: ${j.statePath}, ${j.tokenPath}`)}}else if(M.state==="pending"&&M.retryCode){L=S0[Math.min(T,S0.length-1)]??w0,T++;let E=j0(M.retryCode);if(E!==O)O=E,U($,`The vault has not created the request yet (${E}); retrying.`)}let H0=F-Y();if(H0<=0)break;await b.step(()=>H(Math.min(L,H0))),await b.check()}if(I)throw new _(`Claustrum approval is still pending. In another terminal, run: ${v0(I,Q)} and then rerun setup.`,{reason:"approval-pending",...D!==void 0&&{lastErrorCode:D}});let C=j0(D);throw new _(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(B){if(B instanceof y||B instanceof R||B instanceof _)throw B;let q=B?.code;throw new _(r1,{reason:"incomplete",...typeof q==="string"&&{lastErrorCode:q}})}finally{x.close()}}var m0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",n1=[{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 z0(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function d0(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),W=n1.find((V)=>V.name===Q);if(!W)throw z0($);if(!("values"in W)){if(K!==-1)throw z0($);J[W.key]=!0;continue}let G;if(K!==-1)G=$.slice(K+1);else if(W.spaceForm)G=z[++Z];else throw z0($);if(G===void 0||!W.values.includes(G))throw W.invalid?Error(W.invalid):z0($);if(W.key==="hosts")J.hosts.push(G);else J.opencode=G}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 p0(z,J){let Z=new Set(J);for(;;){let $=await u(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{rename as G2}from"node:fs/promises";import{setTimeout as j2}from"node:timers/promises";import{domainToUnicode as q2}from"node:url";import{applyEdits as q0,createScanner as Y2,findNodeAtLocation as D2,modify as u0,parse as b2,parseTree as B2}from"jsonc-parser";import{randomUUID as t1}from"node:crypto";import{mkdir as e1,open as z2,rename as J2,stat as Z2,unlink as $2}from"node:fs/promises";import{basename as K2,dirname as Q2,join as W2}from"node:path";import{setTimeout as X2}from"node:timers/promises";async function c0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",K=Q2(z);await e1(K,{recursive:!0});let Q;if(!$)try{Q=(await Z2(z)).mode&4095}catch(V){if(V.code!=="ENOENT")throw V}let W=W2(K,`.${K2(z)}.${(Z.stageName??t1)()}.tmp`),G=!1;try{let V=await z2(W,"wx",Q??438);G=!0;try{if(await V.writeFile(J,"utf8"),Q!==void 0)await V.chmod(Q)}finally{await V.close()}let X=Z.now??(()=>performance.now()),j=X();for(let b=0;;b++){await Z.beforeRename?.();try{await(Z.rename??J2)(W,z),G=!1;return}catch(x){let Y=x.code,H=2000-(X()-j);if(!$||!["EPERM","EBUSY","EACCES"].includes(Y??"")||H<=0||b>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??X2)(Math.min(H,25*2**Math.min(b,2)))}}}finally{if(G)await $2(W).catch(()=>{})}}function i0(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 Y0(z){let J=i0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function V2(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`\\\\${q2(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}=k(Z);try{let Q=/^file:\/\//i.test(z)?V2(z,K==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let W=JSON.parse((Z.fs??S).readText($.join(Q,"package.json")));return W&&typeof W==="object"&&"name"in W&&typeof W.name==="string"?W.name:null}catch{return null}}function a0(z,J){let Z=[],$=b2(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 l0(z,J,Z){let $=B2(z),K=$&&D2($,[J]),Q=K?.children??[],W=Q[Z];if(!W||!K)throw Error("Invalid plugin array edit.");let G=[{offset:W.offset,length:W.length,content:""}],V=(X,j)=>{let b=Y2(z.slice(X,j),!0);if(b.scan(),z[X+b.getTokenOffset()]===",")G.push({offset:X+b.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let X=Q[Z-1];if(X)V(X.offset+X.length,W.offset);V(W.offset+W.length,K.offset+K.length-1)}else V(W.offset+W.length,Q[Z+1]?.offset??W.offset+W.length);return q0(z,G)}function s0(z,J,Z,$){let K=a0(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
|
-
`}},
|
|
12
|
-
`,
|
|
13
|
-
${
|
|
14
|
-
${
|
|
11
|
+
`}},W=z,G=K[J],V=Array.isArray(G)?[...G]:[],X=V.flatMap((x,Y)=>Y0(x)===Z?[Y]:[]),j=`${Z}@${$}`;if(!X.length)W=q0(W,u0(W,G===void 0?[J]:[J,V.length],G===void 0?[j]:j,Q));else{let x=X[0],Y=V[x],H=Array.isArray(Y)?[j,...Y.slice(1)]:Y&&typeof Y==="object"?{...Y,package:j}:j;if(JSON.stringify(Y)!==JSON.stringify(H))W=q0(W,u0(W,[J,x],H,Q));for(let B of X.slice(1).reverse())W=l0(W,J,B)}let b=J==="plugin"?"plugins":"plugin";if(Array.isArray(K[b])){let x=K[b];for(let Y=x.length-1;Y>=0;Y--)if(Y0(x[Y])===Z)W=l0(W,b,Y)}return W}function D0(z,J,Z={}){let $=Z.fs??S,{path:K,opencode:Q}=k(Z),W=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((V)=>{let X=K.join(Q,`${V}.jsonc`),j=K.join(Q,`${V}.json`),b=$.exists(X)?X:$.exists(j)?j:X,x=$.exists(b),Y=x?$.readText(b):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
|
|
12
|
+
`,H=a0(Y,W),B=[],q=[];for(let I of["plugin","plugins"]){if(!Array.isArray(H[I]))continue;for(let D of H[I]){let O=i0(D);if(O===null)continue;if(x2(O,b,Z)===z.packages.opencode)B.push(JSON.stringify(D));else if(Y0(D)===z.packages.opencode)q.push(JSON.stringify(D))}}if(B.length>0)return{path:b,content:Y,changed:!1,existingLocalEntries:B,existingNpmEntries:q};let F=s0(Y,W,z.packages.opencode,z.version);return{path:b,content:F,changed:!x||F!==Y}})}async function b0(z,J){let Z=typeof J==="function"?new f(J):J;for(let $ of z){if(!$.changed)continue;await c0($.path,$.content,{beforeRename:Z?()=>Z.check({reuse:!0}):void 0,rename:Z?(K,Q)=>Z.step(()=>G2(K,Q)):void 0,wait:Z?(K)=>Z.step(()=>j2(K)):void 0})}}async function B0(z,J,Z={}){let{platform:$,env:K}=k(Z),Q=await o(Z.runner??w,$,J,["install",`npm:${z.packages.pi}@${z.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new r({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var t0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function U2(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&&!o0(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 F2(z,J,Z,$){let K=[];for(let Q of J){let W=Z.get(Q)??"not-enrolled",G=$.get(Q);if(W==="unknown"){let{name:V,paths:X}=z.vault.hosts[Q],j=await i(A(X),V).catch(()=>"unreadable");if(j==="vault"||j==="host")W="enrolled";else if(j==="local")W="not-enrolled";if(W==="enrolled"){let b=await r0(A(X),V).catch(()=>{return});if(b?.state==="approved")G=await h({},b,A(X).tokenPath,z.vault.hosts[Q].requestedGrants)}}K.push({host:Q,outcome:W,...G&&{access:G}})}return K}async function V0(z,J=[],Z={}){let $=d0(J);if(e())throw Error(g);U2(z);let K=Z.terminal??n0(),Q=await W0(z,Z);U(K,`${z.displayName} setup`);for(let[D,O]of[["OpenCode",Q.opencode],["Pi",Q.pi]])U(K,`${D}: ${O.installed?`found (version ${O.version??"unknown"})`:"not found"} — ${O.directory}`);U(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let W=Q.pi.installed&&!Q.pi.executable;if(W)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 G=["opencode","pi"].filter((D)=>Q[D].installed&&!(D==="pi"&&W));if($.hosts.some((D)=>!G.includes(D)))throw Error(m0);let V=$.yes||$.dryRun&&!l(K);if(!V&&!l(K))throw Error("Setup requires a TTY or --yes.");let X=$.hosts.length?G.filter((D)=>$.hosts.includes(D)):V?G:await p0(K,G)??[],j=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(X.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(V||!l(K))throw Error(t0);let D=await u(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:$.dryRun,mode:"local",detection:Q};j=D}if(!X.length)return U(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:X,dryRun:$.dryRun,mode:"local",detection:Q};let{env:b,platform:x}=k(Z),Y=Z.fence??p(Z.runner??w,{platform:x,isFile:Z.fs?.isFile.bind(Z.fs),onProgress:(D)=>U(K,D)}),B=new f(async()=>{try{await c(Y,b)}catch(D){if(D instanceof R)U(K,D.refusalText);throw D}},Z.now);if(U(K,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let D=Y.previewRunningHosts?await Y.previewRunningHosts(b):{hosts:await Y.listRunningHosts(b),uncheckedRuntimes:0},O=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 T=new Set(new y(O).activeHosts.map((C)=>C.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let C of T)U(K,`${C} 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 R)U(K,D.refusalText)}else await B.check();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 q=$.claustrum||$.enrollOnly;if(!q&&!$.login&&!$.noClaustrum&&!V&&Q.claustrum.available&&l(K)){let D=await B.step(()=>u(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:$.dryRun,mode:"local",detection:Q};q=D===!0}let F=q?"claustrum":"local",I=!$.enrollOnly&&X.includes("opencode")?D0(z,j,Z):[];for(let D of I){for(let T of D.existingLocalEntries??[])U(K,`OpenCode: already registered from ${T} in ${D.path}.`);let O=[...D.existingLocalEntries??[],...D.existingNpmEntries??[]];if(O.length>1)U(K,`Warning: ${z.displayName} may load twice in ${D.path}: ${O.join(", ")}. Entries were left unchanged.`)}if($.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(q){let O=A(z.vault.hosts[D].paths);U(K,`Would Connect ${D}: write ${O.statePath} and ${O.tokenPath}; wait for ck auth enroll approve.`)}else U(K,`Would sign in locally for ${D}.`);if(!$.enrollOnly&&z.beforeRegister)U(K,`Would run beforeRegister(${D}, ${F}).`)}for(let D of I)U(K,`${D.changed?"Would write":"Unchanged"} ${D.path}:
|
|
13
|
+
${D.content}`);if(!$.enrollOnly&&X.includes("pi"))U(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let D of X)U(K,`Would migrate ${D} using the plugin callback (provider-specific writes).`)}else{let D={opencodeGeneration:j,mode:F,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},O=new Map,T=new Map;try{for(let C of X){if(z.beforeSignIn)await B.check({reuse:!0}),await B.step(()=>z.beforeSignIn?.(C,D));if(q){O.set(C,"unknown");try{let M=await h0(z,C,Z,K,B);if(M)T.set(C,M)}catch(M){if(M instanceof _)O.set(C,"not-enrolled");throw M}O.set(C,"enrolled")}else await B.check({reuse:!0}),await B.step(()=>z.signInLocal(C,D));if($.enrollOnly)continue;if(z.beforeRegister)await B.check({reuse:!0}),await B.step(()=>z.beforeRegister?.(C,F,D));if(C==="opencode")await b0(I,B);else await B.check({reuse:!0}),await B.step(()=>B0(z,Q.pi.executable,Z));if(z.migrate)await B.check({reuse:!0}),await B.step(()=>z.migrate?.(C,D))}}catch(C){if(O.size===0)throw C;try{let M=await F2(z,X,O,T);k0(C,M);for(let L of M)U(K,N0(L,z.vault.hosts[L.host].grantFallback))}catch{}throw C}}if(U(K,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${F}).`),$.enrollOnly)U(K,`Enroll-only: no host config or plugin registration ${$.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:$.dryRun,mode:F,detection:Q}}var v={name:"@cortexkit/opencode-openai-auth",version:"1.18.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 && 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.52.1","@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 R2}from"node:path";import{resolveClaustrumConnectionPath as N2}from"@cortexkit/claustrum-client";var e0={name:"@cortexkit/pi-openai-auth",version:"1.18.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 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.52.1","@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 J0}from"node:fs";import{homedir as Z0}from"node:os";import{join as $0,resolve as z1}from"node:path";import{fileURLToPath as O2}from"node:url";var J1=new Set;function I2(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return $0(Z0(),".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 Z0();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return $0(Z0(),z.slice(2));return z.startsWith("file://")?O2(z):z}function $1(z=I2()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=$0(z,x0),$=$0(Z0(),".pi","agent",x0),K=(W)=>{let G=U0(W),V=Z1(a(G),"pi");return J0(W)||J0(G)||J0(V.tokenPath)||J0(V.statePath)};if(z1(Z)===z1($)||K(Z)||!K($))return Z;let Q=`${Z}\x00${$}`;if(!J1.has(Q))J1.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 C2(z=$1()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||U0(z)}function K1(z=$1()){return{configPath:z,statePath:C2(z)}}function q1(z={}){let J=z.print??console.log,Z=z.fence??(z.createFence??p)(void 0,{onProgress:J}),$={opencode:{stateDir:a(X1().statePath),host:"opencode"},pi:{stateDir:a(K1().statePath),host:"pi"}},K=async(Q)=>{let W=await i(A($[Q]),s(Q));if(W==="host")throw Error(g);if(W!=="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:v.name,pi:e0.name},version:v.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:N2(),hosts:{opencode:{name:s("opencode"),displayName:M0("opencode"),requestedGrants:F0,paths:$.opencode},pi:{name:s("pi"),displayName:M0("pi"),requestedGrants:F0,paths:$.pi}}},async beforeRegister(Q,W){if(await i(A($[Q]),s(Q))==="host")throw Error(g);if(W==="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,W){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(W.opencodeGeneration!=="1"){let q=R2(P("opencode2",z.io)??P("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${q} 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(W.opencodeGeneration==="2")return;if(G1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let G=j1(),V={path:{id:"openai"}};if(await G.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??Q1,j=new AbortController,b=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),x={version:v.version,signal:j.signal},Y,H=!b;try{Y=await X({...x,headless:b})}catch(q){if(b)throw q;H=!1,J("Browser callback unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}if(H){if(!(z.openBrowser??W1)(Y.url))j.abort(),await Y.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}J(`${Y.url}
|
|
14
|
+
${Y.instructions}`);let B=await Y.completion;await c(Z),await K(Q),await G.set({...V,body:{type:"oauth",access:B.access,refresh:B.refresh,expires:B.expires,...B.accountId?{accountId:B.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 Y1({version:v.version}),await V0(q1(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
|