@cortexkit/opencode-openai-auth 1.13.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +9 -9
- package/dist/{codex-request-Bu2sjxQn.d.ts → codex-request-Cl6zEfsR.d.ts} +20 -3
- package/dist/{index-p8v28mh9.js → index-2f330s35.js} +2 -2
- package/dist/index-3mbw88h7.js +91 -0
- package/dist/{index-r8y79mzp.js → index-94b345dw.js} +1 -1
- package/dist/{index-khqwa7g2.js → index-999nwa9p.js} +20 -20
- package/dist/{index-tzrf3ax2.js → index-cxnrd85v.js} +1 -1
- package/dist/{index-cs0tey1r.js → index-gkye2xh1.js} +2 -2
- package/dist/{index-zmerz2yv.js → index-k5av4j8p.js} +2 -2
- package/dist/{index-rhe4jm5t.js → index-pc4vrrex.js} +2 -2
- package/dist/{index-4s50rsec.js → index-snq7bwr6.js} +2 -2
- package/dist/{index-th0bzvpn.js → index-wma2ggn9.js} +2 -2
- package/dist/{index-2g95z7kb.js → index-xk7f1aef.js} +21 -21
- package/dist/{index-2ccfywax.js → index-yygzbxjk.js} +1 -1
- package/dist/{index-0bh5fs56.js → index-z9cj13z7.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-2qht8n50.js → token-sgwxn4xg.js} +1 -1
- package/dist/token-util-8mrnmkge.js +1 -0
- 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 +7 -7
- package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +21 -15
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +81 -4
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +1 -1
- package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +21 -15
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +81 -4
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +1 -1
- package/dist/index-7s8g79dd.js +0 -91
- package/dist/token-util-20g3fwxd.js +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
3
|
-
`);return J<0?"":z.slice(J+1)}class
|
|
4
|
-
|
|
2
|
+
import{c as Q1}from"./index-yygzbxjk.js";import{Ha as a0,Ia as d,Ja as U,Ka as m,Ub as $1,kc as K1,ta as j0,ua as c,va as V0,wa as u,xa as t0,xc as X1}from"./index-999nwa9p.js";import{Od as y,Pd as r,Rd as P0,Td as l0,Ud as s,Vd as A,Wd as i0,Xd as p,Yd as U0,Zd as L0,ve as J1}from"./index-3mbw88h7.js";import"./index-snq7bwr6.js";import"./index-gkye2xh1.js";import"./index-wma2ggn9.js";import{Uf as H0,_f as B0,ag as D0,dg as Z1}from"./index-pc4vrrex.js";import"./index-2f330s35.js";import"./index-94b345dw.js";import"./index-cxnrd85v.js";import{spawn as W1}from"node:child_process";var k=4096,q1=1048576;class x0{buffer=Buffer.alloc(k);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=k){if(z.length>k||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-k),this.start=0,this.length=k;return}let J=Math.max(0,this.length+z.length-k);if(J>0)this.truncated=!0;this.start=(this.start+J)%k,this.length-=J;let $=(this.start+this.length)%k,Z=Math.min(z.length,k-$);if(z.copy(this.buffer,$,0,Z),Z<z.length)z.copy(this.buffer,0,Z);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,k-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let $=0;while($<z.length){let Z=z[$];if(Z===void 0||(Z&192)!==128)break;$++}return z.subarray($).toString("utf8")}}var T={run(z,J,$={}){return new Promise((Z)=>{let K=performance.now(),Q=$.timeoutMs??15000,G=new x0,q=[],Y=0,X=!1,W=!1,B=!1,x;try{x=W1(z,[...J],{env:$.env??process.env,windowsHide:!0,windowsVerbatimArguments:$.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let b=Q>0?setTimeout(()=>{B=!0,x.kill("SIGTERM")},Q):void 0;x.stdout?.on("data",(F)=>{let O=q1-Y,D=Math.min(O,F.length);if(D>0)q.push(F.subarray(0,D)),Y+=D;if(F.length>O)X=!0,x.kill("SIGTERM")}),x.stderr?.on("data",(F)=>G.push(F));let j=!1,H=(F,O)=>{if(j)return;if(j=!0,b)clearTimeout(b);Z({exitCode:W?1:X?1:F??1,stdout:Buffer.concat(q,Y).toString("utf8"),stderr:G.toString(),stderrTruncated:G.didTruncate,...W?{spawnError:!0}:{},signal:O??null,timedOut:B,durationMs:performance.now()-K})};x.once("error",()=>{if(W=!0,x.pid===void 0)H(null,null)}),x.once("close",(F,O)=>H(F,O))})}};function i(z,J,$,Z,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test($)){if(/["%!\r\n]/.test($)||Z.some((G)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(G)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${$}" ${Z.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run($,Z,{env:K,timeoutMs:Q})}function F0(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function E(z,J,$,Z){let K=J.requestedGrants??Z;if(!K)return;let Q=K.map((G)=>({grant:G,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${F0(`enrolled:${J.approvedName}`)} --selector-kind ${G.selector.exact===void 0?"category":"exact"} --selector ${F0(G.selector.exact??G.selector.category)} --operation ${G.operation}`}}));if(J.requestedGrantsStatus==="dropped")return{state:"older-vault",grants:Q};try{if(!z.listScoped)return{state:"unconfirmed",grants:Q};let{token:G}=await U0($),q=await z.listScoped(G),Y=Q.map((X)=>({...X,reachableLogins:q.rows.filter((W)=>W.operations.includes(X.grant.operation)&&(X.grant.selector.exact!==void 0?W.id===X.grant.selector.exact:W.categories.includes(X.grant.selector.category))).length}));return{state:Y.every((X)=>X.reachableLogins>0)?"reachable":Y.some((X)=>X.reachableLogins>0)?"partial":"no-logins",grants:Y.map((X)=>{if(X.reachableLogins===0)return X;let{grantCommand:W,...B}=X;return B})}}catch{return{state:"unconfirmed",grants:Q}}}function f(z){let J=[],$=z.grants.some((Z)=>Z.grantCommand)?"run:":"check ck auth status for the approved name before granting access.";if(z.state==="older-vault")J.push(`Approved. This vault is too old to grant access with the approval; ${$}`);else if(z.state==="no-logins")J.push(`Approved, but no logins are reachable yet; ${$}`);else if(z.state==="partial")J.push(`Approved, but some requested access has no reachable logins yet; ${$}`);else if(z.state==="unconfirmed")J.push(`Approved, but access could not be confirmed; ${z.grants.some((Z)=>Z.grantCommand)?"check ck auth status or run:":$}`);for(let{grant:Z,reachableLogins:K,grantCommand:Q}of z.grants){if(K!==void 0&&K>0){let G=Z.selector.exact===void 0?`the vault's ${JSON.stringify(Z.selector.category)} accounts`:`credential ${JSON.stringify(Z.selector.exact)}`;J.push(`Confirmed ${Z.operation} access to ${G} (${K} reachable ${K===1?"login":"logins"}).`)}if(Q)J.push(` ${Q}`)}return J}var Y1="Pi install failed; run pi install after checking your npm connection.";function B1(z){let J=Buffer.from(z,"utf8");if(J.length<=k)return z;let $=J.length-k;while($<J.length){let Z=J[$];if(Z===void 0||(Z&192)!==128)break;$++}return J.subarray($).toString("utf8")}function D1(z){let J=z.indexOf(`
|
|
3
|
+
`);return J<0?"":z.slice(J+1)}class a extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(Y1);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?D1(z.stderrTail):z.stderrTail,$=H0(J);this.stderrTail=B1(typeof $==="string"?$:"")}}var j1={opencode:"OpenCode",pi:"Pi"},V1={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function M0({host:z,outcome:J,access:$}){return`${j1[z]}: ${V1[J]}${$?` — ${f($).join(`
|
|
4
|
+
`)}`:""}`}var x1=new WeakMap;function O0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;x1.set(z,Object.freeze(J.map(($)=>Object.freeze({...$}))))}import{accessSync as O1,constants as C1,existsSync as R1,readFileSync as k1,realpathSync as N1,statSync as I1}from"node:fs";import{mkdtemp as _1,rm as w1}from"node:fs/promises";import{tmpdir as A1}from"node:os";import{join as T1}from"node:path";import{parse as P1}from"jsonc-parser";import{homedir as F1}from"node:os";import{posix as U1,win32 as H1}from"node:path";import{fileURLToPath as M1}from"node:url";function N(z={}){let J=z.env??process.env,$=z.platform??process.platform,Z=$==="win32"?H1:U1,K=z.home??($==="win32"?J.USERPROFILE:J.HOME)??F1(),Q=z.cwd??process.cwd(),G=(W)=>Z.resolve(Q,W),q=J.OPENCODE_CONFIG_DIR?.trim(),Y=J.XDG_CONFIG_HOME?.trim(),X=J.PI_CODING_AGENT_DIR?.trim()||Z.join(K,".pi","agent");if(X==="~")X=K;else if(/^~[/\\]/.test(X))X=Z.join(K,X.slice(2));if(X.startsWith("file://"))X=M1(X);return{env:J,platform:$,path:Z,home:K,cwd:Q,opencode:q?G(q):Y?Z.join(G(Y),"opencode"):Z.join(K,".config","opencode"),pi:G(X)}}function z0(z,J){try{return I1(z)[J]()}catch{return!1}}var P={exists:R1,isFile:(z)=>z0(z,"isFile"),isDirectory:(z)=>z0(z,"isDirectory"),isExecutable(z){try{return O1(z,C1.X_OK),z0(z,"isFile")}catch{return!1}},readText:(z)=>k1(z,"utf8"),realpath:N1};function w(z,J={}){let{env:$,platform:Z,path:K,cwd:Q}=N(J),G=J.fs??P,q=Object.entries($).find(([X])=>Z==="win32"?X.toUpperCase()==="PATH":X==="PATH")?.[1]??"",Y=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let X of q.split(Z==="win32"?";":":")){let W=X.trim().replace(/^"|"$/g,"");if(!W)continue;for(let B of Y){let x=K.resolve(Q,W,z+B);if(Z==="win32"?G.isFile(x):G.isExecutable(x))return x}}return null}function C0(z={}){let{platform:J,home:$,env:Z,path:K}=N(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",K.join($,"Applications","OpenCode.app"),K.join($,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=Z.LOCALAPPDATA||K.join($,"AppData","Local");return[K.join(Q,"Programs","opencode"),K.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",K.join($,".local","share","applications","opencode.desktop")]}function J0(z,J){let $=J.fs??P,{path:Z}=N(J);try{let K=$.readText(z);if(K.length>65536)return z;let Q=[...K.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...K.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let G=Q.at(-1)?.[1];if(G){let q=Z.join(Z.dirname(z),...G.split(/[/\\]+/));if($.isFile(q))return $.realpath(q)}return $.realpath(z)}catch{return z}}function L1(z,J){let $=J.fs??P,{path:Z}=N(J),K=Z.dirname(J0(z,J));for(;;){try{let G=JSON.parse($.readText(Z.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(G.name))return"2";if(G.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(G.version??"")?"2":"1"}catch{}let Q=Z.dirname(K);if(Q===K)return null;K=Q}}function R0(z={}){let J=w("opencode",z),$=w("opencode2",z),Z=J&&$&&J0(J,z)===J0($,z),K=z.fs??P,{path:Q,opencode:G}=N(z),q="1";for(let X of["jsonc","json"]){let W=Q.join(G,`opencode.${X}`);if(!K.exists(W))continue;try{if(Object.hasOwn(P1(K.readText(W))??{},"plugins"))q="2"}catch{}break}let Y=J?L1(J,z)??(Z?"2":q):null;if($&&Y==="1"&&!Z)return"ambiguous";return $||Z?"2":Y??q}async function Z0(z,J={}){let $=J.fs??P,{env:Z,platform:K,opencode:Q,pi:G}=N(J),q=J.runner??T,Y=w("opencode",J)??w("opencode2",J),X=w("pi",J),W=w("ck",J),B=async(H)=>{if(!H)return null;let F;try{F=await _1(T1(A1(),"common-auth-setup-version-"));let O={...Z,HOME:F,USERPROFILE:F,XDG_CONFIG_HOME:F,XDG_DATA_HOME:F,XDG_STATE_HOME:F,XDG_CACHE_HOME:F,OPENCODE_CONFIG_DIR:F,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:F},D=await i(q,K,H,["--version"],O,2000);return D.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(D.stdout)?.[0]??null:null}catch{return null}finally{if(F)await w1(F,{recursive:!0,force:!0}).catch(()=>{})}},x=!1;if(W&&$.exists(z.vault.connectionFile))try{(await(J.connect??s)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),x=!0}catch{x=!1}let[b,j]=await Promise.all([B(Y),B(X)]);return{opencode:{installed:$.isDirectory(Q)||C0(J).some((H)=>$.exists(H))||Y!==null,executable:Y,version:b,directory:Q,generation:R0(J)},pi:{installed:X!==null||$.isDirectory(G),executable:X,version:j,directory:G},claustrum:{available:x,executable:W}}}import{setTimeout as m1}from"node:timers/promises";import{writeEnrollmentTokenFile as d1}from"@cortexkit/claustrum-client";var k0=45000,$0=new Set(["opencode","litecode","opencode2","pi"]),I0=new Set(["node","bun"]),S1=[...$0,...I0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),v1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${S1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,y1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function E1(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function N0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var f1=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--title","--input-type","--preload","--cwd","-c","--config","--tsconfig-override","-d","--define","-l","--main-fields"]),g1=new Set(["-e","--eval","-p","--print"]);function h1(z,J){for(let $=0;$<J.length;$++){let Z=J[$]??"";if(Z==="--")return J[$+1];if(g1.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&f1.has(Z))$++;continue}if(z==="bun"&&Z==="run")continue;return Z}return}function _0(z){let[J,...$]=E1(z);if(J===void 0)return null;let Z=N0(J);if($0.has(Z))return Z;if(!I0.has(Z))return null;let K=h1(Z,$);if(K===void 0)return null;let Q=N0(K);if($0.has(Q))return Q;return y1.test(K)?"pi":null}class C extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.exitCode=z.exitCode,this.signal=z.signal,this.timedOut=z.timedOut,this.durationMs=z.durationMs}get refusalText(){let z=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${z} after ${Math.round(this.durationMs)} ms.`}}class v extends Error{activeHosts;constructor(z){let J=z.map(($)=>({pid:$.pid,command:_0($.command)??"host"}));super(`OpenCode or Pi processes are currently running:
|
|
5
|
+
${J.map(($)=>` - PID ${$.pid}: ${$.command}`).join(`
|
|
5
6
|
`)}
|
|
6
7
|
|
|
7
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function J0(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,X,W,b)=>{let D=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let Y=await z.run(X,W,{env:J.env,timeoutMs:b});return G={step:K,exitCode:Y.exitCode,signal:Y.signal??null,timedOut:Y.timedOut??!1,durationMs:Y.durationMs??performance.now()-D},Y}finally{if(G.exitCode===null)G.durationMs=performance.now()-D;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let b=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",A1],F0);if(b.exitCode!==0)throw new O(G);let D=JSON.parse(b.stdout);if(!D||typeof D!=="object"||!("complete"in D)||D.complete!==!0||!("processes"in D))throw new O(G);let Y=D.processes,B=Y===null?[]:Array.isArray(Y)?Y:[Y],q=[];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 H=V.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(V.Name))q.push({pid:H,command:V.Name});else if(typeof V.CommandLine==="string")q.push({pid:H,command:V.CommandLine});else if(H!==$)throw new O(G)}return q}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 X=[];for(let b of K.stdout.split(/\r?\n/)){let D=b.trim();if(!D)continue;let Y,B;if(Z){let q=/^"([^"]+)","(\d+)"(?:,|$)/.exec(D);if(!q)throw new O(G);B=q[1]??"",Y=Number(q[2])}else{let q=/^(\d+)\s+(.+)$/.exec(D);if(!q){if(/^PID\s+COMMAND$/i.test(D))continue;throw new O(G)}Y=Number(q[1]),B=q[2]??""}if(!Number.isSafeInteger(Y)||Y<0)throw new O(G);X.push({pid:Y,command:B})}if(!X.length)throw new O(G);let W=X.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`],F0);if(b.exitCode!==0)throw new O(G);let D=JSON.parse(b.stdout||"null"),Y=D===null?[]:Array.isArray(D)?D:[D],B=new Map;for(let q of Y){if(!q||typeof q!=="object"||!("ProcessId"in q)||!("CommandLine"in q)||!Number.isSafeInteger(q.ProcessId))throw new O(G);if(typeof q.CommandLine==="string")B.set(Number(q.ProcessId),q.CommandLine);else if(W.some((V)=>V.pid===q.ProcessId))throw new O(G)}for(let q of W)q.command=B.get(q.pid)??""}return X}catch(K){if(K instanceof O)throw K;throw new O(G)}}function y(z=w,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&O0(G.command)!==null;return{async listRunningHosts(G){return(await J0(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await J0(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((X)=>X.pid!==Z&&/^(?:node|bun)\.exe$/i.test(X.command)).length:0}}}}async function E(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var y1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",A0='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.',w0=300000,C0=1000,R0=[1000,2000,4000,8000,16000,30000];function Z0(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=Z0(J.lastErrorCode)}}function k0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function _0(z,J,Z,$,G){if(l())throw Error(S);let{name:Q,displayName:K,paths:X}=z.vault.hosts[J],W=_(X);await G();let b=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"})}),D=Z.now??(()=>performance.now()),Y=Z.wait??S1;try{let B=new I0({proposedName:Q,displayName:K,paths:W,client:b,writeTokenFile:async(x,R)=>{await G(),await v1(x,R)}});await G();let q=await B.status();if(q.state==="approved"){F($,`Already connected as ${q.approvedName??q.proposedName}.`);return}F($,`Asking the vault to connect ${Q}…`);let V=D()+w0,H,U,C,j=0;for(;;){let x=await B.reconcile();if(x.state==="approved"){F($,`Connected ${J} to Claustrum.`);return}if(x.state==="unavailable"&&x.code===N0)throw new I(A0,{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 R=C0;if(x.state==="busy")U="busy";else if(x.retryCode)U=x.retryCode;if(x.state==="pending"&&x.requestId){if(j=0,x.requestId!==H){if(!/^[a-zA-Z0-9_-]+$/.test(x.requestId))throw new I("Invalid enrollment request id.",{reason:"invalid-request"});H=x.requestId,F($,"Waiting for approval. In another terminal, run:"),F($,` ${k0(x.requestId,Q)}`),F($,`Enrollment files: ${W.statePath}, ${W.tokenPath}`)}}else if(x.state==="pending"&&x.retryCode){R=R0[Math.min(j,R0.length-1)]??C0,j++;let n=Z0(x.retryCode);if(n!==C)C=n,F($,`The vault has not created the request yet (${n}); retrying.`)}let h=V-D();if(h<=0)break;await Y(Math.min(R,h)),await G()}if(H)throw new I(`Claustrum approval is still pending. In another terminal, run: ${k0(H,Q)} and then rerun setup.`,{reason:"approval-pending",...U!==void 0&&{lastErrorCode:U}});let M=Z0(U);throw new I(`The vault never created the enrollment request (last error: ${M}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:M})}catch(B){if(B instanceof P||B instanceof O||B instanceof I)throw B;let q=B?.code;throw new I(y1,{reason:"incomplete",...typeof q==="string"&&{lastErrorCode:q}})}finally{b.close()}}var T0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",E1=[{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 L0(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=E1.find((W)=>W.name===Q);if(!K)throw a($);if(!("values"in K)){if(G!==-1)throw a($);J[K.key]=!0;continue}let X;if(G!==-1)X=$.slice(G+1);else if(K.spaceForm)X=z[++Z];else throw a($);if(X===void 0||!K.values.includes(X))throw K.invalid?Error(K.invalid):a($);if(K.key==="hosts")J.hosts.push(X);else J.opencode=X}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function P0(z,J){let Z=new Set(J);for(;;){let $=await 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 i1}from"node:url";import{applyEdits as $0,createScanner as s1,findNodeAtLocation as r1,modify as v0,parse as n1,parseTree as o1}from"jsonc-parser";import{randomUUID as f1}from"node:crypto";import{mkdir as g1,open as m1,rename as d1,stat as h1,unlink as c1}from"node:fs/promises";import{basename as u1,dirname as p1,join as l1}from"node:path";import{setTimeout as a1}from"node:timers/promises";async function S0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=p1(z);await g1(G,{recursive:!0});let Q;if(!$)try{Q=(await h1(z)).mode&4095}catch(W){if(W.code!=="ENOENT")throw W}let K=l1(G,`.${u1(z)}.${(Z.stageName??f1)()}.tmp`),X=!1;try{let W=await m1(K,"wx",Q??438);X=!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()),D=b();for(let Y=0;;Y++){await Z.beforeRename?.();try{await(Z.rename??d1)(K,z),X=!1;return}catch(B){let q=B.code,V=2000-(b()-D);if(!$||!["EPERM","EBUSY","EACCES"].includes(q??"")||V<=0||Y>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??a1)(Math.min(V,25*2**Math.min(Y,2)))}}}finally{if(X)await c1(K).catch(()=>{})}}function E0(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 G0(z){let J=E0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function t1(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`\\\\${i1(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 e1(z,J,Z){let{path:$,platform:G}=N(Z);try{let Q=/^file:\/\//i.test(z)?t1(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 f0(z,J){let Z=[],$=n1(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 y0(z,J,Z){let $=o1(z),G=$&&r1($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let X=[{offset:K.offset,length:K.length,content:""}],W=(b,D)=>{let Y=s1(z.slice(b,D),!0);if(Y.scan(),z[b+Y.getTokenOffset()]===",")X.push({offset:b+Y.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 $0(z,X)}function g0(z,J,Z,$){let G=f0(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
|
|
8
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function K0(z=T,J={}){let $=(J.platform??process.platform)==="win32",Z=J.selfPid??process.pid,K={step:$?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(G,q,Y,X)=>{let W=performance.now();K={step:G,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let B=await z.run(q,Y,{env:J.env,timeoutMs:X});return K={step:G,exitCode:B.exitCode,signal:B.signal??null,timedOut:B.timedOut??!1,durationMs:B.durationMs??performance.now()-W},B}finally{if(K.exitCode===null)K.durationMs=performance.now()-W;J.onStep?.({...K})}};try{if($&&J.hostImagesOnly){let X=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",v1],k0);if(X.exitCode!==0)throw new C(K);let W=JSON.parse(X.stdout);if(!W||typeof W!=="object"||!("complete"in W)||W.complete!==!0||!("processes"in W))throw new C(K);let B=W.processes,x=B===null?[]:Array.isArray(B)?B:[B],b=[];for(let j of x){if(!j||typeof j!=="object"||!("Name"in j)||typeof j.Name!=="string"||!("ProcessId"in j)||!Number.isSafeInteger(j.ProcessId)||j.ProcessId<0||!("CommandLine"in j))throw new C(K);let H=j.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(j.Name))b.push({pid:H,command:j.Name});else if(typeof j.CommandLine==="string")b.push({pid:H,command:j.CommandLine});else if(H!==Z)throw new C(K)}return b}let G=await Q($?"tasklist":"ps",$?"tasklist.exe":"ps",$?["/fo","csv","/nh"]:["-eo","pid,command"]);if(G.exitCode!==0)throw new C(K);let q=[];for(let X of G.stdout.split(/\r?\n/)){let W=X.trim();if(!W)continue;let B,x;if($){let b=/^"([^"]+)","(\d+)"(?:,|$)/.exec(W);if(!b)throw new C(K);x=b[1]??"",B=Number(b[2])}else{let b=/^(\d+)\s+(.+)$/.exec(W);if(!b){if(/^PID\s+COMMAND$/i.test(W))continue;throw new C(K)}B=Number(b[1]),x=b[2]??""}if(!Number.isSafeInteger(B)||B<0)throw new C(K);q.push({pid:B,command:x})}if(!q.length)throw new C(K);let Y=q.filter((X)=>X.pid!==Z&&/^(?:node|bun)\.exe$/i.test(X.command));if($&&Y.length&&J.inspectRuntimes!==!1){let X=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],k0);if(X.exitCode!==0)throw new C(K);let W=JSON.parse(X.stdout||"null"),B=W===null?[]:Array.isArray(W)?W:[W],x=new Map;for(let b of B){if(!b||typeof b!=="object"||!("ProcessId"in b)||!("CommandLine"in b)||!Number.isSafeInteger(b.ProcessId))throw new C(K);if(typeof b.CommandLine==="string")x.set(Number(b.ProcessId),b.CommandLine);else if(Y.some((j)=>j.pid===b.ProcessId))throw new C(K)}for(let b of Y)b.command=x.get(b.pid)??""}return q}catch(G){if(G instanceof C)throw G;throw new C(K)}}function g(z=T,J={}){let $=J.selfPid??process.pid,Z=(K)=>K.pid!==$&&_0(K.command)!==null;return{async listRunningHosts(K){return(await K0(z,{...J,env:K,hostImagesOnly:!0})).filter(Z)},async previewRunningHosts(K){let Q=await K0(z,{...J,env:K,inspectRuntimes:!1}),G=(J.platform??process.platform)==="win32";return{hosts:Q.filter(Z),uncheckedRuntimes:G?Q.filter((q)=>q.pid!==$&&/^(?:node|bun)\.exe$/i.test(q.command)).length:0}}}}async function h(z,J){let $=await z.listRunningHosts(J);if($.length)throw new v($)}var p1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",S0='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.',v0=300000,w0=1000,A0=[1000,2000,4000,8000,16000,30000];function Q0(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class _ extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=Q0(J.lastErrorCode)}}function T0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function y0(z,J,$,Z,K){if(r())throw Error(y);let{name:Q,displayName:G,requestedGrants:q,paths:Y}=z.vault.hosts[J],X=A(Y);await K();let W=await($.connect??s)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new _("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),B=$.now??(()=>performance.now()),x=$.wait??m1;try{let b=new L0({proposedName:Q,displayName:G,requestedGrants:q,paths:X,client:W,writeTokenFile:async(V,R)=>{await K(),await d1(V,R)}});await K();let j=await b.status();if(j.state==="approved"){U(Z,`Already connected as ${j.approvedName??j.proposedName}.`);let V=await E(W,j,X.tokenPath,q);if(V)for(let R of f(V))U(Z,R);return V}U(Z,`Asking the vault to connect ${Q}…`);let H=B()+v0,F,O,D,M=0;for(;;){let V=await b.reconcile();if(V.state==="approved"){U(Z,`Connected ${J} to Claustrum.`);let S=await E(W,V,X.tokenPath,q);if(S)for(let b1 of f(S))U(Z,b1);return S}if(V.state==="unavailable"&&V.code===P0)throw new _(S0,{reason:"unsupported-vault",lastErrorCode:V.code});if(V.state!=="pending"&&V.state!=="busy")throw new _("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in V&&{lastErrorCode:V.code}});let R=w0;if(V.state==="busy")O="busy";else if(V.retryCode)O=V.retryCode;if(V.state==="pending"&&V.requestId){if(M=0,V.requestId!==F){if(!/^[a-zA-Z0-9_-]+$/.test(V.requestId))throw new _("Invalid enrollment request id.",{reason:"invalid-request"});F=V.requestId,U(Z,"Waiting for approval. In another terminal, run:"),U(Z,` ${T0(V.requestId,Q)}`),U(Z,`Enrollment files: ${X.statePath}, ${X.tokenPath}`)}}else if(V.state==="pending"&&V.retryCode){R=A0[Math.min(M,A0.length-1)]??w0,M++;let S=Q0(V.retryCode);if(S!==D)D=S,U(Z,`The vault has not created the request yet (${S}); retrying.`)}let l=H-B();if(l<=0)break;await x(Math.min(R,l)),await K()}if(F)throw new _(`Claustrum approval is still pending. In another terminal, run: ${T0(F,Q)} and then rerun setup.`,{reason:"approval-pending",...O!==void 0&&{lastErrorCode:O}});let I=Q0(O);throw new _(`The vault never created the enrollment request (last error: ${I}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:I})}catch(b){if(b instanceof v||b instanceof C||b instanceof _)throw b;let j=b?.code;throw new _(p1,{reason:"incomplete",...typeof j==="string"&&{lastErrorCode:j}})}finally{W.close()}}var E0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",u1=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function o(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function f0(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let $=0;$<z.length;$++){let Z=z[$],K=Z.indexOf("="),Q=K===-1?Z:Z.slice(0,K),G=u1.find((Y)=>Y.name===Q);if(!G)throw o(Z);if(!("values"in G)){if(K!==-1)throw o(Z);J[G.key]=!0;continue}let q;if(K!==-1)q=Z.slice(K+1);else if(G.spaceForm)q=z[++$];else throw o(Z);if(q===void 0||!G.values.includes(q))throw G.invalid?Error(G.invalid):o(Z);if(G.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 g0(z,J){let $=new Set(J);for(;;){let Z=await m(z,[...["opencode","pi"].map((K)=>({value:K,label:`[${$.has(K)?"x":" "}] ${K==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(K)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if(Z===null)return null;if(Z==="done")return[...$];if($.has(Z))$.delete(Z);else $.add(Z)}}import{domainToUnicode as z2}from"node:url";import{applyEdits as G0,createScanner as J2,findNodeAtLocation as Z2,modify as m0,parse as $2,parseTree as K2}from"jsonc-parser";import{randomUUID as c1}from"node:crypto";import{mkdir as l1,open as i1,rename as a1,stat as s1,unlink as r1}from"node:fs/promises";import{basename as o1,dirname as n1,join as t1}from"node:path";import{setTimeout as e1}from"node:timers/promises";async function h0(z,J,$={}){let Z=($.platform??process.platform)==="win32",K=n1(z);await l1(K,{recursive:!0});let Q;if(!Z)try{Q=(await s1(z)).mode&4095}catch(Y){if(Y.code!=="ENOENT")throw Y}let G=t1(K,`.${o1(z)}.${($.stageName??c1)()}.tmp`),q=!1;try{let Y=await i1(G,"wx",Q??438);q=!0;try{if(await Y.writeFile(J,"utf8"),Q!==void 0)await Y.chmod(Q)}finally{await Y.close()}let X=$.now??(()=>performance.now()),W=X();for(let B=0;;B++){await $.beforeRename?.();try{await($.rename??a1)(G,z),q=!1;return}catch(x){let b=x.code,j=2000-(X()-W);if(!Z||!["EPERM","EBUSY","EACCES"].includes(b??"")||j<=0||B>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await($.wait??e1)(Math.min(j,25*2**Math.min(B,2)))}}}finally{if(q)await r1(G).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 X0(z){let J=p0(z);if(J===null)return null;let $=J.indexOf("@",J.startsWith("@")?1:0);return $<0?J:J.slice(0,$)}function Q2(z,J){let $=new URL(z);if(/%2f/i.test($.pathname)||J&&/%5c/i.test($.pathname))throw Error("Encoded path separators are not valid in a file URL.");let Z=decodeURIComponent($.pathname);if(!J){if($.hostname)throw Error("A POSIX file URL must be local.");return Z}let K=Z.replaceAll("/","\\");if($.hostname)return`\\\\${z2($.hostname)}${K}`;if(!/^\\[a-z]:/i.test(K))throw Error("A Windows file URL must have an absolute drive path.");return K.slice(1)}function G2(z,J,$){let{path:Z,platform:K}=N($);try{let Q=/^file:\/\//i.test(z)?Q2(z,K==="win32"):Z.isAbsolute(z)||z.startsWith(".")?Z.resolve(Z.dirname(J),z):null;if(Q===null)return null;let G=JSON.parse(($.fs??P).readText(Z.join(Q,"package.json")));return G&&typeof G==="object"&&"name"in G&&typeof G.name==="string"?G.name:null}catch{return null}}function u0(z,J){let $=[],Z=$2(z,$,{allowTrailingComma:!0});if($.length||!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid OpenCode config; refusing to overwrite it.");if(Z[J]!==void 0&&!Array.isArray(Z[J]))throw Error(`OpenCode ${J} must be an array.`);return Z}function d0(z,J,$){let Z=K2(z),K=Z&&Z2(Z,[J]),Q=K?.children??[],G=Q[$];if(!G||!K)throw Error("Invalid plugin array edit.");let q=[{offset:G.offset,length:G.length,content:""}],Y=(X,W)=>{let B=J2(z.slice(X,W),!0);if(B.scan(),z[X+B.getTokenOffset()]===",")q.push({offset:X+B.getTokenOffset(),length:1,content:""})};if($===Q.length-1){let X=Q[$-1];if(X)Y(X.offset+X.length,G.offset);Y(G.offset+G.length,K.offset+K.length-1)}else Y(G.offset+G.length,Q[$+1]?.offset??G.offset+G.length);return G0(z,q)}function c0(z,J,$,Z){let K=u0(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
|
|
8
9
|
`)?`\r
|
|
9
10
|
`:`
|
|
10
|
-
`}},
|
|
11
|
-
`,
|
|
12
|
-
${
|
|
13
|
-
|
|
14
|
-
${q.instructions}`);let H=await q.completion;await E(Z),await G(Q),await X.set({...W,body:{type:"oauth",access:H.access,refresh:H.refresh,expires:H.expires,...H.accountId?{accountId:H.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await J1({version:L.version}),await q0(z1(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
|
|
11
|
+
`}},G=z,q=K[J],Y=Array.isArray(q)?[...q]:[],X=Y.flatMap((x,b)=>X0(x)===$?[b]:[]),W=`${$}@${Z}`;if(!X.length)G=G0(G,m0(G,q===void 0?[J]:[J,Y.length],q===void 0?[W]:W,Q));else{let x=X[0],b=Y[x],j=Array.isArray(b)?[W,...b.slice(1)]:b&&typeof b==="object"?{...b,package:W}:W;if(JSON.stringify(b)!==JSON.stringify(j))G=G0(G,m0(G,[J,x],j,Q));for(let H of X.slice(1).reverse())G=d0(G,J,H)}let B=J==="plugin"?"plugins":"plugin";if(Array.isArray(K[B])){let x=K[B];for(let b=x.length-1;b>=0;b--)if(X0(x[b])===$)G=d0(G,B,b)}return G}function b0(z,J,$={}){let Z=$.fs??P,{path:K,opencode:Q}=N($),G=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((Y)=>{let X=K.join(Q,`${Y}.jsonc`),W=K.join(Q,`${Y}.json`),B=Z.exists(X)?X:Z.exists(W)?W:X,x=Z.exists(B),b=x?Z.readText(B):`${JSON.stringify({$schema:`https://opencode.ai/${Y==="tui"?"tui":"config"}.json`},null,2)}
|
|
12
|
+
`,j=u0(b,G),H=[],F=[];for(let D of["plugin","plugins"]){if(!Array.isArray(j[D]))continue;for(let M of j[D]){let I=p0(M);if(I===null)continue;if(G2(I,B,$)===z.packages.opencode)H.push(JSON.stringify(M));else if(X0(M)===z.packages.opencode)F.push(JSON.stringify(M))}}if(H.length>0)return{path:B,content:b,changed:!1,existingLocalEntries:H,existingNpmEntries:F};let O=c0(b,G,z.packages.opencode,z.version);return{path:B,content:O,changed:!x||O!==b}})}async function W0(z,J){for(let $ of z){if(!$.changed)continue;await J?.(),await h0($.path,$.content,{beforeRename:J})}}async function q0(z,J,$={}){let{platform:Z,env:K}=N($),Q=await i($.runner??T,Z,J,["install",`npm:${z.packages.pi}@${z.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new a({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var s0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function X2(z){for(let J of Object.values(z.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(J))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(z.version))throw Error("Setup requires a concrete package version.");for(let J of Object.values(z.vault.hosts)){if(!/^[a-z0-9][a-z0-9-]*$/.test(J.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.");if(J.requestedGrants!==void 0&&!l0(J.requestedGrants))throw Error("invalid Claustrum enrollment requested grants")}}async function b2(z,J,$,Z){let K=[];for(let Q of J){let G=$.get(Q)??"not-enrolled",q=Z.get(Q);if(G==="unknown"){let{name:Y,paths:X}=z.vault.hosts[Q],W=await p(A(X),Y).catch(()=>"unreadable");if(W==="vault"||W==="host")G="enrolled";else if(W==="local")G="not-enrolled";if(G==="enrolled"){let B=await i0(A(X),Y).catch(()=>{return});if(B?.state==="approved")q=await E({},B,A(X).tokenPath,z.vault.hosts[Q].requestedGrants)}}K.push({host:Q,outcome:G,...q&&{access:q}})}return K}async function Y0(z,J=[],$={}){let Z=f0(J);if(r())throw Error(y);X2(z);let K=$.terminal??a0(),Q=await Z0(z,$);U(K,`${z.displayName} setup`);for(let[D,M]of[["OpenCode",Q.opencode],["Pi",Q.pi]])U(K,`${D}: ${M.installed?`found (version ${M.version??"unknown"})`:"not found"} — ${M.directory}`);U(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let G=Q.pi.installed&&!Q.pi.executable;if(G)U(K,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let q=["opencode","pi"].filter((D)=>Q[D].installed&&!(D==="pi"&&G));if(Z.hosts.some((D)=>!q.includes(D)))throw Error(E0);let Y=Z.yes||Z.dryRun&&!d(K);if(!Y&&!d(K))throw Error("Setup requires a TTY or --yes.");let X=Z.hosts.length?q.filter((D)=>Z.hosts.includes(D)):Y?q:await g0(K,q)??[],W=Z.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(X.includes("opencode")&&!Z.opencode&&Q.opencode.generation==="ambiguous"){if(Y||!d(K))throw Error(s0);let D=await m(K,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(D===null)return{hosts:[],dryRun:Z.dryRun,mode:"local",detection:Q};W=D}if(!X.length)return U(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:X,dryRun:Z.dryRun,mode:"local",detection:Q};let{env:B,platform:x}=N($),b=$.fence??g($.runner??T,{platform:x}),j=async()=>{try{await h(b,B)}catch(D){if(D instanceof C)U(K,D.refusalText);throw D}};if(U(K,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let D=b.previewRunningHosts?await b.previewRunningHosts(B):{hosts:await b.listRunningHosts(B),uncheckedRuntimes:0},M=D.hosts;if(D.uncheckedRuntimes>0)U(K,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let I=new Set(new v(M).activeHosts.map((V)=>V.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let V of I)U(K,`${V} is running; setup will ask you to quit it.`)}catch(D){if(U(K,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),D instanceof C)U(K,D.refusalText)}else await j();if((Z.claustrum||Z.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let H=Z.claustrum||Z.enrollOnly;if(!H&&!Z.login&&!Z.noClaustrum&&!Y&&Q.claustrum.available&&d(K)){let D=await m(K,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(D===null)return U(K,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:Q};H=D===!0}let F=H?"claustrum":"local",O=!Z.enrollOnly&&X.includes("opencode")?b0(z,W,$):[];for(let D of O){for(let I of D.existingLocalEntries??[])U(K,`OpenCode: already registered from ${I} in ${D.path}.`);let M=[...D.existingLocalEntries??[],...D.existingNpmEntries??[]];if(M.length>1)U(K,`Warning: ${z.displayName} may load twice in ${D.path}: ${M.join(", ")}. Entries were left unchanged.`)}if(Z.dryRun){U(K,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let D of X){if(z.beforeSignIn)U(K,`Would run beforeSignIn(${D}, ${F}).`);if(H){let M=A(z.vault.hosts[D].paths);U(K,`Would Connect ${D}: write ${M.statePath} and ${M.tokenPath}; wait for ck auth enroll approve.`)}else U(K,`Would sign in locally for ${D}.`);if(!Z.enrollOnly&&z.beforeRegister)U(K,`Would run beforeRegister(${D}, ${F}).`)}for(let D of O)U(K,`${D.changed?"Would write":"Unchanged"} ${D.path}:
|
|
13
|
+
${D.content}`);if(!Z.enrollOnly&&X.includes("pi"))U(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!Z.enrollOnly&&z.migrate)for(let D of X)U(K,`Would migrate ${D} using the plugin callback (provider-specific writes).`)}else{let D={opencodeGeneration:W,mode:F,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},M=new Map,I=new Map;try{for(let V of X){if(await j(),await z.beforeSignIn?.(V,D),await j(),H){M.set(V,"unknown");try{let R=await y0(z,V,$,K,j);if(R)I.set(V,R)}catch(R){if(R instanceof _)M.set(V,"not-enrolled");throw R}M.set(V,"enrolled")}else await z.signInLocal(V,D);if(await j(),Z.enrollOnly)continue;if(await z.beforeRegister?.(V,F,D),await j(),V==="opencode")await W0(O,j);else await q0(z,Q.pi.executable,$);await j(),await z.migrate?.(V,D)}}catch(V){if(M.size===0)throw V;try{let R=await b2(z,X,M,I);O0(V,R);for(let l of R)U(K,M0(l))}catch{}throw V}}if(U(K,`${Z.dryRun?"Planned":Z.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${F}).`),Z.enrollOnly)U(K,`Enroll-only: no host config or plugin registration ${Z.dryRun?"will be":"was"} written.`),U(K,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else U(K,`Next: ${X.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:X,dryRun:Z.dryRun,mode:F,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.14.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.44.0","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.1.0","@opencode/plugin":"2.2.6"},dependencies:{"@cortexkit/claustrum-client":"^0.18.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.8.3","@opentui/solid":">=0.8.3",ai:"^7.0.165","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as j2}from"node:path";import{resolveClaustrumConnectionPath as V2}from"@cortexkit/claustrum-client";var r0={name:"@cortexkit/pi-openai-auth",version:"1.14.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.44.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.18.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as n}from"node:fs";import{homedir as t}from"node:os";import{join as e,resolve as o0}from"node:path";import{fileURLToPath as Y2}from"node:url";var n0=new Set;function B2(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return e(t(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return t();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return e(t(),z.slice(2));return z.startsWith("file://")?Y2(z):z}function e0(z=B2()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let $=e(z,B0),Z=e(t(),".pi","agent",B0),K=(G)=>{let q=D0(G),Y=t0(u(q),"pi");return n(G)||n(q)||n(Y.tokenPath)||n(Y.statePath)};if(o0($)===o0(Z)||K($)||!K(Z))return $;let Q=`${$}\x00${Z}`;if(!n0.has(Q))n0.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${Z} (${$} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return Z}function D2(z=e0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||D0(z)}function z1(z=e0()){return{configPath:z,statePath:D2(z)}}function G1(z={}){let J=z.print??console.log,$=z.fence??g(),Z={opencode:{stateDir:u($1().statePath),host:"opencode"},pi:{stateDir:u(z1().statePath),host:"pi"}},K=async(Q)=>{let G=await p(A(Z[Q]),c(Q));if(G==="host")throw Error(y);if(G!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:r0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:V2(),hosts:{opencode:{name:c("opencode"),displayName:V0("opencode"),requestedGrants:j0,paths:Z.opencode},pi:{name:c("pi"),displayName:V0("pi"),requestedGrants:j0,paths:Z.pi}}},async beforeRegister(Q,G){if(await p(A(Z[Q]),c(Q))==="host")throw Error(y);if(G==="claustrum"){if(Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,G){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(G.opencodeGeneration!=="1"){let F=j2(w("opencode2",z.io)??w("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${F} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(G.opencodeGeneration==="2")return;if(K1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let q=Q1(),Y={path:{id:"openai"}};if(await q.get(Y)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??J1,W=new AbortController,B=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),x={version:L.version,signal:W.signal},b,j=!B;try{b=await X({...x,headless:B})}catch(F){if(B)throw F;j=!1,J("Browser callback unavailable; using device-code sign-in."),b=await X({version:L.version,headless:!0})}if(j){if(!(z.openBrowser??Z1)(b.url))W.abort(),await b.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),b=await X({version:L.version,headless:!0})}J(`${b.url}
|
|
14
|
+
${b.instructions}`);let H=await b.completion;await h($),await K(Q),await q.set({...Y,body:{type:"oauth",access:H.access,refresh:H.refresh,expires:H.expires,...H.accountId?{accountId:H.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await X1({version:L.version}),await Y0(G1(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
|
|
@@ -653,11 +653,27 @@ interface ClaustrumWatchState {
|
|
|
653
653
|
readonly vault: WatchMode;
|
|
654
654
|
readonly insula?: WatchMode;
|
|
655
655
|
}
|
|
656
|
+
type ClaustrumRequestedGrant = {
|
|
657
|
+
selector: {
|
|
658
|
+
category: string;
|
|
659
|
+
exact?: never;
|
|
660
|
+
} | {
|
|
661
|
+
exact: string;
|
|
662
|
+
category?: never;
|
|
663
|
+
};
|
|
664
|
+
operation: 'read' | 'list';
|
|
665
|
+
};
|
|
666
|
+
interface EnrollmentGrantProposal {
|
|
667
|
+
requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
|
|
668
|
+
/** Sent is not proof of access: the operator can approve without grants. */
|
|
669
|
+
requestedGrantsStatus?: 'sent' | 'dropped';
|
|
670
|
+
}
|
|
656
671
|
interface ClaustrumEnrollmentClient {
|
|
657
672
|
enrollPropose(input: {
|
|
658
673
|
name: string;
|
|
659
674
|
requestSecretHash: string;
|
|
660
675
|
displayName?: string;
|
|
676
|
+
requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
|
|
661
677
|
}): Promise<{
|
|
662
678
|
requestId: string;
|
|
663
679
|
}>;
|
|
@@ -668,20 +684,21 @@ interface ClaustrumEnrollmentClient {
|
|
|
668
684
|
}
|
|
669
685
|
interface ClaustrumEnrollmentConnection extends ClaustrumEnrollmentClient {
|
|
670
686
|
close(): void;
|
|
687
|
+
listScoped?: ClaustrumClient['listScoped'];
|
|
671
688
|
}
|
|
672
689
|
type ClaustrumEnrollmentStatus = {
|
|
673
690
|
state: 'idle';
|
|
674
|
-
} | {
|
|
691
|
+
} | (EnrollmentGrantProposal & {
|
|
675
692
|
state: 'pending';
|
|
676
693
|
proposedName: string;
|
|
677
694
|
requestId?: string;
|
|
678
695
|
retryCode?: string;
|
|
679
|
-
} | {
|
|
696
|
+
}) | (EnrollmentGrantProposal & {
|
|
680
697
|
state: 'approved';
|
|
681
698
|
proposedName: string;
|
|
682
699
|
approvedName?: string;
|
|
683
700
|
tokenGeneration: number;
|
|
684
|
-
} | {
|
|
701
|
+
}) | {
|
|
685
702
|
state: 'denied';
|
|
686
703
|
proposedName: string;
|
|
687
704
|
} | {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{B as
|
|
1
|
+
import{wg as y}from"./index-cxnrd85v.js";import{randomUUID as k}from"node:crypto";import{lstat as N,readFile as f,rename as F,unlink as I}from"node:fs/promises";import{tmpdir as P}from"node:os";import{dirname as W,join as E,resolve as K}from"node:path";var B=process.platform==="win32",L=new Set;function V(j){if(j?.reason==="io-error"){if(j.win32Code===2||j.win32Code===3)return"ENOENT";if(j.win32Code===80||j.win32Code===183)return"EEXIST"}return j?.code??"ERR_PRIVATE_FILE"}var _;var b="native-addon-unavailable";function v(j){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:j}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:b})}function g(j,x){return x instanceof j.PrivateFilesUnavailableError||x?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function m(j){try{await j.verifyPrivatePath(E(P(),`.common-auth-private-files-probe-${k()}`),"file")}catch(x){if(g(j,x))throw v(x)}}function $(){return _??=import("@cortexkit/private-files").then(async(j)=>{if(B)await m(j);return j},(j)=>{throw B?v(j):j}),_}class Q extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor(j,x,z){let q=z;super(q?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${x}: ${j} (${b}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${x}: ${j} (${q?.reason??q?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:z});this.path=j,this.stage=x,this.name="PrivateFileError",this.code=V(q),this.win32Code=q?.win32Code,this.reason=q?.reason}}function p(j){return B&&j instanceof Q&&j.reason==="io-error"&&(j.win32Code===32||j.win32Code===303)}async function T(j,x,z){try{return await z()}catch(q){if(q instanceof Q)throw q;throw new Q(j,x,q)}}var c;async function Y(j,x){j=K(j),x??=c,await T(j,"safe-parent",async()=>{let z=await(await $()).verifySafeParent(j,x);if(z.ok===!1){if(z.reason==="io-error"||z.reason==="wrong-kind")await N(j);throw new Q(z.level??z.path,"safe-parent",{...z,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function S(j,x,z=!1){if(j=K(j),x==="directory")return Y(j);await T(j,"verify",async()=>{let q=await $(),H=await q.verifyOwnerOnly(j),C=!1;if(!H.ok){let{reason:J}=H.refusal;if(J==="io-error")await q.verifyPrivatePath(j,x);if(z&&[q.EXTRA_ACE,q.NOT_PROTECTED,q.NULL_DACL,q.EMPTY_DACL].includes(J))await Y(W(j)),await q.securePrivatePath(j,x),C=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:J,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await q.verifyPrivatePath(j,x),C&&!L.has(j))L.add(j),process.emitWarning(`Private permissions tightened: ${j}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function w(j,x=!1,z){j=K(j),await T(j,"directory",async()=>{let q=await $();try{return await N(j),await Y(j,z)}catch(C){if(V(C)!=="ENOENT")throw C}let H=W(j);if(H===j)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await w(H,!1,z);try{await q.createOwnerOnly(j,{kind:"dir"})}catch(C){if(V(C)!=="EEXIST")throw C}await Y(j,z)})}async function e(j,x=!1){if(!B)return f(j,"utf8");return(await u(j,x)).toString("utf8")}async function u(j,x=!1){if(!B)return f(j);if(j=K(j),x)await Y(W(j)),await S(j,"file",!0);return T(j,"read",async()=>(await $()).readOwnerOnly(j))}async function d(j,x){await Y(W(K(j))),await T(j,"create",async()=>{await(await $()).createPrivateFile(K(j),x)})}async function r(j){await Y(W(K(j))),await T(j,"directory-create",async()=>{await(await $()).createOwnerOnly(K(j),{kind:"dir"})})}async function l(j,x,z={}){j=K(j),x=K(x);let q=z.now??(()=>performance.now()),H=q(),C=z.deadline??1/0,J,Z=[0,10,20,40,80,100],U,G=0;for(let D of Z){let R=Math.min(J??1/0,C);if(q()>=R)break;if(D)await(z.sleep??((O)=>new Promise((X)=>setTimeout(X,O))))(Math.min(D,Math.max(0,R-q())));if(q()>=R)break;let A=q();if(await z.beforeRename?.(),J!==void 0)J+=q()-A;if(q()>=C)break;G++;try{return await(z.rename??F)(j,x),{attempts:G,elapsedMs:q()-H}}catch(O){U??=O;let X=O;if(!(X.win32Code!==void 0?X.win32Code===32||X.win32Code===33:["EBUSY","EPERM","EACCES"].includes(X.code??"")&&!X.reason))break;J??=q()+500}}let M=new Q(x,"rename",U??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw M.attempts=G,M.elapsedMs=q()-H,M}async function a(j,x,z={}){j=K(j),await w(W(j));try{await S(j,"file",!0)}catch(G){if(G.code!=="ENOENT")throw G}let q=K(z.stagePath??`${j}.${k()}.tmp`);if(W(q)!==W(j))throw new Q(j,"stage-directory",{code:"EXDEV"});let H=!1,C=!1,J={attempts:0,elapsedMs:0},Z="stage-create",U=(G)=>{try{z.onOutcome?.({path:j,stage:G?.stage??"published",published:C,fileDurable:C,durabilityConfirmed:!1,attempts:G?.attempts??J.attempts,elapsedMs:G?.elapsedMs??J.elapsedMs,...G&&{code:G.code,win32Code:G.win32Code}})}catch{}};try{if(await d(q,x),H=!0,Z="before-rename",J=await l(q,j,z),H=!1,C=!0,Z="published-callback",z.onRenamed?.(),Z="published-verify",await S(j,"file"),z.durable&&z.durability!=="file-only-on-windows")throw new Q(j,"directory-sync-unsupported",{code:"ENOTSUP"});U()}catch(G){let M=G instanceof Q?G:new Q(j,Z,G);if(M.published=C,M.fileDurable=C,C)Object.assign(M,J);if(H){try{await I(q)}catch{M.orphanPath=q}H=!1}throw U(M),M}finally{if(H)await I(q).catch(()=>{})}}
|
|
2
|
+
export{B as eg,Q as fg,p as gg,T as hg,Y as ig,S as jg,w as kg,e as lg,d as mg,r as ng,l as og,a as pg};
|