@cortexkit/opencode-openai-auth 1.14.0 → 1.14.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.
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as Q1}from"./index-a9tzfpxy.js";import{Ha as a0,Ia as d,Ja as U,Ka as m,Tb as $1,jc as K1,ta as j0,ua as c,va as V0,wa as u,wc as X1,xa as t0}from"./index-yew3mp47.js";import{Nd as y,Od as r,Qd as P0,Sd as l0,Td as s,Ud as A,Vd as i0,Wd as p,Xd as U0,Yd as L0,ue as J1}from"./index-4zpxwh8y.js";import"./index-zcpher1w.js";import"./index-xxmaf5ks.js";import"./index-3c9pk6zn.js";import{$f as D0,Tf as H0,Zf as B0,cg as Z1}from"./index-wap9mf5f.js";import"./index-nfbmjq6g.js";import"./index-q111b2h5.js";import"./index-1abcvt9p.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(`
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
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
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
5
  ${J.map(($)=>` - PID ${$.pid}: ${$.command}`).join(`
@@ -10,5 +10,5 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);thi
10
10
  `:`
11
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
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.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.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.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.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}
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
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}
@@ -1,2 +1,2 @@
1
- import{vg as y}from"./index-1abcvt9p.js";import{randomUUID as k}from"node:crypto";import{lstat as N,readFile as f,rename as F,unlink as I}from"node:fs/promises";import{tmpdir as P}from"node:os";import{dirname as W,join as E,resolve as K}from"node:path";var B=process.platform==="win32",L=new Set;function V(j){if(j?.reason==="io-error"){if(j.win32Code===2||j.win32Code===3)return"ENOENT";if(j.win32Code===80||j.win32Code===183)return"EEXIST"}return j?.code??"ERR_PRIVATE_FILE"}var _;var b="native-addon-unavailable";function v(j){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:j}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:b})}function g(j,x){return x instanceof j.PrivateFilesUnavailableError||x?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function m(j){try{await j.verifyPrivatePath(E(P(),`.common-auth-private-files-probe-${k()}`),"file")}catch(x){if(g(j,x))throw v(x)}}function $(){return _??=import("@cortexkit/private-files").then(async(j)=>{if(B)await m(j);return j},(j)=>{throw B?v(j):j}),_}class Q extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor(j,x,z){let q=z;super(q?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${x}: ${j} (${b}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${x}: ${j} (${q?.reason??q?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:z});this.path=j,this.stage=x,this.name="PrivateFileError",this.code=V(q),this.win32Code=q?.win32Code,this.reason=q?.reason}}function p(j){return B&&j instanceof Q&&j.reason==="io-error"&&(j.win32Code===32||j.win32Code===303)}async function T(j,x,z){try{return await z()}catch(q){if(q instanceof Q)throw q;throw new Q(j,x,q)}}var c;async function Y(j,x){j=K(j),x??=c,await T(j,"safe-parent",async()=>{let z=await(await $()).verifySafeParent(j,x);if(z.ok===!1){if(z.reason==="io-error"||z.reason==="wrong-kind")await N(j);throw new Q(z.level??z.path,"safe-parent",{...z,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function S(j,x,z=!1){if(j=K(j),x==="directory")return Y(j);await T(j,"verify",async()=>{let q=await $(),H=await q.verifyOwnerOnly(j),C=!1;if(!H.ok){let{reason:J}=H.refusal;if(J==="io-error")await q.verifyPrivatePath(j,x);if(z&&[q.EXTRA_ACE,q.NOT_PROTECTED,q.NULL_DACL,q.EMPTY_DACL].includes(J))await Y(W(j)),await q.securePrivatePath(j,x),C=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:J,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await q.verifyPrivatePath(j,x),C&&!L.has(j))L.add(j),process.emitWarning(`Private permissions tightened: ${j}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function w(j,x=!1,z){j=K(j),await T(j,"directory",async()=>{let q=await $();try{return await N(j),await Y(j,z)}catch(C){if(V(C)!=="ENOENT")throw C}let H=W(j);if(H===j)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await w(H,!1,z);try{await q.createOwnerOnly(j,{kind:"dir"})}catch(C){if(V(C)!=="EEXIST")throw C}await Y(j,z)})}async function e(j,x=!1){if(!B)return f(j,"utf8");return(await u(j,x)).toString("utf8")}async function u(j,x=!1){if(!B)return f(j);if(j=K(j),x)await Y(W(j)),await S(j,"file",!0);return T(j,"read",async()=>(await $()).readOwnerOnly(j))}async function d(j,x){await Y(W(K(j))),await T(j,"create",async()=>{await(await $()).createPrivateFile(K(j),x)})}async function r(j){await Y(W(K(j))),await T(j,"directory-create",async()=>{await(await $()).createOwnerOnly(K(j),{kind:"dir"})})}async function l(j,x,z={}){j=K(j),x=K(x);let q=z.now??(()=>performance.now()),H=q(),C=z.deadline??1/0,J,Z=[0,10,20,40,80,100],U,G=0;for(let D of Z){let R=Math.min(J??1/0,C);if(q()>=R)break;if(D)await(z.sleep??((O)=>new Promise((X)=>setTimeout(X,O))))(Math.min(D,Math.max(0,R-q())));if(q()>=R)break;let A=q();if(await z.beforeRename?.(),J!==void 0)J+=q()-A;if(q()>=C)break;G++;try{return await(z.rename??F)(j,x),{attempts:G,elapsedMs:q()-H}}catch(O){U??=O;let X=O;if(!(X.win32Code!==void 0?X.win32Code===32||X.win32Code===33:["EBUSY","EPERM","EACCES"].includes(X.code??"")&&!X.reason))break;J??=q()+500}}let M=new Q(x,"rename",U??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw M.attempts=G,M.elapsedMs=q()-H,M}async function a(j,x,z={}){j=K(j),await w(W(j));try{await S(j,"file",!0)}catch(G){if(G.code!=="ENOENT")throw G}let q=K(z.stagePath??`${j}.${k()}.tmp`);if(W(q)!==W(j))throw new Q(j,"stage-directory",{code:"EXDEV"});let H=!1,C=!1,J={attempts:0,elapsedMs:0},Z="stage-create",U=(G)=>{try{z.onOutcome?.({path:j,stage:G?.stage??"published",published:C,fileDurable:C,durabilityConfirmed:!1,attempts:G?.attempts??J.attempts,elapsedMs:G?.elapsedMs??J.elapsedMs,...G&&{code:G.code,win32Code:G.win32Code}})}catch{}};try{if(await d(q,x),H=!0,Z="before-rename",J=await l(q,j,z),H=!1,C=!0,Z="published-callback",z.onRenamed?.(),Z="published-verify",await S(j,"file"),z.durable&&z.durability!=="file-only-on-windows")throw new Q(j,"directory-sync-unsupported",{code:"ENOTSUP"});U()}catch(G){let M=G instanceof Q?G:new Q(j,Z,G);if(M.published=C,M.fileDurable=C,C)Object.assign(M,J);if(H){try{await I(q)}catch{M.orphanPath=q}H=!1}throw U(M),M}finally{if(H)await I(q).catch(()=>{})}}
2
- export{B as dg,Q as eg,p as fg,T as gg,Y as hg,S as ig,w as jg,e as kg,d as lg,r as mg,l as ng,a as og};
1
+ import{wg as y}from"./index-cxnrd85v.js";import{randomUUID as k}from"node:crypto";import{lstat as N,readFile as f,rename as F,unlink as I}from"node:fs/promises";import{tmpdir as P}from"node:os";import{dirname as W,join as E,resolve as K}from"node:path";var B=process.platform==="win32",L=new Set;function V(j){if(j?.reason==="io-error"){if(j.win32Code===2||j.win32Code===3)return"ENOENT";if(j.win32Code===80||j.win32Code===183)return"EEXIST"}return j?.code??"ERR_PRIVATE_FILE"}var _;var b="native-addon-unavailable";function v(j){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:j}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:b})}function g(j,x){return x instanceof j.PrivateFilesUnavailableError||x?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function m(j){try{await j.verifyPrivatePath(E(P(),`.common-auth-private-files-probe-${k()}`),"file")}catch(x){if(g(j,x))throw v(x)}}function $(){return _??=import("@cortexkit/private-files").then(async(j)=>{if(B)await m(j);return j},(j)=>{throw B?v(j):j}),_}class Q extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor(j,x,z){let q=z;super(q?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${x}: ${j} (${b}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${x}: ${j} (${q?.reason??q?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:z});this.path=j,this.stage=x,this.name="PrivateFileError",this.code=V(q),this.win32Code=q?.win32Code,this.reason=q?.reason}}function p(j){return B&&j instanceof Q&&j.reason==="io-error"&&(j.win32Code===32||j.win32Code===303)}async function T(j,x,z){try{return await z()}catch(q){if(q instanceof Q)throw q;throw new Q(j,x,q)}}var c;async function Y(j,x){j=K(j),x??=c,await T(j,"safe-parent",async()=>{let z=await(await $()).verifySafeParent(j,x);if(z.ok===!1){if(z.reason==="io-error"||z.reason==="wrong-kind")await N(j);throw new Q(z.level??z.path,"safe-parent",{...z,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function S(j,x,z=!1){if(j=K(j),x==="directory")return Y(j);await T(j,"verify",async()=>{let q=await $(),H=await q.verifyOwnerOnly(j),C=!1;if(!H.ok){let{reason:J}=H.refusal;if(J==="io-error")await q.verifyPrivatePath(j,x);if(z&&[q.EXTRA_ACE,q.NOT_PROTECTED,q.NULL_DACL,q.EMPTY_DACL].includes(J))await Y(W(j)),await q.securePrivatePath(j,x),C=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:J,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await q.verifyPrivatePath(j,x),C&&!L.has(j))L.add(j),process.emitWarning(`Private permissions tightened: ${j}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function w(j,x=!1,z){j=K(j),await T(j,"directory",async()=>{let q=await $();try{return await N(j),await Y(j,z)}catch(C){if(V(C)!=="ENOENT")throw C}let H=W(j);if(H===j)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await w(H,!1,z);try{await q.createOwnerOnly(j,{kind:"dir"})}catch(C){if(V(C)!=="EEXIST")throw C}await Y(j,z)})}async function e(j,x=!1){if(!B)return f(j,"utf8");return(await u(j,x)).toString("utf8")}async function u(j,x=!1){if(!B)return f(j);if(j=K(j),x)await Y(W(j)),await S(j,"file",!0);return T(j,"read",async()=>(await $()).readOwnerOnly(j))}async function d(j,x){await Y(W(K(j))),await T(j,"create",async()=>{await(await $()).createPrivateFile(K(j),x)})}async function r(j){await Y(W(K(j))),await T(j,"directory-create",async()=>{await(await $()).createOwnerOnly(K(j),{kind:"dir"})})}async function l(j,x,z={}){j=K(j),x=K(x);let q=z.now??(()=>performance.now()),H=q(),C=z.deadline??1/0,J,Z=[0,10,20,40,80,100],U,G=0;for(let D of Z){let R=Math.min(J??1/0,C);if(q()>=R)break;if(D)await(z.sleep??((O)=>new Promise((X)=>setTimeout(X,O))))(Math.min(D,Math.max(0,R-q())));if(q()>=R)break;let A=q();if(await z.beforeRename?.(),J!==void 0)J+=q()-A;if(q()>=C)break;G++;try{return await(z.rename??F)(j,x),{attempts:G,elapsedMs:q()-H}}catch(O){U??=O;let X=O;if(!(X.win32Code!==void 0?X.win32Code===32||X.win32Code===33:["EBUSY","EPERM","EACCES"].includes(X.code??"")&&!X.reason))break;J??=q()+500}}let M=new Q(x,"rename",U??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw M.attempts=G,M.elapsedMs=q()-H,M}async function a(j,x,z={}){j=K(j),await w(W(j));try{await S(j,"file",!0)}catch(G){if(G.code!=="ENOENT")throw G}let q=K(z.stagePath??`${j}.${k()}.tmp`);if(W(q)!==W(j))throw new Q(j,"stage-directory",{code:"EXDEV"});let H=!1,C=!1,J={attempts:0,elapsedMs:0},Z="stage-create",U=(G)=>{try{z.onOutcome?.({path:j,stage:G?.stage??"published",published:C,fileDurable:C,durabilityConfirmed:!1,attempts:G?.attempts??J.attempts,elapsedMs:G?.elapsedMs??J.elapsedMs,...G&&{code:G.code,win32Code:G.win32Code}})}catch{}};try{if(await d(q,x),H=!0,Z="before-rename",J=await l(q,j,z),H=!1,C=!0,Z="published-callback",z.onRenamed?.(),Z="published-verify",await S(j,"file"),z.durable&&z.durability!=="file-only-on-windows")throw new Q(j,"directory-sync-unsupported",{code:"ENOTSUP"});U()}catch(G){let M=G instanceof Q?G:new Q(j,Z,G);if(M.published=C,M.fileDurable=C,C)Object.assign(M,J);if(H){try{await I(q)}catch{M.orphanPath=q}H=!1}throw U(M),M}finally{if(H)await I(q).catch(()=>{})}}
2
+ export{B as eg,Q as fg,p as gg,T as hg,Y as ig,S as jg,w as kg,e as lg,d as mg,r as ng,l as og,a as pg};