@cortexkit/opencode-openai-auth 1.10.0 → 1.11.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-BLzSBegI.d.ts → codex-request-DFeGDzpN.d.ts} +2 -2
- package/dist/index-0kpq9310.js +76 -0
- package/dist/{index-361xxyg2.js → index-2p3st53v.js} +2 -2
- package/dist/{index-dcyhv7eh.js → index-3x7q1rj8.js} +2 -2
- package/dist/{index-mkda7acs.js → index-4daebegf.js} +1 -1
- package/dist/{index-w37815v4.js → index-4rzatybc.js} +1 -1
- package/dist/{index-mf3dqvbn.js → index-7at0fc03.js} +2 -2
- package/dist/{index-fd3f8vw2.js → index-afpxnan1.js} +2 -2
- package/dist/{index-29ztc0ay.js → index-bxxjwt4q.js} +2 -2
- package/dist/index-cy6km6cz.js +64 -0
- package/dist/{index-17rh67pr.js → index-d5v2rn54.js} +1 -1
- package/dist/{index-95z5dpe1.js → index-dp68014q.js} +2 -2
- package/dist/index-h2z9jb3g.js +91 -0
- package/dist/{index-dkhy2peg.js → index-smzgsx6x.js} +1 -1
- package/dist/index.d.ts +1 -1
- 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-util-e49kkftr.js +1 -0
- package/dist/{token-pd3t5f20.js → token-wgntcjq1.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +4 -4
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +26 -15
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +14 -5
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +5 -2
- package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +2 -0
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +7 -0
- package/src/tui-compiled/raw/shared/c97089ed4243981c-host.js +113 -0
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +2 -1
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +26 -15
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +14 -5
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +5 -2
- package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +2 -0
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +7 -0
- package/src/tui-compiled/runtime/shared/c97089ed4243981c-host.js +113 -0
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +2 -1
- package/dist/index-3p1tc2e2.js +0 -91
- package/dist/index-3r9thx6n.js +0 -76
- package/dist/index-ya96m6wr.js +0 -64
- package/dist/token-util-807rzwws.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
|
|
2
|
+
import{c as o1}from"./index-d5v2rn54.js";import{Ha as f1,Ia as m,Ja as H,Ka as g,Mb as r1,cc as n1,pc as e1,ua as i1,va as y,wa as h,xa as c1}from"./index-0kpq9310.js";import{Fd as S,Gd as l,Id as R1,Kd as p,Ld as _,Md as l1,Nd as d,Od as k1,ke as a1}from"./index-h2z9jb3g.js";import"./index-3x7q1rj8.js";import"./index-2p3st53v.js";import"./index-bxxjwt4q.js";import{Jf as D1,Pf as q1,Rf as X1,Uf as s1}from"./index-7at0fc03.js";import"./index-dp68014q.js";import"./index-smzgsx6x.js";import"./index-4daebegf.js";import{spawn as z0}from"node:child_process";var R=4096,J0=1048576;class W1{buffer=Buffer.alloc(R);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=R){if(z.length>R||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-R),this.start=0,this.length=R;return}let J=Math.max(0,this.length+z.length-R);if(J>0)this.truncated=!0;this.start=(this.start+J)%R,this.length-=J;let Z=(this.start+this.length)%R,$=Math.min(z.length,R-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,R-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 G=performance.now(),Q=Z.timeoutMs??15000,K=new W1,q=[],W=0,b=!1,Y=!1,D=!1,B;try{B=z0(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()-G});return}let X=Q>0?setTimeout(()=>{D=!0,B.kill("SIGTERM")},Q):void 0;B.stdout?.on("data",(U)=>{let C=J0-W,j=Math.min(C,U.length);if(j>0)q.push(U.subarray(0,j)),W+=j;if(U.length>C)b=!0,B.kill("SIGTERM")}),B.stderr?.on("data",(U)=>K.push(U));let V=!1,F=(U,C)=>{if(V)return;if(V=!0,X)clearTimeout(X);$({exitCode:Y?1:b?1:U??1,stdout:Buffer.concat(q,W).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...Y?{spawnError:!0}:{},signal:C??null,timedOut:D,durationMs:performance.now()-G})};B.once("error",()=>{if(Y=!0,B.pid===void 0)F(null,null)}),B.once("close",(U,C)=>F(U,C))})}};function c(z,J,Z,$,G,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:G,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:G,timeoutMs:Q})}var Z0="Pi install failed; run pi install after checking your npm connection.";function $0(z){let J=Buffer.from(z,"utf8");if(J.length<=R)return z;let Z=J.length-R;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function G0(z){let J=z.indexOf(`
|
|
3
|
+
`);return J<0?"":z.slice(J+1)}class u extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(Z0);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?G0(z.stderrTail):z.stderrTail,Z=D1(J);this.stderrTail=$0(typeof Z==="string"?Z:"")}}var Q0={opencode:"OpenCode",pi:"Pi"},K0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function j1({host:z,outcome:J}){return`${Q0[z]}: ${K0[J]}`}var b0=new WeakMap;function Y1(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;b0.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as j0,constants as Y0,existsSync as B0,readFileSync as V0,realpathSync as x0,statSync as U0}from"node:fs";import{mkdtemp as F0,rm as H0}from"node:fs/promises";import{tmpdir as M0}from"node:os";import{join as O0}from"node:path";import{parse as C0}from"jsonc-parser";import{homedir as q0}from"node:os";import{posix as X0,win32 as W0}from"node:path";import{fileURLToPath as D0}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?W0:X0,G=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??q0(),Q=z.cwd??process.cwd(),K=(Y)=>$.resolve(Q,Y),q=J.OPENCODE_CONFIG_DIR?.trim(),W=J.XDG_CONFIG_HOME?.trim(),b=J.PI_CODING_AGENT_DIR?.trim()||$.join(G,".pi","agent");if(b==="~")b=G;else if(/^~[/\\]/.test(b))b=$.join(G,b.slice(2));if(b.startsWith("file://"))b=D0(b);return{env:J,platform:Z,path:$,home:G,cwd:Q,opencode:q?K(q):W?$.join(K(W),"opencode"):$.join(G,".config","opencode"),pi:K(b)}}function n(z,J){try{return U0(z)[J]()}catch{return!1}}var T={exists:B0,isFile:(z)=>n(z,"isFile"),isDirectory:(z)=>n(z,"isDirectory"),isExecutable(z){try{return j0(z,Y0.X_OK),n(z,"isFile")}catch{return!1}},readText:(z)=>V0(z,"utf8"),realpath:x0};function A(z,J={}){let{env:Z,platform:$,path:G,cwd:Q}=k(J),K=J.fs??T,q=Object.entries(Z).find(([b])=>$==="win32"?b.toUpperCase()==="PATH":b==="PATH")?.[1]??"",W=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let b of q.split($==="win32"?";":":")){let Y=b.trim().replace(/^"|"$/g,"");if(!Y)continue;for(let D of W){let B=G.resolve(Q,Y,z+D);if($==="win32"?K.isFile(B):K.isExecutable(B))return B}}return null}function B1(z={}){let{platform:J,home:Z,env:$,path:G}=k(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",G.join(Z,"Applications","OpenCode.app"),G.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.LOCALAPPDATA||G.join(Z,"AppData","Local");return[G.join(Q,"Programs","opencode"),G.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",G.join(Z,".local","share","applications","opencode.desktop")]}function o(z,J){let Z=J.fs??T,{path:$}=k(J);try{let G=Z.readText(z);if(G.length>65536)return z;let Q=[...G.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...G.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Q.at(-1)?.[1];if(K){let q=$.join($.dirname(z),...K.split(/[/\\]+/));if(Z.isFile(q))return Z.realpath(q)}return Z.realpath(z)}catch{return z}}function R0(z,J){let Z=J.fs??T,{path:$}=k(J),G=$.dirname(o(z,J));for(;;){try{let K=JSON.parse(Z.readText($.join(G,"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 Q=$.dirname(G);if(Q===G)return null;G=Q}}function V1(z={}){let J=A("opencode",z),Z=A("opencode2",z),$=J&&Z&&o(J,z)===o(Z,z),G=z.fs??T,{path:Q,opencode:K}=k(z),q="1";for(let b of["jsonc","json"]){let Y=Q.join(K,`opencode.${b}`);if(!G.exists(Y))continue;try{if(Object.hasOwn(C0(G.readText(Y))??{},"plugins"))q="2"}catch{}break}let W=J?R0(J,z)??($?"2":q):null;if(Z&&W==="1"&&!$)return"ambiguous";return Z||$?"2":W??q}async function t(z,J={}){let Z=J.fs??T,{env:$,platform:G,opencode:Q,pi:K}=k(J),q=J.runner??w,W=A("opencode",J)??A("opencode2",J),b=A("pi",J),Y=A("ck",J),D=async(F)=>{if(!F)return null;let U;try{U=await F0(O0(M0(),"common-auth-setup-version-"));let C={...$,HOME:U,USERPROFILE:U,XDG_CONFIG_HOME:U,XDG_DATA_HOME:U,XDG_STATE_HOME:U,XDG_CACHE_HOME:U,OPENCODE_CONFIG_DIR:U,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:U},j=await c(q,G,F,["--version"],C,2000);return j.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(j.stdout)?.[0]??null:null}catch{return null}finally{if(U)await H0(U,{recursive:!0,force:!0}).catch(()=>{})}},B=!1;if(Y&&Z.exists(z.vault.connectionFile))try{(await(J.connect??p)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),B=!0}catch{B=!1}let[X,V]=await Promise.all([D(W),D(b)]);return{opencode:{installed:Z.isDirectory(Q)||B1(J).some((F)=>Z.exists(F))||W!==null,executable:W,version:X,directory:Q,generation:V1(J)},pi:{installed:b!==null||Z.isDirectory(K),executable:b,version:V,directory:K},claustrum:{available:B,executable:Y}}}import{setTimeout as L0}from"node:timers/promises";import{writeEnrollmentTokenFile as P0}from"@cortexkit/claustrum-client";var x1=45000,e=new Set(["opencode","litecode","opencode2","pi"]),F1=new Set(["node","bun"]),k0=[...e,...F1].map((z)=>`Name LIKE '${z}%'`).join(" OR "),N0=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${k0}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,I0=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function A0(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function U1(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var w0=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"]),_0=new Set(["-e","--eval","-p","--print"]);function T0(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(_0.has($))return;if($.startsWith("-")){if(!$.includes("=")&&w0.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function H1(z){let[J,...Z]=A0(z);if(J===void 0)return null;let $=U1(J);if(e.has($))return $;if(!F1.has($))return null;let G=T0($,Z);if(G===void 0)return null;let Q=U1(G);if(e.has(Q))return Q;return I0.test(G)?"pi":null}class O 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 P extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:H1(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
|
|
4
4
|
${J.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=J,this.name="ProcessFenceViolationError"}}async function t(z=_,J={}){let Z=(J.platform??process.platform)==="win32",$=J.selfPid??process.pid,G={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(K,q,W,b)=>{let j=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let V=await z.run(q,W,{env:J.env,timeoutMs:b});return G={step:K,exitCode:V.exitCode,signal:V.signal??null,timedOut:V.timedOut??!1,durationMs:V.durationMs??performance.now()-j},V}finally{if(G.exitCode===null)G.durationMs=performance.now()-j;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let b=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",R1],Y0);if(b.exitCode!==0)throw new M(G);let j=JSON.parse(b.stdout);if(!j||typeof j!=="object"||!("complete"in j)||j.complete!==!0||!("processes"in j))throw new M(G);let V=j.processes,Y=V===null?[]:Array.isArray(V)?V:[V],X=[];for(let B of Y){if(!B||typeof B!=="object"||!("Name"in B)||typeof B.Name!=="string"||!("ProcessId"in B)||!Number.isSafeInteger(B.ProcessId)||B.ProcessId<0||!("CommandLine"in B))throw new M(G);let x=B.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(B.Name))X.push({pid:x,command:B.Name});else if(typeof B.CommandLine==="string")X.push({pid:x,command:B.CommandLine});else if(x!==$)throw new M(G)}return X}let K=await Q(Z?"tasklist":"ps",Z?"tasklist.exe":"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new M(G);let q=[];for(let b of K.stdout.split(/\r?\n/)){let j=b.trim();if(!j)continue;let V,Y;if(Z){let X=/^"([^"]+)","(\d+)"(?:,|$)/.exec(j);if(!X)throw new M(G);Y=X[1]??"",V=Number(X[2])}else{let X=/^(\d+)\s+(.+)$/.exec(j);if(!X){if(/^PID\s+COMMAND$/i.test(j))continue;throw new M(G)}V=Number(X[1]),Y=X[2]??""}if(!Number.isSafeInteger(V)||V<0)throw new M(G);q.push({pid:V,command:Y})}if(!q.length)throw new M(G);let W=q.filter((b)=>b.pid!==$&&/^(?:node|bun)\.exe$/i.test(b.command));if(Z&&W.length&&J.inspectRuntimes!==!1){let b=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`],Y0);if(b.exitCode!==0)throw new M(G);let j=JSON.parse(b.stdout||"null"),V=j===null?[]:Array.isArray(j)?j:[j],Y=new Map;for(let X of V){if(!X||typeof X!=="object"||!("ProcessId"in X)||!("CommandLine"in X)||!Number.isSafeInteger(X.ProcessId))throw new M(G);if(typeof X.CommandLine==="string")Y.set(Number(X.ProcessId),X.CommandLine);else if(W.some((B)=>B.pid===X.ProcessId))throw new M(G)}for(let X of W)X.command=Y.get(X.pid)??""}return q}catch(K){if(K instanceof M)throw K;throw new M(G)}}function v(z=_,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&F0(G.command)!==null;return{async listRunningHosts(G){return(await t(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await t(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((q)=>q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(q.command)).length:0}}}}async function E(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var L1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",R0='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.',N0=300000,x0=1000,H0=[1000,2000,4000,8000,16000,30000];function e(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class I extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=e(J.lastErrorCode)}}function O0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function k0(z,J,Z,$,G){let{name:Q,paths:K}=z.vault.hosts[J],q=w(K);await G();let W=await(Z.connect??c)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new I("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),b=Z.now??(()=>performance.now()),j=Z.wait??T1;try{let V=new C0({proposedName:Q,paths:q,client:W,writeTokenFile:async(U,O)=>{await G(),await w1(U,O)}});await G();let Y=await V.status();if(Y.state==="approved"){H($,`Already connected as ${Y.approvedName??Y.proposedName}.`);return}H($,`Asking the vault to connect ${Q}…`);let X=b()+N0,B,x,F,C=0;for(;;){let U=await V.reconcile();if(U.state==="approved"){H($,`Connected ${J} to Claustrum.`);return}if(U.state==="unavailable"&&U.code===M0)throw new I(R0,{reason:"unsupported-vault",lastErrorCode:U.code});if(U.state!=="pending"&&U.state!=="busy")throw new I("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in U&&{lastErrorCode:U.code}});let O=x0;if(U.state==="busy")x="busy";else if(U.retryCode)x=U.retryCode;if(U.state==="pending"&&U.requestId){if(C=0,U.requestId!==B){if(!/^[a-zA-Z0-9_-]+$/.test(U.requestId))throw new I("Invalid enrollment request id.",{reason:"invalid-request"});B=U.requestId,H($,"Waiting for approval. In another terminal, run:"),H($,` ${O0(U.requestId,Q)}`),H($,`Enrollment files: ${q.statePath}, ${q.tokenPath}`)}}else if(U.state==="pending"&&U.retryCode){O=H0[Math.min(C,H0.length-1)]??x0,C++;let y=e(U.retryCode);if(y!==F)F=y,H($,`The vault has not created the request yet (${y}); retrying.`)}let k=X-b();if(k<=0)break;await j(Math.min(O,k)),await G()}if(B)throw new I(`Claustrum approval is still pending. In another terminal, run: ${O0(B,Q)} and then rerun setup.`,{reason:"approval-pending",...x!==void 0&&{lastErrorCode:x}});let D=e(x);throw new I(`The vault never created the enrollment request (last error: ${D}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:D})}catch(V){if(V instanceof P||V instanceof M||V instanceof I)throw V;let Y=V?.code;throw new I(L1,{reason:"incomplete",...typeof Y==="string"&&{lastErrorCode:Y}})}finally{W.close()}}var I0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",P1=[{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 u(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function A0(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],G=$.indexOf("="),Q=G===-1?$:$.slice(0,G),K=P1.find((W)=>W.name===Q);if(!K)throw u($);if(!("values"in K)){if(G!==-1)throw u($);J[K.key]=!0;continue}let q;if(G!==-1)q=$.slice(G+1);else if(K.spaceForm)q=z[++Z];else throw u($);if(q===void 0||!K.values.includes(q))throw K.invalid?Error(K.invalid):u($);if(K.key==="hosts")J.hosts.push(q);else J.opencode=q}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function _0(z,J){let Z=new Set(J);for(;;){let $=await f(z,[...["opencode","pi"].map((G)=>({value:G,label:`[${Z.has(G)?"x":" "}] ${G==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(G)?"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 u1}from"node:url";import{applyEdits as z0,createScanner as p1,findNodeAtLocation as l1,modify as w0,parse as a1,parseTree as i1}from"jsonc-parser";import{randomUUID as S1}from"node:crypto";import{mkdir as y1,open as v1,rename as E1,stat as f1,unlink as g1}from"node:fs/promises";import{basename as m1,dirname as h1,join as d1}from"node:path";import{setTimeout as c1}from"node:timers/promises";async function T0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=h1(z);await y1(G,{recursive:!0});let Q;if(!$)try{Q=(await f1(z)).mode&4095}catch(W){if(W.code!=="ENOENT")throw W}let K=d1(G,`.${m1(z)}.${(Z.stageName??S1)()}.tmp`),q=!1;try{let W=await v1(K,"wx",Q??438);q=!0;try{if(await W.writeFile(J,"utf8"),Q!==void 0)await W.chmod(Q)}finally{await W.close()}let b=Z.now??(()=>performance.now()),j=b();for(let V=0;;V++){await Z.beforeRename?.();try{await(Z.rename??E1)(K,z),q=!1;return}catch(Y){let X=Y.code,B=2000-(b()-j);if(!$||!["EPERM","EBUSY","EACCES"].includes(X??"")||B<=0||V>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??c1)(Math.min(B,25*2**Math.min(V,2)))}}}finally{if(q)await g1(K).catch(()=>{})}}function P0(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function J0(z){let J=P0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function s1(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 G=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${u1(Z.hostname)}${G}`;if(!/^\\[a-z]:/i.test(G))throw Error("A Windows file URL must have an absolute drive path.");return G.slice(1)}function r1(z,J,Z){let{path:$,platform:G}=N(Z);try{let Q=/^file:\/\//i.test(z)?s1(z,G==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let K=JSON.parse((Z.fs??T).readText($.join(Q,"package.json")));return K&&typeof K==="object"&&"name"in K&&typeof K.name==="string"?K.name:null}catch{return null}}function S0(z,J){let Z=[],$=a1(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 $=i1(z),G=$&&l1($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let q=[{offset:K.offset,length:K.length,content:""}],W=(b,j)=>{let V=p1(z.slice(b,j),!0);if(V.scan(),z[b+V.getTokenOffset()]===",")q.push({offset:b+V.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let b=Q[Z-1];if(b)W(b.offset+b.length,K.offset);W(K.offset+K.length,G.offset+G.length-1)}else W(K.offset+K.length,Q[Z+1]?.offset??K.offset+K.length);return z0(z,q)}function y0(z,J,Z,$){let G=S0(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
|
|
7
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function z1(z=w,J={}){let Z=(J.platform??process.platform)==="win32",$=J.selfPid??process.pid,G={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(K,q,W,b)=>{let Y=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let D=await z.run(q,W,{env:J.env,timeoutMs:b});return G={step:K,exitCode:D.exitCode,signal:D.signal??null,timedOut:D.timedOut??!1,durationMs:D.durationMs??performance.now()-Y},D}finally{if(G.exitCode===null)G.durationMs=performance.now()-Y;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let b=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",N0],x1);if(b.exitCode!==0)throw new O(G);let Y=JSON.parse(b.stdout);if(!Y||typeof Y!=="object"||!("complete"in Y)||Y.complete!==!0||!("processes"in Y))throw new O(G);let D=Y.processes,B=D===null?[]:Array.isArray(D)?D:[D],X=[];for(let V of B){if(!V||typeof V!=="object"||!("Name"in V)||typeof V.Name!=="string"||!("ProcessId"in V)||!Number.isSafeInteger(V.ProcessId)||V.ProcessId<0||!("CommandLine"in V))throw new O(G);let F=V.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(V.Name))X.push({pid:F,command:V.Name});else if(typeof V.CommandLine==="string")X.push({pid:F,command:V.CommandLine});else if(F!==$)throw new O(G)}return X}let K=await Q(Z?"tasklist":"ps",Z?"tasklist.exe":"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new O(G);let q=[];for(let b of K.stdout.split(/\r?\n/)){let Y=b.trim();if(!Y)continue;let D,B;if(Z){let X=/^"([^"]+)","(\d+)"(?:,|$)/.exec(Y);if(!X)throw new O(G);B=X[1]??"",D=Number(X[2])}else{let X=/^(\d+)\s+(.+)$/.exec(Y);if(!X){if(/^PID\s+COMMAND$/i.test(Y))continue;throw new O(G)}D=Number(X[1]),B=X[2]??""}if(!Number.isSafeInteger(D)||D<0)throw new O(G);q.push({pid:D,command:B})}if(!q.length)throw new O(G);let W=q.filter((b)=>b.pid!==$&&/^(?:node|bun)\.exe$/i.test(b.command));if(Z&&W.length&&J.inspectRuntimes!==!1){let b=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`],x1);if(b.exitCode!==0)throw new O(G);let Y=JSON.parse(b.stdout||"null"),D=Y===null?[]:Array.isArray(Y)?Y:[Y],B=new Map;for(let X of D){if(!X||typeof X!=="object"||!("ProcessId"in X)||!("CommandLine"in X)||!Number.isSafeInteger(X.ProcessId))throw new O(G);if(typeof X.CommandLine==="string")B.set(Number(X.ProcessId),X.CommandLine);else if(W.some((V)=>V.pid===X.ProcessId))throw new O(G)}for(let X of W)X.command=B.get(X.pid)??""}return q}catch(K){if(K instanceof O)throw K;throw new O(G)}}function E(z=w,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&H1(G.command)!==null;return{async listRunningHosts(G){return(await z1(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await z1(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((q)=>q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(q.command)).length:0}}}}async function f(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var S0="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",N1='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.',I1=300000,M1=1000,O1=[1000,2000,4000,8000,16000,30000];function J1(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class I extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=J1(J.lastErrorCode)}}function C1(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function A1(z,J,Z,$,G){if(l())throw Error(S);let{name:Q,paths:K}=z.vault.hosts[J],q=_(K);await G();let W=await(Z.connect??p)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new I("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),b=Z.now??(()=>performance.now()),Y=Z.wait??L0;try{let D=new k1({proposedName:Q,paths:q,client:W,writeTokenFile:async(x,M)=>{await G(),await P0(x,M)}});await G();let B=await D.status();if(B.state==="approved"){H($,`Already connected as ${B.approvedName??B.proposedName}.`);return}H($,`Asking the vault to connect ${Q}…`);let X=b()+I1,V,F,U,C=0;for(;;){let x=await D.reconcile();if(x.state==="approved"){H($,`Connected ${J} to Claustrum.`);return}if(x.state==="unavailable"&&x.code===R1)throw new I(N1,{reason:"unsupported-vault",lastErrorCode:x.code});if(x.state!=="pending"&&x.state!=="busy")throw new I("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in x&&{lastErrorCode:x.code}});let M=M1;if(x.state==="busy")F="busy";else if(x.retryCode)F=x.retryCode;if(x.state==="pending"&&x.requestId){if(C=0,x.requestId!==V){if(!/^[a-zA-Z0-9_-]+$/.test(x.requestId))throw new I("Invalid enrollment request id.",{reason:"invalid-request"});V=x.requestId,H($,"Waiting for approval. In another terminal, run:"),H($,` ${C1(x.requestId,Q)}`),H($,`Enrollment files: ${q.statePath}, ${q.tokenPath}`)}}else if(x.state==="pending"&&x.retryCode){M=O1[Math.min(C,O1.length-1)]??M1,C++;let v=J1(x.retryCode);if(v!==U)U=v,H($,`The vault has not created the request yet (${v}); retrying.`)}let N=X-b();if(N<=0)break;await Y(Math.min(M,N)),await G()}if(V)throw new I(`Claustrum approval is still pending. In another terminal, run: ${C1(V,Q)} and then rerun setup.`,{reason:"approval-pending",...F!==void 0&&{lastErrorCode:F}});let j=J1(F);throw new I(`The vault never created the enrollment request (last error: ${j}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:j})}catch(D){if(D instanceof P||D instanceof O||D instanceof I)throw D;let B=D?.code;throw new I(S0,{reason:"incomplete",...typeof B==="string"&&{lastErrorCode:B}})}finally{W.close()}}var w1="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",y0=[{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 a(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function _1(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],G=$.indexOf("="),Q=G===-1?$:$.slice(0,G),K=y0.find((W)=>W.name===Q);if(!K)throw a($);if(!("values"in K)){if(G!==-1)throw a($);J[K.key]=!0;continue}let q;if(G!==-1)q=$.slice(G+1);else if(K.spaceForm)q=z[++Z];else throw a($);if(q===void 0||!K.values.includes(q))throw K.invalid?Error(K.invalid):a($);if(K.key==="hosts")J.hosts.push(q);else J.opencode=q}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function T1(z,J){let Z=new Set(J);for(;;){let $=await g(z,[...["opencode","pi"].map((G)=>({value:G,label:`[${Z.has(G)?"x":" "}] ${G==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(G)?"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 l0}from"node:url";import{applyEdits as Z1,createScanner as a0,findNodeAtLocation as i0,modify as P1,parse as s0,parseTree as r0}from"jsonc-parser";import{randomUUID as v0}from"node:crypto";import{mkdir as E0,open as f0,rename as g0,stat as m0,unlink as d0}from"node:fs/promises";import{basename as h0,dirname as c0,join as u0}from"node:path";import{setTimeout as p0}from"node:timers/promises";async function L1(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=c0(z);await E0(G,{recursive:!0});let Q;if(!$)try{Q=(await m0(z)).mode&4095}catch(W){if(W.code!=="ENOENT")throw W}let K=u0(G,`.${h0(z)}.${(Z.stageName??v0)()}.tmp`),q=!1;try{let W=await f0(K,"wx",Q??438);q=!0;try{if(await W.writeFile(J,"utf8"),Q!==void 0)await W.chmod(Q)}finally{await W.close()}let b=Z.now??(()=>performance.now()),Y=b();for(let D=0;;D++){await Z.beforeRename?.();try{await(Z.rename??g0)(K,z),q=!1;return}catch(B){let X=B.code,V=2000-(b()-Y);if(!$||!["EPERM","EBUSY","EACCES"].includes(X??"")||V<=0||D>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??p0)(Math.min(V,25*2**Math.min(D,2)))}}}finally{if(q)await d0(K).catch(()=>{})}}function y1(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 $1(z){let J=y1(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function n0(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 G=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${l0(Z.hostname)}${G}`;if(!/^\\[a-z]:/i.test(G))throw Error("A Windows file URL must have an absolute drive path.");return G.slice(1)}function o0(z,J,Z){let{path:$,platform:G}=k(Z);try{let Q=/^file:\/\//i.test(z)?n0(z,G==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let K=JSON.parse((Z.fs??T).readText($.join(Q,"package.json")));return K&&typeof K==="object"&&"name"in K&&typeof K.name==="string"?K.name:null}catch{return null}}function v1(z,J){let Z=[],$=s0(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 S1(z,J,Z){let $=r0(z),G=$&&i0($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let q=[{offset:K.offset,length:K.length,content:""}],W=(b,Y)=>{let D=a0(z.slice(b,Y),!0);if(D.scan(),z[b+D.getTokenOffset()]===",")q.push({offset:b+D.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let b=Q[Z-1];if(b)W(b.offset+b.length,K.offset);W(K.offset+K.length,G.offset+G.length-1)}else W(K.offset+K.length,Q[Z+1]?.offset??K.offset+K.length);return Z1(z,q)}function E1(z,J,Z,$){let G=v1(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
|
|
8
8
|
`)?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`}},K=z,q=G[J],W=Array.isArray(q)?[...q]:[],b=W.flatMap((
|
|
11
|
-
`,
|
|
12
|
-
${
|
|
13
|
-
ck auth grant --principal enrolled:${b} --selector-kind category --selector ${
|
|
14
|
-
${X.instructions}`);let
|
|
10
|
+
`}},K=z,q=G[J],W=Array.isArray(q)?[...q]:[],b=W.flatMap((B,X)=>$1(B)===Z?[X]:[]),Y=`${Z}@${$}`;if(!b.length)K=Z1(K,P1(K,q===void 0?[J]:[J,W.length],q===void 0?[Y]:Y,Q));else{let B=b[0],X=W[B],V=Array.isArray(X)?[Y,...X.slice(1)]:X&&typeof X==="object"?{...X,package:Y}:Y;if(JSON.stringify(X)!==JSON.stringify(V))K=Z1(K,P1(K,[J,B],V,Q));for(let F of b.slice(1).reverse())K=S1(K,J,F)}let D=J==="plugin"?"plugins":"plugin";if(Array.isArray(G[D])){let B=G[D];for(let X=B.length-1;X>=0;X--)if($1(B[X])===Z)K=S1(K,D,X)}return K}function G1(z,J,Z={}){let $=Z.fs??T,{path:G,opencode:Q}=k(Z),K=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((W)=>{let b=G.join(Q,`${W}.jsonc`),Y=G.join(Q,`${W}.json`),D=$.exists(b)?b:$.exists(Y)?Y:b,B=$.exists(D),X=B?$.readText(D):`${JSON.stringify({$schema:`https://opencode.ai/${W==="tui"?"tui":"config"}.json`},null,2)}
|
|
11
|
+
`,V=v1(X,K),F=[],U=[];for(let j of["plugin","plugins"]){if(!Array.isArray(V[j]))continue;for(let x of V[j]){let M=y1(x);if(M===null)continue;if(o0(M,D,Z)===z.packages.opencode)F.push(JSON.stringify(x));else if($1(x)===z.packages.opencode)U.push(JSON.stringify(x))}}if(F.length>0)return{path:D,content:X,changed:!1,existingLocalEntries:F,existingNpmEntries:U};let C=E1(X,K,z.packages.opencode,z.version);return{path:D,content:C,changed:!B||C!==X}})}async function Q1(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await L1(Z.path,Z.content,{beforeRename:J})}}async function K1(z,J,Z={}){let{platform:$,env:G}=k(Z),Q=await c(Z.runner??w,$,J,["install",`npm:${z.packages.pi}@${z.version}`],G);if(Q.exitCode!==0||Q.timedOut)throw new u({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var g1="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function t0(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.")}async function e0(z,J,Z){let $=[];for(let G of J){let Q=Z.get(G)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:q}=z.vault.hosts[G],W=await d(_(q),K).catch(()=>"unreadable");if(W==="vault"||W==="host")Q="enrolled";else if(W==="local")Q="not-enrolled"}$.push({host:G,outcome:Q})}return $}async function b1(z,J=[],Z={}){let $=_1(J);if(l())throw Error(S);t0(z);let G=Z.terminal??f1(),Q=await t(z,Z);H(G,`${z.displayName} setup`);for(let[j,x]of[["OpenCode",Q.opencode],["Pi",Q.pi]])H(G,`${j}: ${x.installed?`found (version ${x.version??"unknown"})`:"not found"} — ${x.directory}`);H(G,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)H(G,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let q=["opencode","pi"].filter((j)=>Q[j].installed&&!(j==="pi"&&K));if($.hosts.some((j)=>!q.includes(j)))throw Error(w1);let W=$.yes||$.dryRun&&!m(G);if(!W&&!m(G))throw Error("Setup requires a TTY or --yes.");let b=$.hosts.length?q.filter((j)=>$.hosts.includes(j)):W?q:await T1(G,q)??[],Y=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(b.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(W||!m(G))throw Error(g1);let j=await g(G,[{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(j===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};Y=j}if(!b.length)return H(G,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:b,dryRun:$.dryRun,mode:"local",detection:Q};let{env:D,platform:B}=k(Z),X=Z.fence??E(Z.runner??w,{platform:B}),V=async()=>{try{await f(X,D)}catch(j){if(j instanceof O)H(G,j.refusalText);throw j}};if(H(G,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let j=X.previewRunningHosts?await X.previewRunningHosts(D):{hosts:await X.listRunningHosts(D),uncheckedRuntimes:0},x=j.hosts;if(j.uncheckedRuntimes>0)H(G,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let M=new Set(new P(x).activeHosts.map((N)=>N.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let N of M)H(G,`${N} is running; setup will ask you to quit it.`)}catch(j){if(H(G,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),j instanceof O)H(G,j.refusalText)}else await V();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 F=$.claustrum||$.enrollOnly;if(!F&&!$.login&&!$.noClaustrum&&!W&&Q.claustrum.available&&m(G)){let j=await g(G,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(j===null)return H(G,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};F=j===!0}let U=F?"claustrum":"local",C=!$.enrollOnly&&b.includes("opencode")?G1(z,Y,Z):[];for(let j of C){for(let M of j.existingLocalEntries??[])H(G,`OpenCode: already registered from ${M} in ${j.path}.`);let x=[...j.existingLocalEntries??[],...j.existingNpmEntries??[]];if(x.length>1)H(G,`Warning: ${z.displayName} may load twice in ${j.path}: ${x.join(", ")}. Entries were left unchanged.`)}if($.dryRun){H(G,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let j of b){if(z.beforeSignIn)H(G,`Would run beforeSignIn(${j}, ${U}).`);if(F){let x=_(z.vault.hosts[j].paths);H(G,`Would Connect ${j}: write ${x.statePath} and ${x.tokenPath}; wait for ck auth enroll approve.`)}else H(G,`Would sign in locally for ${j}.`);if(!$.enrollOnly&&z.beforeRegister)H(G,`Would run beforeRegister(${j}, ${U}).`)}for(let j of C)H(G,`${j.changed?"Would write":"Unchanged"} ${j.path}:
|
|
12
|
+
${j.content}`);if(!$.enrollOnly&&b.includes("pi"))H(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let j of b)H(G,`Would migrate ${j} using the plugin callback (provider-specific writes).`)}else{let j={opencodeGeneration:Y,mode:U,hosts:Object.freeze([...b]),piAgentDir:Q.pi.directory},x=new Map;try{for(let M of b){if(await V(),await z.beforeSignIn?.(M,j),await V(),F){x.set(M,"unknown");try{await A1(z,M,Z,G,V)}catch(N){if(N instanceof I)x.set(M,"not-enrolled");throw N}x.set(M,"enrolled")}else await z.signInLocal(M,j);if(await V(),$.enrollOnly)continue;if(await z.beforeRegister?.(M,U,j),await V(),M==="opencode")await Q1(C,V);else await K1(z,Q.pi.executable,Z);await V(),await z.migrate?.(M,j)}}catch(M){if(x.size===0)throw M;try{let N=await e0(z,b,x);Y1(M,N);for(let v of N)H(G,j1(v))}catch{}throw M}}if(H(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${b.join(", ")} (${U}).`),$.enrollOnly)H(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),H(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else H(G,`Next: ${b.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:b,dryRun:$.dryRun,mode:U,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.11.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.41.1","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.5"},dependencies:{"@cortexkit/claustrum-client":"^0.16.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.7.0","@opentui/solid":">=0.7.0",ai:"^7.0.159","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as Q2}from"node:path";import{resolveClaustrumConnectionPath as K2}from"@cortexkit/claustrum-client";var m1={name:"@cortexkit/pi-openai-auth",version:"1.11.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.41.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.16.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 i}from"node:fs";import{homedir as s}from"node:os";import{join as r,resolve as d1}from"node:path";import{fileURLToPath as Z2}from"node:url";var h1=new Set;function $2(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return r(s(),".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 s();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return r(s(),z.slice(2));return z.startsWith("file://")?Z2(z):z}function u1(z=$2()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=r(z,q1),$=r(s(),".pi","agent",q1),G=(K)=>{let q=X1(K),W=c1(h(q),"pi");return i(K)||i(q)||i(W.tokenPath)||i(W.statePath)};if(d1(Z)===d1($)||G(Z)||!G($))return Z;let Q=`${Z}\x00${$}`;if(!h1.has(Q))h1.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 G2(z=u1()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||X1(z)}function p1(z=u1()){return{configPath:z,statePath:G2(z)}}function t1(z={}){let J=z.print??console.log,Z=z.fence??E(),$={opencode:{stateDir:h(r1().statePath),host:"opencode"},pi:{stateDir:h(p1().statePath),host:"pi"}},G=async(Q)=>{let K=await d(_($[Q]),y(Q));if(K==="host")throw Error(S);if(K!=="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:m1.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:K2(),hosts:{opencode:{name:y("opencode"),paths:$.opencode},pi:{name:y("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(await d(_($[Q]),y(Q))==="host")throw Error(S);if(K==="claustrum"){let q=await l1(_($[Q]),y(Q)),W=q.state==="approved"?q.approvedName:void 0,b=W??("proposedName"in q?q.proposedName:y(Q));if(!W)J("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(J(`Allow this host to read OpenAI accounts with:
|
|
13
|
+
ck auth grant --principal enrolled:${b} --selector-kind category --selector ${i1.category} --operation read`),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 G(Q)},async signInLocal(Q,K){if(await G(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let U=Q2(A("opencode2",z.io)??A("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${U} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(K.opencodeGeneration==="2")return;if(n1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let q=o1(),W={path:{id:"openai"}};if(await q.get(W)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let b=z.beginLogin??a1,Y=new AbortController,D=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),B={version:L.version,signal:Y.signal},X,V=!D;try{X=await b({...B,headless:D})}catch(U){if(D)throw U;V=!1,J("Browser callback unavailable; using device-code sign-in."),X=await b({version:L.version,headless:!0})}if(V){if(!(z.openBrowser??s1)(X.url))Y.abort(),await X.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),X=await b({version:L.version,headless:!0})}J(`${X.url}
|
|
14
|
+
${X.instructions}`);let F=await X.completion;await f(Z),await G(Q),await q.set({...W,body:{type:"oauth",access:F.access,refresh:F.refresh,expires:F.expires,...F.accountId?{accountId:F.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 e1({version:L.version}),await b1(t1(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
|
|
@@ -770,8 +770,8 @@ declare class OpenAiVault {
|
|
|
770
770
|
readonly name: string;
|
|
771
771
|
readonly paths: VaultPaths;
|
|
772
772
|
constructor(options: OpenAiVaultOptions);
|
|
773
|
-
/** Read
|
|
774
|
-
authority(): Promise<'vault' | 'local' | 'unreadable'>;
|
|
773
|
+
/** Read authority before a request, menu action or background pass, including changes to the host marker. */
|
|
774
|
+
authority(): Promise<'host' | 'vault' | 'local' | 'unreadable'>;
|
|
775
775
|
/**
|
|
776
776
|
* Callbacks that cannot await use the last authority value only while the
|
|
777
777
|
* enrollment files are unchanged. Before the first read, or after a change,
|