@cortexkit/opencode-openai-auth 1.8.3 → 1.8.4
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-GJkvxv4S.d.ts → codex-request-C78nXs79.d.ts} +1 -1
- package/dist/{index-dw6yd976.js → index-1htk005d.js} +2 -2
- package/dist/{index-c50p5mem.js → index-5wgxt362.js} +1 -1
- package/dist/{index-fyrgwfx3.js → index-a5h82jha.js} +2 -2
- package/dist/{index-hpnj460b.js → index-byz2j6hz.js} +1 -1
- package/dist/{index-0v7ar02e.js → index-e7gekawr.js} +1 -1
- package/dist/{index-g556s1mz.js → index-hnmbhgk4.js} +2 -2
- package/dist/{index-rw932qm9.js → index-hvmj07f7.js} +21 -21
- package/dist/{index-z81cged1.js → index-k7zb6wa7.js} +2 -2
- package/dist/{index-b0s5cty6.js → index-kemp2vh4.js} +2 -2
- package/dist/{index-p8m4yh73.js → index-kphzmgq6.js} +1 -1
- package/dist/index-nsdjapq1.js +2 -0
- package/dist/{index-yt52fztj.js → index-pg5c6by3.js} +2 -2
- package/dist/{index-bej7x30p.js → index-t8248wa4.js} +7 -7
- package/dist/index.d.ts +2 -2
- 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-DkNebAiC.d.ts → sidebar-state-CrRiE9hw.d.ts} +3 -1
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-3vtr29vt.js → token-j2jmx8k7.js} +1 -1
- package/dist/token-util-7n2nfbyc.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +1 -1
- package/src/tui-compiled/raw/sidebar-state.js +10 -6
- package/src/tui-compiled/raw/tui.tsx +37 -27
- package/src/tui-compiled/runtime/sidebar-state.js +10 -6
- package/src/tui-compiled/runtime/tui.js +39 -55
- package/dist/index-03hs0rq7.js +0 -2
- package/dist/token-util-erhrf24m.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 h extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(
|
|
2
|
+
import{c as s0}from"./index-e7gekawr.js";import{Aa as y0,Ba as f,Ca as F,Da as E,Lb as n0,hb as a0,na as p0,oa as S,pa as g,qa as m0,zb as i0}from"./index-hvmj07f7.js";import{nd as c0,td as O0,vd as d,wd as w,xd as u0,yd as u,zd as M0}from"./index-kemp2vh4.js";import"./index-a5h82jha.js";import"./index-k7zb6wa7.js";import"./index-pg5c6by3.js";import{Ze as q0,df as Q0,ff as K0,if as l0}from"./index-1htk005d.js";import"./index-hnmbhgk4.js";import"./index-5wgxt362.js";import"./index-byz2j6hz.js";import{spawn as t0}from"node:child_process";var N=4096,e0=1048576;class b0{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=N){if(z.length>N||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-N),this.start=0,this.length=N;return}let J=Math.max(0,this.length+z.length-N);if(J>0)this.truncated=!0;this.start=(this.start+J)%N,this.length-=J;let Z=(this.start+this.length)%N,$=Math.min(z.length,N-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,N-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var _={run(z,J,Z={}){return new Promise(($)=>{let G=performance.now(),Q=Z.timeoutMs??15000,K=new b0,W=[],V=0,q=!1,j=!1,D=!1,Y;try{Y=t0(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,Y.kill("SIGTERM")},Q):void 0;Y.stdout?.on("data",(U)=>{let C=e0-V,b=Math.min(C,U.length);if(b>0)W.push(U.subarray(0,b)),V+=b;if(U.length>C)q=!0,Y.kill("SIGTERM")}),Y.stderr?.on("data",(U)=>K.push(U));let B=!1,x=(U,C)=>{if(B)return;if(B=!0,X)clearTimeout(X);$({exitCode:j?1:q?1:U??1,stdout:Buffer.concat(W,V).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...j?{spawnError:!0}:{},signal:C??null,timedOut:D,durationMs:performance.now()-G})};Y.once("error",()=>{if(j=!0,Y.pid===void 0)x(null,null)}),Y.once("close",(U,C)=>x(U,C))})}};function m(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 z2="Pi install failed; run pi install after checking your npm connection.";function J2(z){let J=Buffer.from(z,"utf8");if(J.length<=N)return z;let Z=J.length-N;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function Z2(z){let J=z.indexOf(`
|
|
3
|
+
`);return J<0?"":z.slice(J+1)}class h extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(z2);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?Z2(z.stderrTail):z.stderrTail,Z=q0(J);this.stderrTail=J2(typeof Z==="string"?Z:"")}}var $2={opencode:"OpenCode",pi:"Pi"},G2={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function X0({host:z,outcome:J}){return`${$2[z]}: ${G2[J]}`}var Q2=new WeakMap;function W0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;Q2.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as W2,constants as V2,existsSync as D2,readFileSync as j2,realpathSync as Y2,statSync as B2}from"node:fs";import{mkdtemp as U2,rm as F2}from"node:fs/promises";import{tmpdir as x2}from"node:os";import{join as H2}from"node:path";import{parse as O2}from"jsonc-parser";import{homedir as K2}from"node:os";import{posix as b2,win32 as q2}from"node:path";import{fileURLToPath as X2}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?q2:b2,G=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??K2(),Q=z.cwd??process.cwd(),K=(j)=>$.resolve(Q,j),W=J.OPENCODE_CONFIG_DIR?.trim(),V=J.XDG_CONFIG_HOME?.trim(),q=J.PI_CODING_AGENT_DIR?.trim()||$.join(G,".pi","agent");if(q==="~")q=G;else if(/^~[/\\]/.test(q))q=$.join(G,q.slice(2));if(q.startsWith("file://"))q=X2(q);return{env:J,platform:Z,path:$,home:G,cwd:Q,opencode:W?K(W):V?$.join(K(V),"opencode"):$.join(G,".config","opencode"),pi:K(q)}}function i(z,J){try{return B2(z)[J]()}catch{return!1}}var T={exists:D2,isFile:(z)=>i(z,"isFile"),isDirectory:(z)=>i(z,"isDirectory"),isExecutable(z){try{return W2(z,V2.X_OK),i(z,"isFile")}catch{return!1}},readText:(z)=>j2(z,"utf8"),realpath:Y2};function A(z,J={}){let{env:Z,platform:$,path:G,cwd:Q}=k(J),K=J.fs??T,W=Object.entries(Z).find(([q])=>$==="win32"?q.toUpperCase()==="PATH":q==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let q of W.split($==="win32"?";":":")){let j=q.trim().replace(/^"|"$/g,"");if(!j)continue;for(let D of V){let Y=G.resolve(Q,j,z+D);if($==="win32"?K.isFile(Y):K.isExecutable(Y))return Y}}return null}function V0(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 s(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 W=$.join($.dirname(z),...K.split(/[/\\]+/));if(Z.isFile(W))return Z.realpath(W)}return Z.realpath(z)}catch{return z}}function M2(z,J){let Z=J.fs??T,{path:$}=k(J),G=$.dirname(s(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 D0(z={}){let J=A("opencode",z),Z=A("opencode2",z),$=J&&Z&&s(J,z)===s(Z,z),G=z.fs??T,{path:Q,opencode:K}=k(z),W="1";for(let q of["jsonc","json"]){let j=Q.join(K,`opencode.${q}`);if(!G.exists(j))continue;try{if(Object.hasOwn(O2(G.readText(j))??{},"plugins"))W="2"}catch{}break}let V=J?M2(J,z)??($?"2":W):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??W}async function r(z,J={}){let Z=J.fs??T,{env:$,platform:G,opencode:Q,pi:K}=k(J),W=J.runner??_,V=A("opencode",J)??A("opencode2",J),q=A("pi",J),j=A("ck",J),D=async(x)=>{if(!x)return null;let U;try{U=await U2(H2(x2(),"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},b=await m(W,G,x,["--version"],C,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(U)await F2(U,{recursive:!0,force:!0}).catch(()=>{})}},Y=!1;if(j&&Z.exists(z.vault.connectionFile))try{(await(J.connect??d)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),Y=!0}catch{Y=!1}let[X,B]=await Promise.all([D(V),D(q)]);return{opencode:{installed:Z.isDirectory(Q)||V0(J).some((x)=>Z.exists(x))||V!==null,executable:V,version:X,directory:Q,generation:D0(J)},pi:{installed:q!==null||Z.isDirectory(K),executable:q,version:B,directory:K},claustrum:{available:Y,executable:j}}}import{setTimeout as T2}from"node:timers/promises";import{writeEnrollmentTokenFile as w2}from"@cortexkit/claustrum-client";var j0=45000,n=new Set(["opencode","litecode","opencode2","pi"]),B0=new Set(["node","bun"]),C2=[...n,...B0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),R2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${C2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,N2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function k2(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function Y0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var I2=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"]),A2=new Set(["-e","--eval","-p","--print"]);function _2(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(A2.has($))return;if($.startsWith("-")){if(!$.includes("=")&&I2.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function U0(z){let[J,...Z]=k2(z);if(J===void 0)return null;let $=Y0(J);if(n.has($))return $;if(!B0.has($))return null;let G=_2($,Z);if(G===void 0)return null;let Q=Y0(G);if(n.has(Q))return Q;return N2.test(G)?"pi":null}class M 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:U0(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 i(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,D,V,q)=>{let j=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let W=await z.run(D,V,{env:J.env,timeoutMs:q});return G={step:K,exitCode:W.exitCode,signal:W.signal??null,timedOut:W.timedOut??!1,durationMs:W.durationMs??performance.now()-j},W}finally{if(G.exitCode===null)G.durationMs=performance.now()-j;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",F2],q0);if(q.exitCode!==0)throw new M(G);let j=JSON.parse(q.stdout);if(!j||typeof j!=="object"||!("complete"in j)||j.complete!==!0||!("processes"in j))throw new M(G);let W=j.processes,U=W===null?[]:Array.isArray(W)?W:[W],X=[];for(let Y of U){if(!Y||typeof Y!=="object"||!("Name"in Y)||typeof Y.Name!=="string"||!("ProcessId"in Y)||!Number.isSafeInteger(Y.ProcessId)||Y.ProcessId<0||!("CommandLine"in Y))throw new M(G);let F=Y.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(Y.Name))X.push({pid:F,command:Y.Name});else if(typeof Y.CommandLine==="string")X.push({pid:F,command:Y.CommandLine});else if(F!==$)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 D=[];for(let q of K.stdout.split(/\r?\n/)){let j=q.trim();if(!j)continue;let W,U;if(Z){let X=/^"([^"]+)","(\d+)"(?:,|$)/.exec(j);if(!X)throw new M(G);U=X[1]??"",W=Number(X[2])}else{let X=/^(\d+)\s+(.+)$/.exec(j);if(!X){if(/^PID\s+COMMAND$/i.test(j))continue;throw new M(G)}W=Number(X[1]),U=X[2]??""}if(!Number.isSafeInteger(W)||W<0)throw new M(G);D.push({pid:W,command:U})}if(!D.length)throw new M(G);let V=D.filter((q)=>q.pid!==$&&/^(?:node|bun)\.exe$/i.test(q.command));if(Z&&V.length&&J.inspectRuntimes!==!1){let q=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`],q0);if(q.exitCode!==0)throw new M(G);let j=JSON.parse(q.stdout||"null"),W=j===null?[]:Array.isArray(j)?j:[j],U=new Map;for(let X of W){if(!X||typeof X!=="object"||!("ProcessId"in X)||!("CommandLine"in X)||!Number.isSafeInteger(X.ProcessId))throw new M(G);if(typeof X.CommandLine==="string")U.set(Number(X.ProcessId),X.CommandLine);else if(V.some((Y)=>Y.pid===X.ProcessId))throw new M(G)}for(let X of V)X.command=U.get(X.pid)??""}return D}catch(K){if(K instanceof M)throw K;throw new M(G)}}function y(z=_,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&W0(G.command)!==null;return{async listRunningHosts(G){return(await i(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await i(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((D)=>D.pid!==Z&&/^(?:node|bun)\.exe$/i.test(D.command)).length:0}}}}async function v(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var A2="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",x0='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,V0=1000,j0=[1000,2000,4000,8000,16000,30000];function s(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class A extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=s(J.lastErrorCode)}}function U0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function H0(z,J,Z,$,G){let{name:Q,paths:K}=z.vault.hosts[J],D=w(K);await G();let V=await(Z.connect??m)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new A("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),q=Z.now??(()=>performance.now()),j=Z.wait??N2;try{let W=new B0({proposedName:Q,paths:D,client:V,writeTokenFile:async(b,H)=>{await G(),await k2(b,H)}});x($,`Asking the vault to connect ${Q}…`);let U=q()+F0,X,Y,F,B=0;for(;;){await G();let b=await W.reconcile();if(b.state==="approved"){x($,`Connected ${J} to Claustrum.`);return}if(b.state==="unavailable"&&b.code===Y0)throw new A(x0,{reason:"unsupported-vault",lastErrorCode:b.code});if(b.state!=="pending"&&b.state!=="busy")throw new A("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in b&&{lastErrorCode:b.code}});let H=V0;if(b.state==="busy")Y="busy";else if(b.retryCode)Y=b.retryCode;if(b.state==="pending"&&b.requestId){if(B=0,b.requestId!==X){if(!/^[a-zA-Z0-9_-]+$/.test(b.requestId))throw new A("Invalid enrollment request id.",{reason:"invalid-request"});X=b.requestId,x($,"Waiting for approval. In another terminal, run:"),x($,` ${U0(b.requestId,Q)}`),x($,`Enrollment files: ${D.statePath}, ${D.tokenPath}`)}}else if(b.state==="pending"&&b.retryCode){H=j0[Math.min(B,j0.length-1)]??V0,B++;let R=s(b.retryCode);if(R!==F)F=R,x($,`The vault has not created the request yet (${R}); retrying.`)}let O=U-q();if(O<=0)break;await j(Math.min(H,O))}if(X)throw new A(`Claustrum approval is still pending. In another terminal, run: ${U0(X,Q)} and then rerun setup.`,{reason:"approval-pending",...Y!==void 0&&{lastErrorCode:Y}});let C=s(Y);throw new A(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(W){if(W instanceof P||W instanceof M||W instanceof A)throw W;let U=W?.code;throw new A(A2,{reason:"incomplete",...typeof U==="string"&&{lastErrorCode:U}})}finally{V.close()}}var O0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",I2=[{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 d(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function M0(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=I2.find((V)=>V.name===Q);if(!K)throw d($);if(!("values"in K)){if(G!==-1)throw d($);J[K.key]=!0;continue}let D;if(G!==-1)D=$.slice(G+1);else if(K.spaceForm)D=z[++Z];else throw d($);if(D===void 0||!K.values.includes(D))throw K.invalid?Error(K.invalid):d($);if(K.key==="hosts")J.hosts.push(D);else J.opencode=D}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 C0(z,J){let Z=new Set(J);for(;;){let $=await E(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 g2}from"node:url";import{applyEdits as r,createScanner as h2,findNodeAtLocation as m2,modify as N0,parse as d2,parseTree as c2}from"jsonc-parser";import{randomUUID as _2}from"node:crypto";import{mkdir as T2,open as w2,rename as L2,stat as P2,unlink as S2}from"node:fs/promises";import{basename as y2,dirname as v2,join as E2}from"node:path";import{setTimeout as f2}from"node:timers/promises";async function R0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=v2(z);await T2(G,{recursive:!0});let Q;if(!$)try{Q=(await P2(z)).mode&4095}catch(V){if(V.code!=="ENOENT")throw V}let K=E2(G,`.${y2(z)}.${(Z.stageName??_2)()}.tmp`),D=!1;try{let V=await w2(K,"wx",Q??438);D=!0;try{if(await V.writeFile(J,"utf8"),Q!==void 0)await V.chmod(Q)}finally{await V.close()}let q=Z.now??(()=>performance.now()),j=q();for(let W=0;;W++){await Z.beforeRename?.();try{await(Z.rename??L2)(K,z),D=!1;return}catch(U){let X=U.code,Y=2000-(q()-j);if(!$||!["EPERM","EBUSY","EACCES"].includes(X??"")||Y<=0||W>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??f2)(Math.min(Y,25*2**Math.min(W,2)))}}}finally{if(D)await S2(K).catch(()=>{})}}function A0(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 n(z){let J=A0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function u2(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`\\\\${g2(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 p2(z,J,Z){let{path:$,platform:G}=k(Z);try{let Q=/^file:\/\//i.test(z)?u2(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 I0(z,J){let Z=[],$=d2(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 k0(z,J,Z){let $=c2(z),G=$&&m2($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let D=[{offset:K.offset,length:K.length,content:""}],V=(q,j)=>{let W=h2(z.slice(q,j),!0);if(W.scan(),z[q+W.getTokenOffset()]===",")D.push({offset:q+W.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let q=Q[Z-1];if(q)V(q.offset+q.length,K.offset);V(K.offset+K.length,G.offset+G.length-1)}else V(K.offset+K.length,Q[Z+1]?.offset??K.offset+K.length);return r(z,D)}function _0(z,J,Z,$){let G=I0(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 o(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,W,V,q)=>{let j=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let D=await z.run(W,V,{env:J.env,timeoutMs:q});return G={step:K,exitCode:D.exitCode,signal:D.signal??null,timedOut:D.timedOut??!1,durationMs:D.durationMs??performance.now()-j},D}finally{if(G.exitCode===null)G.durationMs=performance.now()-j;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",R2],j0);if(q.exitCode!==0)throw new M(G);let j=JSON.parse(q.stdout);if(!j||typeof j!=="object"||!("complete"in j)||j.complete!==!0||!("processes"in j))throw new M(G);let D=j.processes,Y=D===null?[]:Array.isArray(D)?D:[D],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 W=[];for(let q of K.stdout.split(/\r?\n/)){let j=q.trim();if(!j)continue;let D,Y;if(Z){let X=/^"([^"]+)","(\d+)"(?:,|$)/.exec(j);if(!X)throw new M(G);Y=X[1]??"",D=Number(X[2])}else{let X=/^(\d+)\s+(.+)$/.exec(j);if(!X){if(/^PID\s+COMMAND$/i.test(j))continue;throw new M(G)}D=Number(X[1]),Y=X[2]??""}if(!Number.isSafeInteger(D)||D<0)throw new M(G);W.push({pid:D,command:Y})}if(!W.length)throw new M(G);let V=W.filter((q)=>q.pid!==$&&/^(?:node|bun)\.exe$/i.test(q.command));if(Z&&V.length&&J.inspectRuntimes!==!1){let q=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`],j0);if(q.exitCode!==0)throw new M(G);let j=JSON.parse(q.stdout||"null"),D=j===null?[]:Array.isArray(j)?j:[j],Y=new Map;for(let X of D){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(V.some((B)=>B.pid===X.ProcessId))throw new M(G)}for(let X of V)X.command=Y.get(X.pid)??""}return W}catch(K){if(K instanceof M)throw K;throw new M(G)}}function y(z=_,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&U0(G.command)!==null;return{async listRunningHosts(G){return(await o(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await o(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((W)=>W.pid!==Z&&/^(?:node|bun)\.exe$/i.test(W.command)).length:0}}}}async function v(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var L2="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",C0='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.',R0=300000,F0=1000,x0=[1000,2000,4000,8000,16000,30000];function t(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=t(J.lastErrorCode)}}function H0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function N0(z,J,Z,$,G){let{name:Q,paths:K}=z.vault.hosts[J],W=w(K);await G();let V=await(Z.connect??d)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new I("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),q=Z.now??(()=>performance.now()),j=Z.wait??T2;try{let D=new M0({proposedName:Q,paths:W,client:V,writeTokenFile:async(b,H)=>{await G(),await w2(b,H)}});F($,`Asking the vault to connect ${Q}…`);let Y=q()+R0,X,B,x,U=0;for(;;){await G();let b=await D.reconcile();if(b.state==="approved"){F($,`Connected ${J} to Claustrum.`);return}if(b.state==="unavailable"&&b.code===O0)throw new I(C0,{reason:"unsupported-vault",lastErrorCode:b.code});if(b.state!=="pending"&&b.state!=="busy")throw new I("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in b&&{lastErrorCode:b.code}});let H=F0;if(b.state==="busy")B="busy";else if(b.retryCode)B=b.retryCode;if(b.state==="pending"&&b.requestId){if(U=0,b.requestId!==X){if(!/^[a-zA-Z0-9_-]+$/.test(b.requestId))throw new I("Invalid enrollment request id.",{reason:"invalid-request"});X=b.requestId,F($,"Waiting for approval. In another terminal, run:"),F($,` ${H0(b.requestId,Q)}`),F($,`Enrollment files: ${W.statePath}, ${W.tokenPath}`)}}else if(b.state==="pending"&&b.retryCode){H=x0[Math.min(U,x0.length-1)]??F0,U++;let R=t(b.retryCode);if(R!==x)x=R,F($,`The vault has not created the request yet (${R}); retrying.`)}let O=Y-q();if(O<=0)break;await j(Math.min(H,O))}if(X)throw new I(`Claustrum approval is still pending. In another terminal, run: ${H0(X,Q)} and then rerun setup.`,{reason:"approval-pending",...B!==void 0&&{lastErrorCode:B}});let C=t(B);throw new I(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(D){if(D instanceof P||D instanceof M||D instanceof I)throw D;let Y=D?.code;throw new I(L2,{reason:"incomplete",...typeof Y==="string"&&{lastErrorCode:Y}})}finally{V.close()}}var k0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",P2=[{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 c(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function I0(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=P2.find((V)=>V.name===Q);if(!K)throw c($);if(!("values"in K)){if(G!==-1)throw c($);J[K.key]=!0;continue}let W;if(G!==-1)W=$.slice(G+1);else if(K.spaceForm)W=z[++Z];else throw c($);if(W===void 0||!K.values.includes(W))throw K.invalid?Error(K.invalid):c($);if(K.key==="hosts")J.hosts.push(W);else J.opencode=W}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 A0(z,J){let Z=new Set(J);for(;;){let $=await E(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 u2}from"node:url";import{applyEdits as e,createScanner as p2,findNodeAtLocation as l2,modify as T0,parse as a2,parseTree as i2}from"jsonc-parser";import{randomUUID as S2}from"node:crypto";import{mkdir as y2,open as v2,rename as E2,stat as f2,unlink as g2}from"node:fs/promises";import{basename as m2,dirname as h2,join as d2}from"node:path";import{setTimeout as c2}from"node:timers/promises";async function _0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=h2(z);await y2(G,{recursive:!0});let Q;if(!$)try{Q=(await f2(z)).mode&4095}catch(V){if(V.code!=="ENOENT")throw V}let K=d2(G,`.${m2(z)}.${(Z.stageName??S2)()}.tmp`),W=!1;try{let V=await v2(K,"wx",Q??438);W=!0;try{if(await V.writeFile(J,"utf8"),Q!==void 0)await V.chmod(Q)}finally{await V.close()}let q=Z.now??(()=>performance.now()),j=q();for(let D=0;;D++){await Z.beforeRename?.();try{await(Z.rename??E2)(K,z),W=!1;return}catch(Y){let X=Y.code,B=2000-(q()-j);if(!$||!["EPERM","EBUSY","EACCES"].includes(X??"")||B<=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??c2)(Math.min(B,25*2**Math.min(D,2)))}}}finally{if(W)await g2(K).catch(()=>{})}}function L0(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 z0(z){let J=L0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function s2(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`\\\\${u2(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 r2(z,J,Z){let{path:$,platform:G}=k(Z);try{let Q=/^file:\/\//i.test(z)?s2(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 P0(z,J){let Z=[],$=a2(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 w0(z,J,Z){let $=i2(z),G=$&&l2($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let W=[{offset:K.offset,length:K.length,content:""}],V=(q,j)=>{let D=p2(z.slice(q,j),!0);if(D.scan(),z[q+D.getTokenOffset()]===",")W.push({offset:q+D.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let q=Q[Z-1];if(q)V(q.offset+q.length,K.offset);V(K.offset+K.length,G.offset+G.length-1)}else V(K.offset+K.length,Q[Z+1]?.offset??K.offset+K.length);return e(z,W)}function S0(z,J,Z,$){let G=P0(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,
|
|
11
|
-
`,
|
|
12
|
-
${b.content}`);if(!$.enrollOnly&&q.includes("pi"))
|
|
13
|
-
ck auth grant --principal enrolled:${q} --selector-kind category --selector ${
|
|
14
|
-
${X.instructions}`);let
|
|
10
|
+
`}},K=z,W=G[J],V=Array.isArray(W)?[...W]:[],q=V.flatMap((Y,X)=>z0(Y)===Z?[X]:[]),j=`${Z}@${$}`;if(!q.length)K=e(K,T0(K,W===void 0?[J]:[J,V.length],W===void 0?[j]:j,Q));else{let Y=q[0],X=V[Y],B=Array.isArray(X)?[j,...X.slice(1)]:X&&typeof X==="object"?{...X,package:j}:j;if(JSON.stringify(X)!==JSON.stringify(B))K=e(K,T0(K,[J,Y],B,Q));for(let x of q.slice(1).reverse())K=w0(K,J,x)}let D=J==="plugin"?"plugins":"plugin";if(Array.isArray(G[D])){let Y=G[D];for(let X=Y.length-1;X>=0;X--)if(z0(Y[X])===Z)K=w0(K,D,X)}return K}function J0(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((V)=>{let q=G.join(Q,`${V}.jsonc`),j=G.join(Q,`${V}.json`),D=$.exists(q)?q:$.exists(j)?j:q,Y=$.exists(D),X=Y?$.readText(D):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
|
|
11
|
+
`,B=P0(X,K),x=[],U=[];for(let b of["plugin","plugins"]){if(!Array.isArray(B[b]))continue;for(let H of B[b]){let O=L0(H);if(O===null)continue;if(r2(O,D,Z)===z.packages.opencode)x.push(JSON.stringify(H));else if(z0(H)===z.packages.opencode)U.push(JSON.stringify(H))}}if(x.length>0)return{path:D,content:X,changed:!1,existingLocalEntries:x,existingNpmEntries:U};let C=S0(X,K,z.packages.opencode,z.version);return{path:D,content:C,changed:!Y||C!==X}})}async function Z0(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await _0(Z.path,Z.content,{beforeRename:J})}}async function $0(z,J,Z={}){let{platform:$,env:G}=k(Z),Q=await m(Z.runner??_,$,J,["install",`npm:${z.packages.pi}@${z.version}`],G);if(Q.exitCode!==0||Q.timedOut)throw new h({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var v0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function n2(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 o2(z,J,Z){let $=[];for(let G of J){let Q=Z.get(G)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:W}=z.vault.hosts[G],V=await u(w(W),K).catch(()=>"unreadable");if(V==="vault")Q="enrolled";else if(V==="local")Q="not-enrolled"}$.push({host:G,outcome:Q})}return $}async function G0(z,J=[],Z={}){let $=I0(J);n2(z);let G=Z.terminal??y0(),Q=await r(z,Z);F(G,`${z.displayName} setup`);for(let[b,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])F(G,`${b}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);F(G,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)F(G,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let W=["opencode","pi"].filter((b)=>Q[b].installed&&!(b==="pi"&&K));if($.hosts.some((b)=>!W.includes(b)))throw Error(k0);let V=$.yes||$.dryRun&&!f(G);if(!V&&!f(G))throw Error("Setup requires a TTY or --yes.");let q=$.hosts.length?W.filter((b)=>$.hosts.includes(b)):V?W:await A0(G,W)??[],j=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(q.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(V||!f(G))throw Error(v0);let b=await E(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(b===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};j=b}if(!q.length)return F(G,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:q,dryRun:$.dryRun,mode:"local",detection:Q};let{env:D,platform:Y}=k(Z),X=Z.fence??y(Z.runner??_,{platform:Y}),B=async()=>{try{await v(X,D)}catch(b){if(b instanceof M)F(G,b.refusalText);throw b}};if(F(G,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let b=X.previewRunningHosts?await X.previewRunningHosts(D):{hosts:await X.listRunningHosts(D),uncheckedRuntimes:0},H=b.hosts;if(b.uncheckedRuntimes>0)F(G,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let O=new Set(new P(H).activeHosts.map((R)=>R.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let R of O)F(G,`${R} is running; setup will ask you to quit it.`)}catch(b){if(F(G,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof M)F(G,b.refusalText)}else await B();if(($.claustrum||$.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let x=$.claustrum||$.enrollOnly;if(!x&&!$.login&&!$.noClaustrum&&!V&&Q.claustrum.available&&f(G)){let b=await E(G,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(b===null)return F(G,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};x=b===!0}let U=x?"claustrum":"local",C=!$.enrollOnly&&q.includes("opencode")?J0(z,j,Z):[];for(let b of C){for(let O of b.existingLocalEntries??[])F(G,`OpenCode: already registered from ${O} in ${b.path}.`);let H=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(H.length>1)F(G,`Warning: ${z.displayName} may load twice in ${b.path}: ${H.join(", ")}. Entries were left unchanged.`)}if($.dryRun){F(G,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of q){if(z.beforeSignIn)F(G,`Would run beforeSignIn(${b}, ${U}).`);if(x){let H=w(z.vault.hosts[b].paths);F(G,`Would Connect ${b}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else F(G,`Would sign in locally for ${b}.`);if(!$.enrollOnly&&z.beforeRegister)F(G,`Would run beforeRegister(${b}, ${U}).`)}for(let b of C)F(G,`${b.changed?"Would write":"Unchanged"} ${b.path}:
|
|
12
|
+
${b.content}`);if(!$.enrollOnly&&q.includes("pi"))F(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let b of q)F(G,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:j,mode:U,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await B(),await z.beforeSignIn?.(O,b),await B(),x){H.set(O,"unknown");try{await N0(z,O,Z,G,B)}catch(R){if(R instanceof I)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await z.signInLocal(O,b);if(await B(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,U,b),await B(),O==="opencode")await Z0(C,B);else await $0(z,Q.pi.executable,Z);await B(),await z.migrate?.(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await o2(z,q,H);W0(O,R);for(let o0 of R)F(G,X0(o0))}catch{}throw O}}if(F(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${q.join(", ")} (${U}).`),$.enrollOnly)F(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(G,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:q,dryRun:$.dryRun,mode:U,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.8.4",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.29.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.0"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.7.0","@opentui/solid":">=0.7.0",ai:"^7.0.155","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};import{basename as $1}from"node:path";import{resolveClaustrumConnectionPath as G1}from"@cortexkit/claustrum-client";var E0={name:"@cortexkit/pi-openai-auth",version:"1.8.4",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.29.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.2","@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{existsSync as p}from"node:fs";import{homedir as l}from"node:os";import{join as a,resolve as f0}from"node:path";import{fileURLToPath as z1}from"node:url";var g0=new Set;function J1(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return a(l(),".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 l();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return a(l(),z.slice(2));return z.startsWith("file://")?z1(z):z}function h0(z=J1()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=a(z,Q0),$=a(l(),".pi","agent",Q0),G=(K)=>{let W=K0(K),V=m0(g(W),"pi");return p(K)||p(W)||p(V.tokenPath)||p(V.statePath)};if(f0(Z)===f0($)||G(Z)||!G($))return Z;let Q=`${Z}\x00${$}`;if(!g0.has(Q))g0.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 Z1(z=h0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||K0(z)}function d0(z=h0()){return{configPath:z,statePath:Z1(z)}}function r0(z={}){let J=z.print??console.log,Z=z.fence??y(),$={opencode:{stateDir:g(a0().statePath),host:"opencode"},pi:{stateDir:g(d0().statePath),host:"pi"}},G=async(Q)=>{if(await u(w($[Q]),S(Q))!=="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:E0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:G1(),hosts:{opencode:{name:S("opencode"),paths:$.opencode},pi:{name:S("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let W=await u0(w($[Q]),S(Q)),V=W.state==="approved"?W.approvedName:void 0,q=V??("proposedName"in W?W.proposedName:S(Q));if(!V)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:${q} --selector-kind category --selector ${p0.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=$1(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(i0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let W=s0(),V={path:{id:"openai"}};if(await W.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let q=z.beginLogin??c0,j=new AbortController,D=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),Y={version:L.version,signal:j.signal},X,B=!D;try{X=await q({...Y,headless:D})}catch(U){if(D)throw U;B=!1,J("Browser callback unavailable; using device-code sign-in."),X=await q({version:L.version,headless:!0})}if(B){if(!(z.openBrowser??l0)(X.url))j.abort(),await X.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),X=await q({version:L.version,headless:!0})}J(`${X.url}
|
|
14
|
+
${X.instructions}`);let x=await X.completion;await v(Z),await G(Q),await W.set({...V,body:{type:"oauth",access:x.access,refresh:x.refresh,expires:x.expires,...x.accountId?{accountId:x.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await n0({version:L.version}),await G0(r0(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { gt as QuotaMap } from "./sidebar-state-
|
|
1
|
+
import { gt as QuotaMap } from "./sidebar-state-CrRiE9hw.js";
|
|
2
2
|
import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
|
|
3
3
|
import "@cortexkit/private-files";
|
|
4
4
|
type OAuthCredential = {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`;try{G?.({channel:Q,level:I,message:S,data:K})}catch{}if(H===void 0)return;if(U.push(r),U.length>=50){let F=R(!1);if(F instanceof Promise)F.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(I,X)=>x(Q,"error",I,X),warn:(I,X)=>x(Q,"warn",I,X),info:(I,X)=>x(Q,"info",I,X),debug:(I,X)=>x(Q,"debug",I,X),trace:(I,X)=>x(Q,"trace",I,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,U=[],V)clearTimeout(V),V=void 0;H=void 0,Z=void 0,$=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var O=BJ();function L(J){O.configure(J);let{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}=O;return{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}}function v(J){O.setLogLevel(J)}function u(){return O.flushLogs()}function c(J){return O.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,pJ=d.redactStrings;function hJ(J){L({...J,extraSecretKeys:f})}function uJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function fJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",xJ="openai-auth-state.json";function oJ(J){return MJ(J)===AJ?qJ(TJ(J),xJ):`${J}.state.json`}import{spawn as _J}from"node:child_process";function nJ(J,H=process.platform,Z=_J){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),U=Z("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}let $=Z(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore"});return $.on("error",()=>{}),$.unref(),$.pid!==void 0}catch{return!1}}export{T as
|
|
1
|
+
import{jf as q,lf as _,nf as A,of as w,qf as k,sf as p}from"./index-hnmbhgk4.js";import{appendFileSync as QJ,chmodSync as UJ,existsSync as W,renameSync as g,statSync as ZJ}from"node:fs";import{open as $J}from"node:fs/promises";import{dirname as VJ,resolve as IJ}from"node:path";var i=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,e=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function JJ(J){return J instanceof Error||Object.prototype.toString.call(J)==="[object Error]"}function T(J={}){let H=[e,...J.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function Z(G){let U=G.toLowerCase().replace(/[-_]/g,"");return i.test(G)||U.includes("apikey")||U.endsWith("secret")||U.endsWith("password")||U.endsWith("token")&&!U.endsWith("tokens")||!!J.extraSecretKeys?.(U)}function $(G){let U=G,V=[["name",G.name],["message",G.message],["stack",G.stack]];for(let j of["code","status","cause"])if(U[j]!==void 0)V.push([j,U[j]]);let Y=new Set(V.map(([j])=>j));for(let j of Object.entries(G))if(!Y.has(j[0]))V.push(j);return V}function B(G,U,V,Y=0){if(typeof G==="string")return H.reduce((j,C)=>j.replace(C,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(V.has(G))return"[Circular]";V.add(G);try{if(Array.isArray(G))return G.map((N)=>B(N,U,V,Y));let j=JJ(G);if(j&&Y>=8)return"[Truncated]";let C=j?Y+1:Y;return Object.fromEntries((j?$(G):Object.entries(G)).map(([N,z])=>[N,U&&Z(N)?"***REDACTED***":B(z,U,V,C)]))}finally{V.delete(G)}}return{redact:(G)=>B(G,!0,new WeakSet),redactStrings:(G)=>B(G,!1,new WeakSet)}}var E=T(),GJ=E.redact,HJ=E.redactStrings;var D={error:0,warn:1,info:2,debug:3,trace:4},h=5242880,m=3;function b(J){try{UJ(J,384)}catch{}}function jJ(J){try{if(!(W(J)&&ZJ(J).size>=h))return;for(let Z=m-1;Z>=1;Z--)if(W(`${J}.${Z}`)){let $=`${J}.${Z+1}`;g(`${J}.${Z}`,$),b($)}let H=`${J}.1`;g(J,H),b(H)}catch{}}async function M(J){let{file:H,handle:Z}=J;if(J.file=void 0,J.handle=void 0,H&&Z)await _(H,"log-close",()=>Z.close())}async function y(J,H){await w(VJ(H));try{await A(H,"file",!0)}catch(Z){if(Z.code!=="ENOENT")throw Z;try{await k(H,"")}catch($){if($.code!=="EEXIST")throw $;await A(H,"file",!0)}}return J.handle=await _(H,"log-open",()=>$J(H,"a")),J.file=H,J.handle}async function XJ(J,H,Z){H=IJ(H);try{if(J.file!==H)await M(J);let $=J.handle??await y(J,H);if((await _(H,"log-stat",()=>$.stat())).size>=h){await M(J);for(let G=m-1;G>=0;G--){let U=G===0?H:`${H}.${G}`,V=`${H}.${G+1}`;try{await A(U,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await A(V,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await p(U,V),await A(V,"file")}$=await y(J,H)}await _(H,"log-append",()=>$.appendFile(Z,"utf8"))}catch($){throw await M(J).catch(()=>{}),$}}function YJ(J){try{return` ${JSON.stringify(J)}`}catch{return" [unserializable]"}}function BJ(J){let H,Z,$,B=T(),G,U=[],V,Y=Promise.resolve(),j,C={};function N(Q){let I=Y.then(Q);return Y=I.catch((X)=>{j=X}),I}function z(Q){if(q&&Q.file!==H)N(()=>M(C)).catch(()=>{});H=Q.file,Z=Q.level,B=T(Q),G=Q.captureSink}function s(Q){if(Q===void 0||Q in D)$=Q}function o(){if(H===void 0)return;return(typeof H==="function"?H():H)||void 0}function t(){if($)return $;let Q=typeof Z==="function"?Z():Z;if(Q&&Q in D)return Q;return"info"}function R(Q=!0){if(V)clearTimeout(V),V=void 0;if(!U.length){if(q)return N(async()=>{if(Q)await M(C);if(j)throw j});return}let I;try{I=o()}catch{if(U=[],q&&Q)return N(()=>M(C));return}let X=U.join("");if(U=[],!I){if(q&&Q)return N(()=>M(C));return}if(q)return N(async()=>{try{await XJ(C,I,X)}finally{if(Q)await M(C)}});try{if(jJ(I),W(I))b(I);QJ(I,X,{encoding:"utf8",mode:384})}catch{}}function a(){if(!V)V=setTimeout(()=>{V=void 0;let Q=R(!1);if(Q instanceof Promise)Q.catch(()=>{})},500)}function x(Q,I,X,P){if(H===void 0&&G===void 0)return;try{if(D[I]>D[t()])return;let S=B.redactStrings(X),K;try{K=B.redact(P)}catch{K="[unserializable]"}let r=`[${new Date().toISOString()}] ${I.toUpperCase()} [${Q}] ${S}`+(P===void 0?"":YJ(K))+`
|
|
2
|
+
`;try{G?.({channel:Q,level:I,message:S,data:K})}catch{}if(H===void 0)return;if(U.push(r),U.length>=50){let F=R(!1);if(F instanceof Promise)F.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(I,X)=>x(Q,"error",I,X),warn:(I,X)=>x(Q,"warn",I,X),info:(I,X)=>x(Q,"info",I,X),debug:(I,X)=>x(Q,"debug",I,X),trace:(I,X)=>x(Q,"trace",I,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,U=[],V)clearTimeout(V),V=void 0;H=void 0,Z=void 0,$=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var O=BJ();function L(J){O.configure(J);let{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}=O;return{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}}function v(J){O.setLogLevel(J)}function u(){return O.flushLogs()}function c(J){return O.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,pJ=d.redactStrings;function hJ(J){L({...J,extraSecretKeys:f})}function uJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function fJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",xJ="openai-auth-state.json";function oJ(J){return MJ(J)===AJ?qJ(TJ(J),xJ):`${J}.state.json`}import{spawn as _J}from"node:child_process";function nJ(J,H=process.platform,Z=_J){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),U=Z("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}let $=Z(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore"});return $.on("error",()=>{}),$.unref(),$.pid!==void 0}catch{return!1}}export{T as Ye,GJ as Ze,v as _e,u as $e,c as af,pJ as bf,hJ as cf,AJ as df,xJ as ef,oJ as ff,uJ as gf,fJ as hf,nJ as if};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as B}from"node:crypto";import{homedir as G,tmpdir as W}from"node:os";import{dirname as J,join as w,resolve as z}from"node:path";var A="OPENCODE_OPENAI_AUTH_RPC_DIR",K="openai-auth-";function L(k){return B("sha256").update(k).digest("hex").slice(0,16)}function M(){let k=process.env.XDG_STATE_HOME||w(G(),".local","state");return w(k,"cortexkit","openai-auth","rpc")}function Q(k){let q=process.env[A]?.trim();if(q)return z(k,q);return w(M(),`${K}${L(k)}`)}async function $(k){let q=process.env[A]?.trim();if(q)return{dir:z(k,q),secureDir:!1};let x=Q(k);return{dir:x,secureDir:!0,sweepRoot:J(x)}}export{W as
|
|
1
|
+
import{createHash as B}from"node:crypto";import{homedir as G,tmpdir as W}from"node:os";import{dirname as J,join as w,resolve as z}from"node:path";var A="OPENCODE_OPENAI_AUTH_RPC_DIR",K="openai-auth-";function L(k){return B("sha256").update(k).digest("hex").slice(0,16)}function M(){let k=process.env.XDG_STATE_HOME||w(G(),".local","state");return w(k,"cortexkit","openai-auth","rpc")}function Q(k){let q=process.env[A]?.trim();if(q)return z(k,q);return w(M(),`${K}${L(k)}`)}async function $(k){let q=process.env[A]?.trim();if(q)return{dir:z(k,q),secureDir:!1};let x=Q(k);return{dir:x,secureDir:!0,sweepRoot:J(x)}}export{W as uf,K as vf,Q as wf,$ as xf};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{jf as Q,kf as q,lf as D0,nf as C,of as w,pf as R,qf as h,rf as F0,tf as O}from"./index-hnmbhgk4.js";import{randomUUID as M}from"node:crypto";import{lstat as v,mkdir as W0,open as V0,readFile as Y0,rename as Z0,rm as T,stat as L}from"node:fs/promises";import{dirname as P,join as _0}from"node:path";function H0($,f){return`${$}.${f}.lock`}class Q0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class I extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function E0($,f,G){let H=performance.now();for(;;){f.signal?.throwIfAborted();let W=await G0({path:$,name:f.name,ttlMs:f.ttlMs,renew:f.renew??!1,...f.onStep?{onStep:f.onStep}:{},...f.onRenewalTimer?{onRenewalTimer:f.onRenewalTimer}:{}});if(W)try{return f.signal?.throwIfAborted(),await G(W)}finally{await W.release()}let Y=f.timeoutMs-(performance.now()-H);if(Y<=0)throw new Q0({target:$,name:f.name,timeoutMs:f.timeoutMs});await new Promise((Z)=>setTimeout(Z,Math.min(25,Math.ceil(Y))))}}async function x0($,f){let G=await V0($,"wx",384),H;try{H=await G.stat()}catch{H=void 0}try{await G.writeFile(f,"utf8")}catch(W){try{let Y=await v($).catch(()=>{return});if(H&&Y&&Y.dev===H.dev&&Y.ino===H.ino)await T($,{force:!0}).catch(()=>{})}catch{}throw W}finally{await G.close()}}var q0=globalThis.setTimeout.bind(globalThis),C0=globalThis.clearTimeout.bind(globalThis);function R0($){let f=$?.code;return f==="ENOENT"||!Q&&(f==="EINVAL"||f==="ENOTDIR")}var J0;function S0($,f){if($.dev!==f.dev||$.ino!==f.ino)return!1;if($.ino===0&&$.birthtimeMs!==f.birthtimeMs)return!1;return!0}var I0=1000;function G0($){return T0({...$,now:Date.now})}async function T0($){let f=H0($.path,$.name),G=_0(f,"owner.json"),H=M(),W=$.now??Date.now,Y=null,Z=!1,g=!1,J,c,g0=new Promise((z)=>{c=z});function d(z){try{let K=$.onRenewalTimer?.(z);if(K&&(typeof K==="object"||typeof K==="function")&&"then"in K&&typeof K.then==="function")Promise.resolve(K).catch(()=>{})}catch{}}function a(){if(!Y)return;C0(Y),Y=null,d("cancelled")}function V(z,K){if(J||Z)return;J=Object.freeze({reason:z,expectedOwnerId:H,...typeof K?.ownerId==="string"?{observedOwnerId:K.ownerId}:{},...typeof K?.expiresAt==="number"?{observedExpiresAt:K.expiresAt}:{}}),a(),c(J)}let E,A=null,x=`${f}.evicting`,X=_0(x,"owner.json"),i=M(),s=5000,n=8;async function F(){if(Q)try{return JSON.parse(await R(f,!0))}catch(z){if(z.code!=="EISDIR"&&z.reason!=="wrong-kind")throw z;return await C(f,"directory",!0),JSON.parse(await R(G,!0))}try{return JSON.parse(await Y0(f,"utf8"))}catch(z){if(z.code!=="EISDIR")throw z;return JSON.parse(await Y0(G,"utf8"))}}async function U0(){if(Q){let B=await F(),_=Number(B?.expiresAt)-W();await O(f,`${JSON.stringify({ownerId:H,expiresAt:W()+$.ttlMs})}
|
|
2
2
|
`,{deadline:performance.now()+Math.max(0,_),beforeRename:async()=>{let j=await F();if(j?.ownerId!==H||!(Number(j?.expiresAt)>W())||!await D())throw new I({target:$.path,name:$.name})}});return}let z=`${f}.${M()}.tmp`,K,N=!1;try{K=await V0(z,"wx",384),N=!0,await K.writeFile(`${JSON.stringify({ownerId:H,expiresAt:W()+$.ttlMs})}
|
|
3
3
|
`,"utf8"),await K.chmod(384),await K.close(),K=void 0;let B=await F();if(B?.ownerId!==H||!(Number(B?.expiresAt)>W())||!await D())throw new I({target:$.path,name:$.name});await Z0(z,f),N=!1}finally{if(await K?.close().catch(()=>{}),N)await T(z,{force:!0}).catch(()=>{})}}async function t(){let z=`${JSON.stringify({ownerId:H,expiresAt:W()+$.ttlMs})}
|
|
4
4
|
`;if(Q)await h(f,z);else await x0(f,z)}async function o(z){let K=z.code;if(K!=="EEXIST"&&K!=="EISDIR")return!1;if(Q){if($.onStep)await $.onStep("lease-contention-read-ready");try{if(K==="EISDIR")await C(f,"directory",!0),await R(G,!0);else await F()}catch(N){if(N.code!=="ENOENT")throw N}}return!0}async function y(){if(Q)await w(P(f));try{return await t(),!0}catch(z){let K=z.code;if(await o(z))return!1;if(K==="ENOENT"){if(Q)await w(P(f));else await W0(P(f),{recursive:!0});try{return await t(),!0}catch(N){if(await o(N))return!1;throw N}}throw z}}async function m(){await new Promise((z)=>setTimeout(z,Math.floor(Math.random()*4)))}async function k(z=!0){if(z&&$.onStep)await $.onStep("lock-read-ready");let K;try{K=await F()}catch(B){if(Q&&B.code!=="ENOENT")throw B}let N=Number(K?.expiresAt);if(Number.isFinite(N)&&N>W())return{status:"live"};if(typeof K?.ownerId==="string"&&Number.isFinite(N))return{status:"stale",identity:{kind:"owner",ownerId:K.ownerId,expiresAt:N}};try{let B=await L(f),_=Number.isFinite(N)?N:B.mtimeMs+$.ttlMs;if(_>W())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:B.dev,ino:B.ino,mtimeMs:B.mtimeMs,expiresAt:_}}}catch(B){if(B.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw B}}function r(z,K){if(K.status!=="stale")return!1;let N=K.identity;if(z.kind==="owner"&&N.kind==="owner")return z.ownerId===N.ownerId&&z.expiresAt===N.expiresAt;return z.kind==="stat"&&N.kind==="stat"&&z.dev===N.dev&&z.ino===N.ino&&z.mtimeMs===N.mtimeMs&&z.expiresAt===N.expiresAt}async function D(){try{return JSON.parse(await R(X,Q))?.ownerId===i}catch(z){if(Q&&z.code!=="ENOENT")throw z;return!1}}async function S(z){if(Q)await D0(z,"remove",()=>T(z,{recursive:!0,force:!0}));else await T(z,{recursive:!0,force:!0}).catch(()=>{})}async function u(){if(await D())await S(x)}async function j0(z){if(!z)return!1;let K;try{let N=await v(x);K={dev:N.dev,ino:N.ino,birthtimeMs:N.birthtimeMs}}catch{return!1}if(!S0(z,K))return!1;try{return await L(X),!0}catch(N){if(N.code!=="ENOENT")return!0}try{await S(x)}catch{}return!0}async function e(){if(Q)await F0(x);else await W0(x);let z;try{let K=await v(x);z={dev:K.dev,ino:K.ino,birthtimeMs:K.birthtimeMs}}catch{z=void 0}try{await J0?.beforeOwnerWrite?.(x,X);let K=await J0?.failOwnerWrite?.(x,X);if(K!==void 0)throw K;let N=`${JSON.stringify({ownerId:i,createdAt:W()})}
|
|
5
5
|
`;if(Q)await h(X,N);else await x0(X,N)}catch(K){let N=await j0(z);if(R0(K)&&!N)return!1;try{await u()}catch{}throw K}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function $0(){let z;try{z=await L(x)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if(Q)try{await C(x,"directory",!0)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if(z.mtimeMs+s>W()){let N=!0;try{await L(X)}catch(B){if(B.code==="ENOENT")N=!1;else return"fresh"}if(N)return"fresh";if(z.mtimeMs+I0>W())return"fresh"}if($.onStep)await $.onStep("stale-marker-stat");let K=`${x}.${M()}`;try{await Z0(x,K)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if($.onStep)await $.onStep("stale-marker-claimed");return await S(K),"recovered"}async function z0(z){try{if(!await e())return!1}catch(K){if(K.code==="EEXIST"){if(Q)try{await C(x,"directory",!0),await R(X,!0)}catch(N){if(N.code!=="ENOENT")throw N}return!1}throw K}try{await z()}finally{await u()}return!0}async function K0(){for(let z=0;z<n;z++){if($.onStep)await $.onStep("relinquish-read");let K;try{K=await F()}catch(N){if(Q)throw N;return}if(K?.ownerId!==H)return;try{await T(f,{recursive:!0,force:!0});return}catch(N){if(Q)throw N;await m()}}}function N0(){if(!$.renew||Z||J)return;let z=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(Y=q0(()=>{Y=null;let K=(async()=>{let N=!Z;try{if(!await z0(async()=>{let _=await F(),j=W();if(Z||J){N=!1;return}if(_?.ownerId!==H){V("taken-over",_),N=!1;return}if(!(Number(_?.expiresAt)>j)){V("expired",_),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Z||J){N=!1;return}if(!await D())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Z||J){N=!1;return}if(!await D())return;if($.onStep)await $.onStep("renewal-write-ready");if(Z||J){N=!1;return}if(await U0(),$.onStep)await $.onStep("renewal-write-finished");if(!await D()){V("marker-lost"),N=!1,await K0();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(B){if(Q&&B instanceof q)E=B,V("renewal-failed"),N=!1;try{let _=await F();if(_?.ownerId!==H)V("taken-over",_);else if(!(Number(_?.expiresAt)>W()))V("expired",_)}catch{V("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(N&&!Z&&!J)N0()}})();A=K,K.finally(()=>{if(A===K)A=null})},z),"unref"in Y)Y.unref();d("scheduled")}function f0(){try{let z=$.onContended?.();if(z&&(typeof z==="object"||typeof z==="function")&&"then"in z&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}catch{}return null}let U=await y();if(!U)for(let z=0;z<n;z++){if(U=await y(),U)break;let K=await k();if(K.status==="live")return f0();if(K.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await e()){await m();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await $0()==="fresh")return null;await m();continue}try{let N=await k();if(N.status==="live")return f0();if(!r(K.identity,N))continue;if(!await D())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await D())return null;let B=await k(!1);if(!r(K.identity,B))continue;if(await S(f),!await D())return null;if($.onStep)await $.onStep("stale-lock-removed");if(U=await y(),!U)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await D())return await K0(),U=!1,null;break}finally{await u()}}if(!U)return null;return N0(),{ownerId:H,whenLost:()=>g0,hasLost:()=>J!==void 0,assertOwned:async()=>{if(E)throw E;let z;try{let K=await F();if(z=K,!Z&&!J&&K?.ownerId===H&&Number(K?.expiresAt)>W())return;V(K?.ownerId!==H?"taken-over":"expired",K)}catch(K){if(V("unreadable"),Q&&K instanceof q)throw K}throw new I({target:$.path,name:$.name,expectedOwnerId:H,...typeof z?.ownerId==="string"?{observedOwnerId:z.ownerId}:{},...typeof z?.expiresAt==="number"?{observedExpiresAt:z.expiresAt}:{}})},release:async()=>{if(Q&&g)return;Z=!0,a(),await A;let z=performance.now()+s+1000,K=5;for(;;){try{let B=!1;if(await z0(async()=>{let j;try{j=await F()}catch(B0){if(Q&&B0.code==="ENOENT"){B=!0;return}throw B0}if(j?.ownerId!==H){B=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await D())return;await S(f),B=!0})){if(Q&&!B)throw new q(f,"release-not-confirmed",{code:"EIO"});g=B;return}await $0()}catch(B){if(Q)throw B;return}let N=z-performance.now();if(N<=0)break;await new Promise((B)=>setTimeout(B,Math.min(K,N))),K=Math.min(K*2,50)}if(Q)throw new q(f,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{randomUUID as X0}from"node:crypto";import{mkdir as A0,open as b,rename as M0,rm as L0}from"node:fs/promises";import{dirname as p}from"node:path";class l extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function d0($,f,G={}){await O0($,f,G)}async function O0($,f,G,H){if(Q)return O($,G.serialize?G.serialize(f):`${JSON.stringify(f,null,2)}
|
|
6
6
|
`,{beforeRename:G.beforeRename,stagePath:`${$}.${(G.stageName??X0)()}.tmp`,onRenamed:H,durable:G.durable,durability:G.durability,onOutcome:G.onOutcome});await A0(p($),{recursive:!0});let W=`${$}.${(G.stageName??X0)()}.tmp`,Y,Z=!1;try{if(Y=await b(W,"wx",384),Z=!0,await Y.writeFile(G.serialize?G.serialize(f):`${JSON.stringify(f,null,2)}
|
|
7
7
|
`,"utf8"),await Y.chmod(384),G.durable)try{await Y.sync()}catch(g){throw new l(g)}if(await Y.close(),Y=void 0,await G.beforeRename?.(),await M0(W,$),Z=!1,H?.(),G.durable){let g=await b(p($),"r");try{await g.sync()}catch(J){throw new l(J)}finally{await g.close()}}}finally{if(await Y?.close().catch(()=>{}),Z)await L0(W,{force:!0}).catch(()=>{})}}async function a0($){if(Q){await C($,"file");let H=new q($,"directory-sync-unsupported",{code:"ENOTSUP"});throw H.published=!0,H}let f=await b($,"r");try{await f.sync()}finally{await f.close()}let G=await b(p($),"r");try{await G.sync()}finally{await G.close()}}var s0=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});
|
|
8
|
-
export{l as
|
|
8
|
+
export{l as Ae,d0 as Be,O0 as Ce,a0 as De,G0 as Ee,H0 as Fe,Q0 as Ge,I as He,E0 as Ie,s0 as Je};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as n}from"node:module";var k=Object.defineProperty;var q=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var l=(b)=>b;function m(b,a){this[b]=l.bind(null,a)}var r=(b,a)=>{for(var c in a)k(b,c,{get:a[c],enumerable:!0,configurable:!0,set:m.bind(a,c)})};var t=n(import.meta.url),o=Symbol.dispose||Symbol.for("Symbol.dispose"),p=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),u=(b,a,c)=>{if(a!=null){if(typeof a!=="object"&&typeof a!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var e;if(c)e=a[p];if(e===void 0)e=a[o];if(typeof e!=="function")throw TypeError("Object not disposable");b.push([c,e,a])}else if(c)b.push([c]);return a},v=(b,a,c)=>{var e=typeof SuppressedError==="function"?SuppressedError:function(d,i,f,g){return g=Error(f),g.name="SuppressedError",g.error=d,g.suppressed=i,g},j=(d)=>a=c?new e(d,a,"An error was suppressed during disposal"):(c=!0,d),h=(d)=>{while(d=b.pop())try{var i=d[1]&&d[1].call(d[2]);if(d[0])return Promise.resolve(i).then(h,(f)=>(j(f),h()))}catch(f){j(f)}if(c)throw a};return h()};
|
|
2
|
-
export{q as
|
|
2
|
+
export{q as yf,r as zf,t as Af,u as Bf,v as Cf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ab as V,yb as X}from"./index-hvmj07f7.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
|
|
2
2
|
`,{mode:W??384}),await $(B,W??384),await L(B,b)}catch(Y){throw await T(B,{force:!0}).catch(()=>{}),Y}return z.set(q,R(j.body)),!0},async all(){let j=await Q(b);if(!j||Object.keys(j).length===0)return{[x]:!0};return j}}}
|
|
3
3
|
export{_ as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{O as
|
|
1
|
+
import{Af as F}from"./index-byz2j6hz.js";import{randomUUID as k}from"node:crypto";import{lstat as N,readFile as f,rename as y,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 O=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 v="native-addon-unavailable";function b(j){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:j}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:v})}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 b(x)}}function $(){return _??=import("@cortexkit/private-files").then(async(j)=>{if(O)await m(j);return j},(j)=>{throw O?b(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} (${v}). 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}}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 p(j,x=!1){if(!O)return f(j,"utf8");return(await u(j,x)).toString("utf8")}async function u(j,x=!1){if(!O)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??((B)=>new Promise((X)=>setTimeout(X,B))))(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??y)(j,x),{attempts:G,elapsedMs:q()-H}}catch(B){U??=B;let X=B;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 e(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{O as jf,Q as kf,T as lf,Y as mf,S as nf,w as of,p as pf,d as qf,r as rf,l as sf,e as tf};
|