@cortexkit/opencode-openai-auth 1.6.1 → 1.6.2
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/{index-cv6aqcvk.js → index-xpc2hm9h.js} +25 -25
- package/dist/index.js +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
3
|
-
`);return b<0?"":G.slice(b+1)}class m extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(
|
|
2
|
+
import{c as g0}from"./index-79y7w9bz.js";import{Db as f0,Ga as R0,Ha as f,Ia as Y,Ja as E,lb as E0,ua as P0,va as S,wa as e}from"./index-k5anexvs.js";import{dd as y0,jd as j0,ld as d,md as _,nd as S0,od as h,pd as D0}from"./index-ge60xry3.js";import"./index-8xq099qf.js";import{Le as b0,Re as w0,Se as I0,Ve as v0}from"./index-b0ty9qam.js";import"./index-7nmdsmpp.js";import"./index-ya9c5e4m.js";import{spawn as h0}from"node:child_process";var R=4096,c0=1048576;class G0{buffer=Buffer.alloc(R);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=R){if(G.length>R||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-R),this.start=0,this.length=R;return}let b=Math.max(0,this.length+G.length-R);if(b>0)this.truncated=!0;this.start=(this.start+b)%R,this.length-=b;let z=(this.start+this.length)%R,Z=Math.min(G.length,R-z);if(G.copy(this.buffer,z,0,Z),Z<G.length)G.copy(this.buffer,0,Z);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),b=Math.min(this.length,R-this.start);if(this.buffer.copy(G,0,this.start,this.start+b),b<this.length)this.buffer.copy(G,b,0,this.length-b);let z=0;while(z<G.length){let Z=G[z];if(Z===void 0||(Z&192)!==128)break;z++}return G.subarray(z).toString("utf8")}}var I={run(G,b,z={}){return new Promise((Z)=>{let J=performance.now(),$=z.timeoutMs??15000,K=new G0,x=[],W=0,Q=!1,D=!1,X=!1,V;try{V=h0(G,[...b],{env:z.env??process.env,windowsHide:!0,windowsVerbatimArguments:z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-J});return}let U=$>0?setTimeout(()=>{X=!0,V.kill("SIGTERM")},$):void 0;V.stdout?.on("data",(F)=>{let k=c0-W,q=Math.min(k,F.length);if(q>0)x.push(F.subarray(0,q)),W+=q;if(F.length>k)Q=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(F)=>K.push(F));let j=!1,B=(F,k)=>{if(j)return;if(j=!0,U)clearTimeout(U);Z({exitCode:D?1:Q?1:F??1,stdout:Buffer.concat(x,W).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...D?{spawnError:!0}:{},signal:k??null,timedOut:X,durationMs:performance.now()-J})};V.once("error",()=>{if(D=!0,V.pid===void 0)B(null,null)}),V.once("close",(F,k)=>B(F,k))})}};function g(G,b,z,Z,J,$=15000){if(b==="win32"&&/\.(cmd|bat)$/i.test(z)){if(/["%!\r\n]/.test(z)||Z.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${z}" ${Z.join(" ")}"`],{env:J,timeoutMs:$,windowsVerbatimArguments:!0})}return G.run(z,Z,{env:J,timeoutMs:$})}var u0="Pi install failed; run pi install after checking your npm connection.";function p0(G){let b=Buffer.from(G,"utf8");if(b.length<=R)return G;let z=b.length-R;while(z<b.length){let Z=b[z];if(Z===void 0||(Z&192)!==128)break;z++}return b.subarray(z).toString("utf8")}function l0(G){let b=G.indexOf(`
|
|
3
|
+
`);return b<0?"":G.slice(b+1)}class m extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(u0);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let b=G.stderrTruncated?l0(G.stderrTail):G.stderrTail,z=b0(b);this.stderrTail=p0(typeof z==="string"?z:"")}}var a0={opencode:"OpenCode",pi:"Pi"},i0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function z0({host:G,outcome:b}){return`${a0[G]}: ${i0[b]}`}var s0=new WeakMap;function J0(G,b){if(typeof G!=="object"&&typeof G!=="function"||!G)return;s0.set(G,Object.freeze(b.map((z)=>Object.freeze({...z}))))}import{accessSync as e0,constants as G2,existsSync as b2,readFileSync as z2,realpathSync as J2,statSync as Z2}from"node:fs";import{mkdtemp as $2,rm as Q2}from"node:fs/promises";import{tmpdir as K2}from"node:os";import{join as q2}from"node:path";import{parse as x2}from"jsonc-parser";import{homedir as r0}from"node:os";import{posix as n0,win32 as o0}from"node:path";import{fileURLToPath as t0}from"node:url";function N(G={}){let b=G.env??process.env,z=G.platform??process.platform,Z=z==="win32"?o0:n0,J=G.home??(z==="win32"?b.USERPROFILE:b.HOME)??r0(),$=G.cwd??process.cwd(),K=(D)=>Z.resolve($,D),x=b.OPENCODE_CONFIG_DIR?.trim(),W=b.XDG_CONFIG_HOME?.trim(),Q=b.PI_CODING_AGENT_DIR?.trim()||Z.join(J,".pi","agent");if(Q==="~")Q=J;else if(/^~[/\\]/.test(Q))Q=Z.join(J,Q.slice(2));if(Q.startsWith("file://"))Q=t0(Q);return{env:b,platform:z,path:Z,home:J,cwd:$,opencode:x?K(x):W?Z.join(K(W),"opencode"):Z.join(J,".config","opencode"),pi:K(Q)}}function c(G,b){try{return Z2(G)[b]()}catch{return!1}}var T={exists:b2,isFile:(G)=>c(G,"isFile"),isDirectory:(G)=>c(G,"isDirectory"),isExecutable(G){try{return e0(G,G2.X_OK),c(G,"isFile")}catch{return!1}},readText:(G)=>z2(G,"utf8"),realpath:J2};function w(G,b={}){let{env:z,platform:Z,path:J,cwd:$}=N(b),K=b.fs??T,x=Object.entries(z).find(([Q])=>Z==="win32"?Q.toUpperCase()==="PATH":Q==="PATH")?.[1]??"",W=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let Q of x.split(Z==="win32"?";":":")){let D=Q.trim().replace(/^"|"$/g,"");if(!D)continue;for(let X of W){let V=J.resolve($,D,G+X);if(Z==="win32"?K.isFile(V):K.isExecutable(V))return V}}return null}function Z0(G={}){let{platform:b,home:z,env:Z,path:J}=N(G);if(b==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",J.join(z,"Applications","OpenCode.app"),J.join(z,"Applications","OpenCode Beta.app")];if(b==="win32"){let $=Z.LOCALAPPDATA||J.join(z,"AppData","Local");return[J.join($,"Programs","opencode"),J.join($,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",J.join(z,".local","share","applications","opencode.desktop")]}function u(G,b){let z=b.fs??T,{path:Z}=N(b);try{let J=z.readText(G);if(J.length>65536)return G;let $=[...J.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!$.length)$.push(...J.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=$.at(-1)?.[1];if(K){let x=Z.join(Z.dirname(G),...K.split(/[/\\]+/));if(z.isFile(x))return z.realpath(x)}return z.realpath(G)}catch{return G}}function U2(G,b){let z=b.fs??T,{path:Z}=N(b),J=Z.dirname(u(G,b));for(;;){try{let K=JSON.parse(z.readText(Z.join(J,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(K.name))return"2";if(K.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(K.version??"")?"2":"1"}catch{}let $=Z.dirname(J);if($===J)return null;J=$}}function $0(G={}){let b=w("opencode",G),z=w("opencode2",G),Z=b&&z&&u(b,G)===u(z,G),J=G.fs??T,{path:$,opencode:K}=N(G),x="1";for(let Q of["jsonc","json"]){let D=$.join(K,`opencode.${Q}`);if(!J.exists(D))continue;try{if(Object.hasOwn(x2(J.readText(D))??{},"plugins"))x="2"}catch{}break}let W=b?U2(b,G)??(Z?"2":x):null;if(z&&W==="1"&&!Z)return"ambiguous";return z||Z?"2":W??x}async function p(G,b={}){let z=b.fs??T,{env:Z,platform:J,opencode:$,pi:K}=N(b),x=b.runner??I,W=w("opencode",b)??w("opencode2",b),Q=w("pi",b),D=w("ck",b),X=async(B)=>{if(!B)return null;let F;try{F=await $2(q2(K2(),"common-auth-setup-version-"));let k={...Z,HOME:F,USERPROFILE:F,XDG_CONFIG_HOME:F,XDG_DATA_HOME:F,XDG_STATE_HOME:F,XDG_CACHE_HOME:F,OPENCODE_CONFIG_DIR:F,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:F},q=await g(x,J,B,["--version"],k,2000);return q.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(q.stdout)?.[0]??null:null}catch{return null}finally{if(F)await Q2(F,{recursive:!0,force:!0}).catch(()=>{})}},V=!1;if(D&&z.exists(G.vault.connectionFile))try{(await(b.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),V=!0}catch{V=!1}let[U,j]=await Promise.all([X(W),X(Q)]);return{opencode:{installed:z.isDirectory($)||Z0(b).some((B)=>z.exists(B))||W!==null,executable:W,version:U,directory:$,generation:$0(b)},pi:{installed:Q!==null||z.isDirectory(K),executable:Q,version:j,directory:K},claustrum:{available:V,executable:D}}}import{setTimeout as B2}from"node:timers/promises";import{writeEnrollmentTokenFile as H2}from"@cortexkit/claustrum-client";var Q0=45000,l=new Set(["opencode","litecode","opencode2","pi"]),q0=new Set(["node","bun"]),W2=[...l,...q0].map((G)=>`Name LIKE '${G}%'`).join(" OR "),X2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${W2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,j2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function D2(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((b)=>b[1]??b[2]??"")}function K0(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var V2=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--title","--input-type","--preload","--cwd","-c","--config","--tsconfig-override","-d","--define","-l","--main-fields"]),F2=new Set(["-e","--eval","-p","--print"]);function Y2(G,b){for(let z=0;z<b.length;z++){let Z=b[z]??"";if(Z==="--")return b[z+1];if(F2.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&V2.has(Z))z++;continue}if(G==="bun"&&Z==="run")continue;return Z}return}function x0(G){let[b,...z]=D2(G);if(b===void 0)return null;let Z=K0(b);if(l.has(Z))return Z;if(!q0.has(Z))return null;let J=Y2(Z,z);if(J===void 0)return null;let $=K0(J);if(l.has($))return $;return j2.test(J)?"pi":null}class H extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(G){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=G.step,this.exitCode=G.exitCode,this.signal=G.signal,this.timedOut=G.timedOut,this.durationMs=G.durationMs}get refusalText(){let G=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${G} after ${Math.round(this.durationMs)} ms.`}}class L extends Error{activeHosts;constructor(G){let b=G.map((z)=>({pid:z.pid,command:x0(z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
|
|
4
4
|
${b.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
|
|
5
5
|
`)}
|
|
6
6
|
|
|
7
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=b,this.name="ProcessFenceViolationError"}}async function a(G=I,b={}){let z=(b.platform??process.platform)==="win32",Z=b.selfPid??process.pid,J={step:z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},$=async(K,W,
|
|
7
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=b,this.name="ProcessFenceViolationError"}}async function a(G=I,b={}){let z=(b.platform??process.platform)==="win32",Z=b.selfPid??process.pid,J={step:z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},$=async(K,x,W,Q)=>{let D=performance.now();J={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let X=await G.run(x,W,{env:b.env,timeoutMs:Q});return J={step:K,exitCode:X.exitCode,signal:X.signal??null,timedOut:X.timedOut??!1,durationMs:X.durationMs??performance.now()-D},X}finally{if(J.exitCode===null)J.durationMs=performance.now()-D;b.onStep?.({...J})}};try{if(z&&b.hostImagesOnly){let Q=await $("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",X2],Q0);if(Q.exitCode!==0)throw new H(J);let D=JSON.parse(Q.stdout);if(!D||typeof D!=="object"||!("complete"in D)||D.complete!==!0||!("processes"in D))throw new H(J);let X=D.processes,V=X===null?[]:Array.isArray(X)?X:[X],U=[];for(let j of V){if(!j||typeof j!=="object"||!("Name"in j)||typeof j.Name!=="string"||!("ProcessId"in j)||!Number.isSafeInteger(j.ProcessId)||j.ProcessId<0||!("CommandLine"in j))throw new H(J);let B=j.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(j.Name))U.push({pid:B,command:j.Name});else if(typeof j.CommandLine==="string")U.push({pid:B,command:j.CommandLine});else if(B!==Z)throw new H(J)}return U}let K=await $(z?"tasklist":"ps",z?"tasklist.exe":"ps",z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new H(J);let x=[];for(let Q of K.stdout.split(/\r?\n/)){let D=Q.trim();if(!D)continue;let X,V;if(z){let U=/^"([^"]+)","(\d+)"(?:,|$)/.exec(D);if(!U)throw new H(J);V=U[1]??"",X=Number(U[2])}else{let U=/^(\d+)\s+(.+)$/.exec(D);if(!U){if(/^PID\s+COMMAND$/i.test(D))continue;throw new H(J)}X=Number(U[1]),V=U[2]??""}if(!Number.isSafeInteger(X)||X<0)throw new H(J);x.push({pid:X,command:V})}if(!x.length)throw new H(J);let W=x.filter((Q)=>Q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(Q.command));if(z&&W.length&&b.inspectRuntimes!==!1){let Q=await $("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],Q0);if(Q.exitCode!==0)throw new H(J);let D=JSON.parse(Q.stdout||"null"),X=D===null?[]:Array.isArray(D)?D:[D],V=new Map;for(let U of X){if(!U||typeof U!=="object"||!("ProcessId"in U)||!("CommandLine"in U)||!Number.isSafeInteger(U.ProcessId))throw new H(J);if(typeof U.CommandLine==="string")V.set(Number(U.ProcessId),U.CommandLine);else if(W.some((j)=>j.pid===U.ProcessId))throw new H(J)}for(let U of W)U.command=V.get(U.pid)??""}return x}catch(K){if(K instanceof H)throw K;throw new H(J)}}function P(G=I,b={}){let z=b.selfPid??process.pid,Z=(J)=>J.pid!==z&&x0(J.command)!==null;return{async listRunningHosts(J){return(await a(G,{...b,env:J,hostImagesOnly:!0})).filter(Z)},async previewRunningHosts(J){let $=await a(G,{...b,env:J,inspectRuntimes:!1}),K=(b.platform??process.platform)==="win32";return{hosts:$.filter(Z),uncheckedRuntimes:K?$.filter((x)=>x.pid!==z&&/^(?:node|bun)\.exe$/i.test(x.command)).length:0}}}}async function v(G,b){let z=await G.listRunningHosts(b);if(z.length)throw new L(z)}var O2="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",V0='This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',F0=300000,U0=1000,W0=[1000,2000,4000,8000,16000,30000];function i(G){return G&&/^[a-z][a-z0-9_]{0,63}$/.test(G)?G:"unknown"}class A extends Error{reason;lastErrorCode;constructor(G,b){super(G);if(this.name="HostNotEnrolledError",this.reason=b.reason,b.lastErrorCode!==void 0)this.lastErrorCode=i(b.lastErrorCode)}}function X0(G,b){return`ck auth enroll approve --request-id ${G} --name ${b}`}async function Y0(G,b,z,Z,J){let{name:$,paths:K}=G.vault.hosts[b],x=_(K);await J();let W=await(z.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new A("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),Q=z.now??(()=>performance.now()),D=z.wait??B2;try{let X=new D0({proposedName:$,paths:x,client:W,writeTokenFile:async(q,O)=>{await J(),await H2(q,O)}});Y(Z,`Asking the vault to connect ${$}…`);let V=Q()+F0,U,j,B,F=0;for(;;){await J();let q=await X.reconcile();if(q.state==="approved"){Y(Z,`Connected ${b} to Claustrum.`);return}if(q.state==="unavailable"&&q.code===j0)throw new A(V0,{reason:"unsupported-vault",lastErrorCode:q.code});if(q.state!=="pending"&&q.state!=="busy")throw new A("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in q&&{lastErrorCode:q.code}});let O=U0;if(q.state==="busy")j="busy";else if(q.retryCode)j=q.retryCode;if(q.state==="pending"&&q.requestId){if(F=0,q.requestId!==U){if(!/^[a-zA-Z0-9_-]+$/.test(q.requestId))throw new A("Invalid enrollment request id.",{reason:"invalid-request"});U=q.requestId,Y(Z,"Waiting for approval. In another terminal, run:"),Y(Z,` ${X0(q.requestId,$)}`),Y(Z,`Enrollment files: ${x.statePath}, ${x.tokenPath}`)}}else if(q.state==="pending"&&q.retryCode){O=W0[Math.min(F,W0.length-1)]??U0,F++;let C=i(q.retryCode);if(C!==B)B=C,Y(Z,`The vault has not created the request yet (${C}); retrying.`)}let M=V-Q();if(M<=0)break;await D(Math.min(O,M))}if(U)throw new A(`Claustrum approval is still pending. In another terminal, run: ${X0(U,$)} and then rerun setup.`,{reason:"approval-pending",...j!==void 0&&{lastErrorCode:j}});let k=i(j);throw new A(`The vault never created the enrollment request (last error: ${k}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:k})}catch(X){if(X instanceof L||X instanceof H||X instanceof A)throw X;let V=X?.code;throw new A(O2,{reason:"incomplete",...typeof V==="string"&&{lastErrorCode:V}})}finally{W.close()}}async function B0(G,b){let z=new Set(b);for(;;){let Z=await E(G,[...["opencode","pi"].map((J)=>({value:J,label:`[${z.has(J)?"x":" "}] ${J==="opencode"?"OpenCode":"Pi"}`,hint:b.includes(J)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if(Z===null)return null;if(Z==="done")return[...z];if(z.has(Z))z.delete(Z);else z.add(Z)}}import{applyEdits as s,createScanner as L2,findNodeAtLocation as y2,modify as O0,parse as S2,parseTree as P2}from"jsonc-parser";import{randomUUID as M2}from"node:crypto";import{mkdir as k2,open as C2,rename as R2,stat as N2,unlink as A2}from"node:fs/promises";import{basename as w2,dirname as I2,join as _2}from"node:path";import{setTimeout as T2}from"node:timers/promises";async function H0(G,b,z={}){let Z=(z.platform??process.platform)==="win32",J=I2(G);await k2(J,{recursive:!0});let $;if(!Z)try{$=(await N2(G)).mode&4095}catch(W){if(W.code!=="ENOENT")throw W}let K=_2(J,`.${w2(G)}.${(z.stageName??M2)()}.tmp`),x=!1;try{let W=await C2(K,"wx",$??438);x=!0;try{if(await W.writeFile(b,"utf8"),$!==void 0)await W.chmod($)}finally{await W.close()}let Q=z.now??(()=>performance.now()),D=Q();for(let X=0;;X++){await z.beforeRename?.();try{await(z.rename??R2)(K,G),x=!1;return}catch(V){let U=V.code,j=2000-(Q()-D);if(!Z||!["EPERM","EBUSY","EACCES"].includes(U??"")||j<=0||X>=40)throw Error(`Unable to replace host config ${G}. Close editors or other programs using the file, then rerun setup.`);await(z.wait??T2)(Math.min(j,25*2**Math.min(X,2)))}}}finally{if(x)await A2(K).catch(()=>{})}}function M0(G){let b=typeof G==="string"?G:Array.isArray(G)?G[0]:G&&typeof G==="object"&&("package"in G)?G.package:null;if(typeof b!=="string")return null;let z=b.indexOf("@",b.startsWith("@")?1:0);return z<0?b:b.slice(0,z)}function k0(G,b,z){let Z=P2(G),J=Z&&y2(Z,[b]),$=J?.children??[],K=$[z];if(!K||!J)throw Error("Invalid plugin array edit.");let x=[{offset:K.offset,length:K.length,content:""}],W=(Q,D)=>{let X=L2(G.slice(Q,D),!0);if(X.scan(),G[Q+X.getTokenOffset()]===",")x.push({offset:Q+X.getTokenOffset(),length:1,content:""})};if(z===$.length-1){let Q=$[z-1];if(Q)W(Q.offset+Q.length,K.offset);W(K.offset+K.length,J.offset+J.length-1)}else W(K.offset+K.length,$[z+1]?.offset??K.offset+K.length);return s(G,x)}function C0(G,b,z,Z){let J=[],$=S2(G,J,{allowTrailingComma:!0});if(J.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");let K={formattingOptions:{insertSpaces:!/^\t+/m.test(G),tabSize:/^([ ]+)"/m.exec(G)?.[1]?.length??2,eol:G.includes(`\r
|
|
8
8
|
`)?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`}},
|
|
11
|
-
`,
|
|
12
|
-
${q.content}`);if(Q.includes("pi"))Y(J,`Would run ${$.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let q of Q)Y(J,`Would migrate ${q} using the plugin callback (provider-specific writes).`)}else{let q={opencodeGeneration:D,mode:F,hosts:Object.freeze([...Q]),piAgentDir:$.pi.directory},O=new Map;try{for(let M of Q){if(await
|
|
13
|
-
ck auth grant --principal enrolled:${
|
|
14
|
-
${
|
|
10
|
+
`}},x=G,W=$[b];if(W!==void 0&&!Array.isArray(W))throw Error(`OpenCode ${b} must be an array.`);let Q=Array.isArray(W)?[...W]:[],D=Q.flatMap((U,j)=>M0(U)===z?[j]:[]),X=`${z}@${Z}`;if(!D.length)x=s(x,O0(x,W===void 0?[b]:[b,Q.length],W===void 0?[X]:X,K));else{let U=D[0],j=Q[U],B=Array.isArray(j)?[X,...j.slice(1)]:j&&typeof j==="object"?{...j,package:X}:X;if(JSON.stringify(j)!==JSON.stringify(B))x=s(x,O0(x,[b,U],B,K));for(let F of D.slice(1).reverse())x=k0(x,b,F)}let V=b==="plugin"?"plugins":"plugin";if(Array.isArray($[V])){let U=$[V];for(let j=U.length-1;j>=0;j--)if(M0(U[j])===z)x=k0(x,V,j)}return x}function r(G,b,z={}){let Z=z.fs??T,{path:J,opencode:$}=N(z),K=b==="2"?"plugins":"plugin";return(b==="2"?["opencode"]:["opencode","tui"]).map((W)=>{let Q=J.join($,`${W}.jsonc`),D=J.join($,`${W}.json`),X=Z.exists(Q)?Q:Z.exists(D)?D:Q,V=Z.exists(X),U=V?Z.readText(X):`${JSON.stringify({$schema:`https://opencode.ai/${W==="tui"?"tui":"config"}.json`},null,2)}
|
|
11
|
+
`,j=C0(U,K,G.packages.opencode,G.version);return{path:X,content:j,changed:!V||j!==U}})}async function n(G,b){for(let z of G){if(!z.changed)continue;await b?.(),await H0(z.path,z.content,{beforeRename:b})}}async function o(G,b,z={}){let{platform:Z,env:J}=N(z),$=await g(z.runner??I,Z,b,["install",`npm:${G.packages.pi}@${G.version}`],J);if($.exitCode!==0||$.timedOut)throw new m({exitCode:$.spawnError?null:$.exitCode,signal:$.signal??null,stderrTail:$.stderr,stderrTruncated:$.stderrTruncated??!1})}var N0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function v2(G){let b={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,opencode:void 0};for(let z of G)if(z==="--yes")b.yes=!0;else if(z==="--dry-run")b.dryRun=!0;else if(z==="--claustrum")b.claustrum=!0;else if(z==="--no-claustrum")b.noClaustrum=!0;else if(z==="--login")b.login=!0;else if(/^--opencode=(1|2|both)$/.test(z))b.opencode=z.slice(11);else throw Error(`Unknown setup argument: ${z}`);if(b.claustrum&&b.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(b.login&&b.claustrum)throw Error("--login and --claustrum cannot be used together.");return b}function E2(G){for(let b of Object.values(G.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(b))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(G.version))throw Error("Setup requires a concrete package version.");for(let b of Object.values(G.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(b.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function f2(G,b,z){let Z=[];for(let J of b){let $=z.get(J)??"not-enrolled";if($==="unknown"){let{name:K,paths:x}=G.vault.hosts[J],W=await h(_(x),K).catch(()=>"unreadable");if(W==="vault")$="enrolled";else if(W==="local")$="not-enrolled"}Z.push({host:J,outcome:$})}return Z}async function t(G,b=[],z={}){let Z=v2(b);E2(G);let J=z.terminal??R0(),$=await p(G,z);Y(J,`${G.displayName} setup`);for(let[q,O]of[["OpenCode",$.opencode],["Pi",$.pi]])Y(J,`${q}: ${O.installed?`found (version ${O.version??"unknown"})`:"not found"} — ${O.directory}`);Y(J,`Claustrum: ${$.claustrum.available?"available":"not available"}`);let K=$.pi.installed&&!$.pi.executable;if(K)Y(J,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let x=["opencode","pi"].filter((q)=>$[q].installed&&!(q==="pi"&&K)),W=Z.yes||Z.dryRun&&!f(J);if(!W&&!f(J))throw Error("Setup requires a TTY or --yes.");let Q=W?x:await B0(J,x)??[],D=Z.opencode??($.opencode.generation==="ambiguous"?"1":$.opencode.generation);if(Q.includes("opencode")&&!Z.opencode&&$.opencode.generation==="ambiguous"){if(W||!f(J))throw Error(N0);let q=await E(J,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(q===null)return{hosts:[],dryRun:Z.dryRun,mode:"local",detection:$};D=q}if(!Q.length)return Y(J,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:Q,dryRun:Z.dryRun,mode:"local",detection:$};let{env:X,platform:V}=N(z),U=z.fence??P(z.runner??I,{platform:V}),j=async()=>{try{await v(U,X)}catch(q){if(q instanceof H)Y(J,q.refusalText);throw q}};if(Y(J,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let q=U.previewRunningHosts?await U.previewRunningHosts(X):{hosts:await U.listRunningHosts(X),uncheckedRuntimes:0},O=q.hosts;if(q.uncheckedRuntimes>0)Y(J,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let M=new Set(new L(O).activeHosts.map((C)=>C.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let C of M)Y(J,`${C} is running; setup will ask you to quit it.`)}catch(q){if(Y(J,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),q instanceof H)Y(J,q.refusalText)}else await j();if(Z.claustrum&&!$.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let B=Boolean(Z.claustrum);if(!B&&!Z.login&&!Z.noClaustrum&&!W&&$.claustrum.available&&f(J)){let q=await E(J,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(q===null)return Y(J,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:$};B=q===!0}let F=B?"claustrum":"local",k=Q.includes("opencode")?r(G,D,z):[];if(Z.dryRun){Y(J,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let q of Q){if(G.beforeSignIn)Y(J,`Would run beforeSignIn(${q}, ${F}).`);if(B){let O=_(G.vault.hosts[q].paths);Y(J,`Would Connect ${q}: write ${O.statePath} and ${O.tokenPath}; wait for ck auth enroll approve.`)}else Y(J,`Would sign in locally for ${q}.`);if(G.beforeRegister)Y(J,`Would run beforeRegister(${q}, ${F}).`)}for(let q of k)Y(J,`${q.changed?"Would write":"Unchanged"} ${q.path}:
|
|
12
|
+
${q.content}`);if(Q.includes("pi"))Y(J,`Would run ${$.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let q of Q)Y(J,`Would migrate ${q} using the plugin callback (provider-specific writes).`)}else{let q={opencodeGeneration:D,mode:F,hosts:Object.freeze([...Q]),piAgentDir:$.pi.directory},O=new Map;try{for(let M of Q){if(await j(),await G.beforeSignIn?.(M,q),await j(),B){O.set(M,"unknown");try{await Y0(G,M,z,J,j)}catch(C){if(C instanceof A)O.set(M,"not-enrolled");throw C}O.set(M,"enrolled")}else await G.signInLocal(M,q);if(await j(),await G.beforeRegister?.(M,F,q),await j(),M==="opencode")await n(k,j);else await o(G,$.pi.executable,z);await j(),await G.migrate(M,q)}}catch(M){if(O.size===0)throw M;try{let C=await f2(G,Q,O);J0(M,C);for(let d0 of C)Y(J,z0(d0))}catch{}throw M}}return Y(J,`${Z.dryRun?"Planned":"Configured"} ${G.displayName} for ${Q.join(", ")} (${F}).`),Y(J,`Next: ${Q.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`),{hosts:Q,dryRun:Z.dryRun,mode:F,detection:$}}import{basename as u2}from"node:path";import{resolveClaustrumConnectionPath as p2}from"@cortexkit/claustrum-client";var A0={name:"@cortexkit/pi-openai-auth",version:"1.6.2",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.26.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{homedir as m2}from"node:os";import{join as _0}from"node:path";function d2(){return process.env.PI_AGENT_DIR?.trim()||_0(m2(),".pi","agent")}function T0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||_0(d2(),w0)}function h2(G=T0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||I0(G)}function L0(G=T0()){return{configPath:G,statePath:h2(G)}}var y={name:"@cortexkit/opencode-openai-auth",version:"1.6.2",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.26.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.32"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.6.1","@opentui/solid":">=0.6.1",ai:"^7.0.143","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};function m0(G={}){let b=G.print??console.log,z=G.fence??P(),Z={opencode:{stateDir:e(E0().statePath),host:"opencode"},pi:{stateDir:e(L0().statePath),host:"pi"}},J=async($)=>{if(await h(_(Z[$]),S($))!=="local")throw Error(`${$} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:y.name,pi:A0.name},version:y.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:p2(),hosts:{opencode:{name:S("opencode"),paths:Z.opencode},pi:{name:S("pi"),paths:Z.pi}}},async beforeRegister($,K){if(K==="claustrum"){let x=await S0(_(Z[$]),S($)),W=x.state==="approved"?x.approvedName:void 0,Q=W??("proposedName"in x?x.proposedName:S($));if(!W)b("The enrollment state does not record an approved name. The command below uses the proposed name; if the vault approved a different name, substitute it.");if(b(`Allow this host to read OpenAI accounts with:
|
|
13
|
+
ck auth grant --principal enrolled:${Q} --selector-kind category --selector ${P0.category} --operation read`),$==="opencode")b("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await J($)},async signInLocal($,K){if(await J($),$==="pi"){b("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let F=u2(w("opencode2",G.io)??w("opencode",G.io)??"opencode");b(`In OpenCode 2, run ${F} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(K.opencodeGeneration==="2")return;if(f0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let x=g0(),W={path:{id:"openai"}};if(await x.get(W)!==void 0){b("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let Q=G.beginLogin??y0,D=new AbortController,X=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),V={version:y.version,signal:D.signal},U,j=!X;try{U=await Q({...V,headless:X})}catch(F){if(X)throw F;j=!1,b("Browser callback unavailable; using device-code sign-in."),U=await Q({version:y.version,headless:!0})}if(j){if(!(G.openBrowser??v0)(U.url))D.abort(),await U.completion.catch(()=>{}),b("Browser unavailable; using device-code sign-in."),U=await Q({version:y.version,headless:!0})}b(`${U.url}
|
|
14
|
+
${U.instructions}`);let B=await U.completion;await v(z),await J($),await x.set({...W,body:{type:"oauth",access:B.access,refresh:B.refresh,expires:B.expires,...B.accountId?{accountId:B.accountId}:{}}}),b("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate($){b(`${$}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await t(m0(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}
|