@cortexkit/opencode-openai-auth 1.13.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +9 -9
- package/dist/{codex-request-Bu2sjxQn.d.ts → codex-request-Cl6zEfsR.d.ts} +20 -3
- package/dist/{index-tzrf3ax2.js → index-1abcvt9p.js} +1 -1
- package/dist/{index-th0bzvpn.js → index-3c9pk6zn.js} +2 -2
- package/dist/{index-0bh5fs56.js → index-4tpttpjw.js} +1 -1
- package/dist/index-4zpxwh8y.js +91 -0
- package/dist/{index-2ccfywax.js → index-a9tzfpxy.js} +1 -1
- package/dist/{index-2g95z7kb.js → index-bc2d4vma.js} +21 -21
- package/dist/{index-zmerz2yv.js → index-f7t7cc9b.js} +1 -1
- package/dist/{index-p8v28mh9.js → index-nfbmjq6g.js} +2 -2
- package/dist/{index-r8y79mzp.js → index-q111b2h5.js} +1 -1
- package/dist/{index-rhe4jm5t.js → index-wap9mf5f.js} +2 -2
- package/dist/{index-cs0tey1r.js → index-xxmaf5ks.js} +2 -2
- package/dist/{index-khqwa7g2.js → index-yew3mp47.js} +19 -19
- package/dist/{index-4s50rsec.js → index-zcpher1w.js} +2 -2
- 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-6x4q5r2r.js} +1 -1
- package/dist/token-util-54mhq85x.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-a9tzfpxy.js";import{Ha as a0,Ia as d,Ja as U,Ka as m,Tb as $1,jc as K1,ta as j0,ua as c,va as V0,wa as u,wc as X1,xa as t0}from"./index-yew3mp47.js";import{Nd as y,Od as r,Qd as P0,Sd as l0,Td as s,Ud as A,Vd as i0,Wd as p,Xd as U0,Yd as L0,ue as J1}from"./index-4zpxwh8y.js";import"./index-zcpher1w.js";import"./index-xxmaf5ks.js";import"./index-3c9pk6zn.js";import{$f as D0,Tf as H0,Zf as B0,cg as Z1}from"./index-wap9mf5f.js";import"./index-nfbmjq6g.js";import"./index-q111b2h5.js";import"./index-1abcvt9p.js";import{spawn as W1}from"node:child_process";var k=4096,q1=1048576;class x0{buffer=Buffer.alloc(k);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=k){if(z.length>k||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-k),this.start=0,this.length=k;return}let J=Math.max(0,this.length+z.length-k);if(J>0)this.truncated=!0;this.start=(this.start+J)%k,this.length-=J;let $=(this.start+this.length)%k,Z=Math.min(z.length,k-$);if(z.copy(this.buffer,$,0,Z),Z<z.length)z.copy(this.buffer,0,Z);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,k-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let $=0;while($<z.length){let Z=z[$];if(Z===void 0||(Z&192)!==128)break;$++}return z.subarray($).toString("utf8")}}var T={run(z,J,$={}){return new Promise((Z)=>{let K=performance.now(),Q=$.timeoutMs??15000,G=new x0,q=[],Y=0,X=!1,W=!1,B=!1,x;try{x=W1(z,[...J],{env:$.env??process.env,windowsHide:!0,windowsVerbatimArguments:$.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let b=Q>0?setTimeout(()=>{B=!0,x.kill("SIGTERM")},Q):void 0;x.stdout?.on("data",(F)=>{let O=q1-Y,D=Math.min(O,F.length);if(D>0)q.push(F.subarray(0,D)),Y+=D;if(F.length>O)X=!0,x.kill("SIGTERM")}),x.stderr?.on("data",(F)=>G.push(F));let j=!1,H=(F,O)=>{if(j)return;if(j=!0,b)clearTimeout(b);Z({exitCode:W?1:X?1:F??1,stdout:Buffer.concat(q,Y).toString("utf8"),stderr:G.toString(),stderrTruncated:G.didTruncate,...W?{spawnError:!0}:{},signal:O??null,timedOut:B,durationMs:performance.now()-K})};x.once("error",()=>{if(W=!0,x.pid===void 0)H(null,null)}),x.once("close",(F,O)=>H(F,O))})}};function i(z,J,$,Z,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test($)){if(/["%!\r\n]/.test($)||Z.some((G)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(G)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${$}" ${Z.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run($,Z,{env:K,timeoutMs:Q})}function F0(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function E(z,J,$,Z){let K=J.requestedGrants??Z;if(!K)return;let Q=K.map((G)=>({grant:G,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${F0(`enrolled:${J.approvedName}`)} --selector-kind ${G.selector.exact===void 0?"category":"exact"} --selector ${F0(G.selector.exact??G.selector.category)} --operation ${G.operation}`}}));if(J.requestedGrantsStatus==="dropped")return{state:"older-vault",grants:Q};try{if(!z.listScoped)return{state:"unconfirmed",grants:Q};let{token:G}=await U0($),q=await z.listScoped(G),Y=Q.map((X)=>({...X,reachableLogins:q.rows.filter((W)=>W.operations.includes(X.grant.operation)&&(X.grant.selector.exact!==void 0?W.id===X.grant.selector.exact:W.categories.includes(X.grant.selector.category))).length}));return{state:Y.every((X)=>X.reachableLogins>0)?"reachable":Y.some((X)=>X.reachableLogins>0)?"partial":"no-logins",grants:Y.map((X)=>{if(X.reachableLogins===0)return X;let{grantCommand:W,...B}=X;return B})}}catch{return{state:"unconfirmed",grants:Q}}}function f(z){let J=[],$=z.grants.some((Z)=>Z.grantCommand)?"run:":"check ck auth status for the approved name before granting access.";if(z.state==="older-vault")J.push(`Approved. This vault is too old to grant access with the approval; ${$}`);else if(z.state==="no-logins")J.push(`Approved, but no logins are reachable yet; ${$}`);else if(z.state==="partial")J.push(`Approved, but some requested access has no reachable logins yet; ${$}`);else if(z.state==="unconfirmed")J.push(`Approved, but access could not be confirmed; ${z.grants.some((Z)=>Z.grantCommand)?"check ck auth status or run:":$}`);for(let{grant:Z,reachableLogins:K,grantCommand:Q}of z.grants){if(K!==void 0&&K>0){let G=Z.selector.exact===void 0?`the vault's ${JSON.stringify(Z.selector.category)} accounts`:`credential ${JSON.stringify(Z.selector.exact)}`;J.push(`Confirmed ${Z.operation} access to ${G} (${K} reachable ${K===1?"login":"logins"}).`)}if(Q)J.push(` ${Q}`)}return J}var Y1="Pi install failed; run pi install after checking your npm connection.";function B1(z){let J=Buffer.from(z,"utf8");if(J.length<=k)return z;let $=J.length-k;while($<J.length){let Z=J[$];if(Z===void 0||(Z&192)!==128)break;$++}return J.subarray($).toString("utf8")}function D1(z){let J=z.indexOf(`
|
|
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.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.44.0","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.1.0","@opencode/plugin":"2.2.6"},dependencies:{"@cortexkit/claustrum-client":"^0.18.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.8.3","@opentui/solid":">=0.8.3",ai:"^7.0.165","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as j2}from"node:path";import{resolveClaustrumConnectionPath as V2}from"@cortexkit/claustrum-client";var r0={name:"@cortexkit/pi-openai-auth",version:"1.14.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.44.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.18.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as n}from"node:fs";import{homedir as t}from"node:os";import{join as e,resolve as o0}from"node:path";import{fileURLToPath as Y2}from"node:url";var n0=new Set;function B2(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return e(t(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return t();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return e(t(),z.slice(2));return z.startsWith("file://")?Y2(z):z}function e0(z=B2()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let $=e(z,B0),Z=e(t(),".pi","agent",B0),K=(G)=>{let q=D0(G),Y=t0(u(q),"pi");return n(G)||n(q)||n(Y.tokenPath)||n(Y.statePath)};if(o0($)===o0(Z)||K($)||!K(Z))return $;let Q=`${$}\x00${Z}`;if(!n0.has(Q))n0.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${Z} (${$} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return Z}function D2(z=e0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||D0(z)}function z1(z=e0()){return{configPath:z,statePath:D2(z)}}function G1(z={}){let J=z.print??console.log,$=z.fence??g(),Z={opencode:{stateDir:u($1().statePath),host:"opencode"},pi:{stateDir:u(z1().statePath),host:"pi"}},K=async(Q)=>{let G=await p(A(Z[Q]),c(Q));if(G==="host")throw Error(y);if(G!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:r0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:V2(),hosts:{opencode:{name:c("opencode"),displayName:V0("opencode"),requestedGrants:j0,paths:Z.opencode},pi:{name:c("pi"),displayName:V0("pi"),requestedGrants:j0,paths:Z.pi}}},async beforeRegister(Q,G){if(await p(A(Z[Q]),c(Q))==="host")throw Error(y);if(G==="claustrum"){if(Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,G){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(G.opencodeGeneration!=="1"){let F=j2(w("opencode2",z.io)??w("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${F} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(G.opencodeGeneration==="2")return;if(K1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let q=Q1(),Y={path:{id:"openai"}};if(await q.get(Y)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??J1,W=new AbortController,B=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),x={version:L.version,signal:W.signal},b,j=!B;try{b=await X({...x,headless:B})}catch(F){if(B)throw F;j=!1,J("Browser callback unavailable; using device-code sign-in."),b=await X({version:L.version,headless:!0})}if(j){if(!(z.openBrowser??Z1)(b.url))W.abort(),await b.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),b=await X({version:L.version,headless:!0})}J(`${b.url}
|
|
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
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 tg,r as ug,t as vg,u as wg,v as xg};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{dg as U,eg as E,ig as F,jg as p,kg as L,og as c}from"./index-nfbmjq6g.js";import{createHash as Cz,randomUUID as y}from"node:crypto";import{chmod as zz,mkdir as Gz,open as Jz,readdir as b,rename as Kz,rmdir as Nz,stat as S,unlink as T}from"node:fs/promises";import{uptime as Qz}from"node:os";import{join as R,resolve as g}from"node:path";function x(z){return(z.now??Date.now)()-(z.uptime??Qz)()*1000-300000}function k(z,G,Q){let V=z.startedAt===void 0?G?.mtimeMs:z.startedAt;return typeof V==="number"&&Number.isFinite(V)&&V<Q}async function Vz(z,G,Q,V){if(!Q)return;await V?.(z);try{let J=await L(z),K=await S(z);if(J===G&&K.dev===Q.dev&&K.ino===Q.ino&&K.mtimeMs===Q.mtimeMs&&K.size===Q.size)await T(z).catch(()=>{})}catch(J){if(J instanceof E&&J.code!=="ENOENT")throw J}}function a(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function u(z){if(!a(z))return!1;try{return process.kill(z,0),!0}catch(G){return G.code==="EPERM"}}function Uz(z){return(G)=>Wz(G,z)}function Wz(z,G){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(G)&&/^[0-9a-f]{16}$/.test(z.slice(G.length))}function Xz(z){let G=/^port-(\d+)\.json$/.exec(z);return G?Number(G[1]):void 0}function s(z,G){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:Q,port:V,token:J}=z;return a(Q)&&Xz(G)===Q&&typeof V==="number"&&Number.isInteger(V)&&V>=1&&V<=65535&&typeof J==="string"&&J.length>0}async function l(z,G){G?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await T(z).catch(()=>{})}async function Ez(z,G,Q={}){let V=async()=>{let J=R(z,`port-${G.pid}.json`);if(U)return await p(z,Q.secureDir??!1),await Q.beforeWrite?.(),await c(J,JSON.stringify({...G,startedAt:Date.now()}),{stagePath:`${J}.${(Q.stageName??y)()}.tmp`}),J;if(await Gz(z,{recursive:!0,mode:Q.secureDir?448:void 0}),Q.secureDir)await zz(z,448);await Q.beforeWrite?.();let K={...G,startedAt:Date.now()},Y=`${J}.${(Q.stageName??y)()}.tmp`,W,N=!1;try{W=await Jz(Y,"wx",384),N=!0,await W.writeFile(JSON.stringify(K),"utf8"),await W.chmod(384),await W.close(),W=void 0,await Kz(Y,J),N=!1}finally{if(await W?.close().catch(()=>{}),N)await T(Y).catch(()=>{})}return J};try{return await V()}catch(J){if(J.code==="ENOENT")return await V();throw J}}async function Lz(z,G,Q,V,J={}){let K=x(J),Y;try{Y=await b(z,{withFileTypes:!0})}catch(N){if(N.code==="ENOENT")return;throw N}let W=g(G);for(let N of Y){if(!N.isDirectory()||!Q(N.name))continue;let X=R(z,N.name),Z;try{Z=await b(X)}catch($){if($.code==="ENOENT")continue;throw $}for(let $ of Z){if(!$.startsWith("port-")||!$.endsWith(".json"))continue;let H=R(X,$),C=await S(H).catch(()=>{return}),q;try{q=await L(H)}catch(O){if(O instanceof E&&O.code!=="ENOENT")throw O;continue}if(q===void 0)continue;let A;try{A=JSON.parse(q)}catch{await l(H,V);continue}if(!s(A,$)){await l(H,V);continue}let I=A;if(!u(I.pid))await T(H).catch(()=>{});else if(k(I,C,K))await Vz(H,q,C,J.beforeRemove)}if(g(X)!==W)await Nz(X).catch(()=>{})}}async function d(z,G,Q={}){let V=x(Q);if(!u(G.pid))return null;let J=R(g(z),`port-${G.pid}.json`);try{if(U)await F(J,"file");let K=await S(J);if(k(G,K,V))return null;return`${J}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch(K){if(K instanceof E&&K.code!=="ENOENT")throw K;return null}}async function n(z,G,Q={}){let V=x(Q),J;try{if(U)await F(z,"directory");J=await b(z)}catch(X){if(X instanceof E&&X.code!=="ENOENT")throw X;return null}let K=[];for(let X of J){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;try{let Z=JSON.parse(await L(R(z,X)));if(s(Z,X))if(u(Z.pid)){let $=Z.startedAt===void 0?await S(R(z,X)).catch(()=>{return}):void 0;if(!k(Z,$,V))K.push(Z)}else await T(R(z,X)).catch(()=>{})}catch(Z){if(Z instanceof E&&Z.code!=="ENOENT")throw Z}}if(K.length===0)return null;let Y=G!==void 0&&G>=1?K.filter((X)=>X.pid===G):[];if(Q.exactPid===!0&&Y.length===0)return null;let W=Y.length>0?Y:K,N=(X)=>typeof X.startedAt==="number"&&Number.isFinite(X.startedAt)?X.startedAt:-1/0;return W.sort((X,Z)=>N(Z)-N(X))[0]??null}import{open as Yz}from"node:fs/promises";import{connect as Zz}from"node:net";import{join as $z,resolve as t}from"node:path";var e=2000,_=new Map,B=new Map;async function Hz(z,G){let Q=$z(t(z),`port-${G.pid}.json`);if(U){let J=JSON.parse(await L(Q));if(J.pid!==G.pid||J.port!==G.port||J.token!==G.token)return null;return null}let V;try{V=await Yz(Q,"r");let J=await V.stat(),K=JSON.parse(await V.readFile("utf8"));if(K.pid!==G.pid||K.port!==G.port||K.token!==G.token)return null;return`${Q}:${J.dev}:${J.ino}:${J.mtimeMs}:${J.size}`}catch{return null}finally{await V?.close().catch(()=>{})}}async function i(z,G,Q,V){let J=_.get(z);if(!U&&J&&await d(G,J.entry)===J.identity)return J;_.delete(z);let K=B.get(z);if(K)return K;let Y=(async()=>{let W=await(V.discover??n)(G,Q,V);if(!W)return null;let N=await Hz(G,W);if(!N)return{entry:W,identity:""};let X={entry:W,identity:N};return _.set(z,X),X})();B.set(z,Y);try{return await Y}finally{if(B.get(z)===Y)B.delete(z)}}async function o(z,G,Q,V=e){return new Promise((J)=>{let K,Y=!1,W=!1,N=(Z,$=!1)=>{if(Y)return;Y=!0,clearTimeout(X),K?.destroy(),J({value:Z,stale:$})},X=setTimeout(()=>N(null),V);try{let Z=JSON.stringify(Q);K=Zz({host:"127.0.0.1",port:z.port}),K.on("connect",()=>{W=!0,K?.write(`POST /rpc/${G} HTTP/1.0\r
|
|
2
2
|
Host: 127.0.0.1:${z.port}\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
Content-Type: application/json\r
|
|
@@ -9,4 +9,4 @@ Authorization: Bearer ${z.token}\r
|
|
|
9
9
|
\r
|
|
10
10
|
`);if(D>=0)C=D+4;if((C??A.length)>16384)return N(null);if(C!==void 0){let P=A.subarray(0,D).toString("latin1").split(`\r
|
|
11
11
|
`),f=/^HTTP\/1\.[01] (\d{3})(?: |$)/.exec(P[0]??"");if(!f)return N(null);let j=Number(f[1]);if(j<200||j>=300)return N(null,[401,403,404,410].includes(j));for(let w of P.slice(1)){let v=w.indexOf(":"),h=w.slice(0,v).toLowerCase(),m=w.slice(v+1).trim();if(h==="transfer-encoding")return N(null);if(h==="content-length"){if(q!==void 0||!/^\d+$/.test(m))return N(null);if(q=Number(m),!Number.isSafeInteger(q)||q>8388608)return N(null)}}A=Buffer.alloc(0)}}let M=H-(C??H);if(M>8388608)return N(null);if(q!==void 0){if(M>q)return N(null);if(M===q)I()}}),K.on("end",()=>{if(q!==void 0&&H-(C??0)!==q)return N(null);I()}),K.on("error",()=>N(null,!W)),K.on("close",()=>N(null))}catch{N(null,!W)}})}async function r(z,G,Q,V,J,K,Y=e){let W=JSON.stringify([t(z),G??null,Q.exactPid===!0]),N=await i(W,z,G,Q);if(V(N?.entry??null),!N)return null;let X=Date.now()+Y,Z=await o(N.entry,J,K,Y);if(!Z.stale)return Z.value;if(_.get(W)===N)_.delete(W);let $=await i(W,z,G,Q);if(!$||Date.now()>=X)return null;if($.entry.port===N.entry.port&&$.entry.pid===N.entry.pid&&$.entry.token===N.entry.token){if(_.get(W)===$)_.delete(W);return null}let H=await o($.entry,J,K,X-Date.now());if(H.stale&&_.get(W)===$)_.delete(W);return H.value}function jz(z,G,Q,V={}){let J={exactPid:V.exactPid,discover:V.discover},K=!1,Y=(W)=>{if(K)return;Q?.(W),K=!0};return{async pending(W,N,X){return(await r(z,G,J,Y,"pending-notifications",{lastReceivedId:W,sessionId:N},X))?.messages??[]},async apply(W,N){return await r(z,G,J,Y,"apply",{...W},N)??{text:"apply failed",knobs:{}}}}}
|
|
12
|
-
export{Uz as
|
|
12
|
+
export{Uz as Mf,Ez as Nf,Lz as Of,n as Pf,e as Qf,jz as Rf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{tg as Z,vg as W}from"./index-1abcvt9p.js";var R=Z(($G,E)=>{var{defineProperty:N,getOwnPropertyDescriptor:Kz,getOwnPropertyNames:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,G)=>{for(var H in G)N(z,H,{get:G[H],enumerable:!0})},Yz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Qz(G))if(!Wz.call(z,K)&&K!==H)N(z,K,{get:()=>G[K],enumerable:!(Q=Kz(G,K))||Q.enumerable})}return z},Zz=(z)=>Yz(N({},"__esModule",{value:!0}),z),O={};Xz(O,{VercelOidcTokenError:()=>S});E.exports=Zz(O);class S extends Error{constructor(z,G){super(z);this.name="VercelOidcTokenError",this.cause=G}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var P=Z((qG,y)=>{var{create:$z,defineProperty:L,getOwnPropertyDescriptor:qz,getOwnPropertyNames:vz,getPrototypeOf:Bz}=Object,Fz=Object.prototype.hasOwnProperty,Uz=(z,G)=>{for(var H in G)L(z,H,{get:G[H],enumerable:!0})},C=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of vz(G))if(!Fz.call(z,K)&&K!==H)L(z,K,{get:()=>G[K],enumerable:!(Q=qz(G,K))||Q.enumerable})}return z},I=(z,G,H)=>(H=z!=null?$z(Bz(z)):{},C(G||!z||!z.__esModule?L(H,"default",{value:z,enumerable:!0}):H,z)),Lz=(z)=>C(L({},"__esModule",{value:!0}),z),x={};Uz(x,{findRootDir:()=>Jz,getUserDataDir:()=>Nz});y.exports=Lz(x);var B=I(W("path")),bz=I(W("fs")),A=I(W("os")),Vz=R();function Jz(){try{let z=process.cwd();while(z!==B.default.dirname(z)){let G=B.default.join(z,".vercel");if(bz.default.existsSync(G))return z;z=B.default.dirname(z)}}catch(z){throw new Vz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Nz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return B.default.join(A.default.homedir(),"Library/Application Support");case"linux":return B.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var i=Z((vG,c)=>{var{create:Rz,defineProperty:b,getOwnPropertyDescriptor:Az,getOwnPropertyNames:Iz,getPrototypeOf:Dz}=Object,wz=Object.prototype.hasOwnProperty,Tz=(z,G)=>{for(var H in G)b(z,H,{get:G[H],enumerable:!0})},u=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Iz(G))if(!wz.call(z,K)&&K!==H)b(z,K,{get:()=>G[K],enumerable:!(Q=Az(G,K))||Q.enumerable})}return z},l=(z,G,H)=>(H=z!=null?Rz(Dz(z)):{},u(G||!z||!z.__esModule?b(H,"default",{value:z,enumerable:!0}):H,z)),jz=(z)=>u(b({},"__esModule",{value:!0}),z),g={};Tz(g,{isValidAccessToken:()=>Ez,readAuthConfig:()=>Oz,writeAuthConfig:()=>Sz});c.exports=jz(g);var F=l(W("fs")),h=l(W("path")),Mz=f();function k(){let z=(0,Mz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(z,"auth.json")}function Oz(){try{let z=k();if(!F.existsSync(z))return null;let G=F.readFileSync(z,"utf8");if(!G)return null;return JSON.parse(G)}catch(z){return null}}function Sz(z){let G=k(),H=h.dirname(G);if(!F.existsSync(H))F.mkdirSync(H,{mode:504,recursive:!0});F.writeFileSync(G,JSON.stringify(z,null,2),{mode:384})}function Ez(z,G=0){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let H=Math.floor(Date.now()/1000),Q=G/1000;return z.expiresAt>=H+Q}});var a=Z((BG,s)=>{var{defineProperty:T,getOwnPropertyDescriptor:Cz,getOwnPropertyNames:xz}=Object,yz=Object.prototype.hasOwnProperty,Pz=(z,G)=>{for(var H in G)T(z,H,{get:G[H],enumerable:!0})},uz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of xz(G))if(!yz.call(z,K)&&K!==H)T(z,K,{get:()=>G[K],enumerable:!(Q=Cz(G,K))||Q.enumerable})}return z},lz=(z)=>uz(T({},"__esModule",{value:!0}),z),d={};Pz(d,{processTokenResponse:()=>iz,refreshTokenRequest:()=>cz});s.exports=lz(d);var D=W("os"),gz="https://vercel.com",hz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",p=`@vercel/oidc node-${process.version} ${(0,D.platform)()} (${(0,D.arch)()}) ${(0,D.hostname)()}`,w=null;async function kz(){if(w)return w;let z=`${gz}/.well-known/openid-configuration`,G=await fetch(z,{headers:{"user-agent":p}});if(!G.ok)throw Error("Failed to discover OAuth endpoints");let H=await G.json();if(!H||typeof H.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let Q=H.token_endpoint;return w=Q,Q}async function cz(z){let G=await kz();return await fetch(G,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":p},body:new URLSearchParams({client_id:hz,grant_type:"refresh_token",...z})})}async function iz(z){let G=await z.json();if(!z.ok){let H=typeof G==="object"&&G&&"error"in G?String(G.error):"Token refresh failed";return[Error(H)]}if(typeof G!=="object"||G===null)return[Error("Invalid token response")];if(typeof G.access_token!=="string")return[Error("Missing access_token in response")];if(G.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof G.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,G]}});var t=Z((FG,r)=>{var{defineProperty:j,getOwnPropertyDescriptor:fz,getOwnPropertyNames:dz}=Object,pz=Object.prototype.hasOwnProperty,sz=(z,G)=>{for(var H in G)j(z,H,{get:G[H],enumerable:!0})},az=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of dz(G))if(!pz.call(z,K)&&K!==H)j(z,K,{get:()=>G[K],enumerable:!(Q=fz(G,K))||Q.enumerable})}return z},_z=(z)=>az(j({},"__esModule",{value:!0}),z),_={};sz(_,{AccessTokenMissingError:()=>m,RefreshAccessTokenFailedError:()=>n});r.exports=_z(_);class m extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login).");this.name="AccessTokenMissingError"}}class n extends Error{constructor(z){super("Failed to refresh authentication token.",{cause:z});this.name="RefreshAccessTokenFailedError"}}});var f=Z((UG,Hz)=>{var{create:mz,defineProperty:V,getOwnPropertyDescriptor:nz,getOwnPropertyNames:rz,getPrototypeOf:tz}=Object,ez=Object.prototype.hasOwnProperty,oz=(z,G)=>{for(var H in G)V(z,H,{get:G[H],enumerable:!0})},o=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of rz(G))if(!ez.call(z,K)&&K!==H)V(z,K,{get:()=>G[K],enumerable:!(Q=nz(G,K))||Q.enumerable})}return z},zz=(z,G,H)=>(H=z!=null?mz(tz(z)):{},o(G||!z||!z.__esModule?V(H,"default",{value:z,enumerable:!0}):H,z)),zG=(z)=>o(V({},"__esModule",{value:!0}),z),Gz={};oz(Gz,{assertVercelOidcTokenResponse:()=>M,findProjectInfo:()=>QG,getTokenPayload:()=>YG,getVercelDataDir:()=>GG,getVercelOidcToken:()=>KG,getVercelToken:()=>HG,isExpired:()=>ZG,loadToken:()=>XG,saveToken:()=>WG});Hz.exports=zG(Gz);var U=zz(W("path")),X=zz(W("fs")),v=R(),J=P(),$=i(),e=a(),q=t();function GG(){let G=(0,J.getUserDataDir)();if(!G)return null;return U.join(G,"com.vercel.cli")}async function HG(z){let G=(0,$.readAuthConfig)();if(!G?.token)throw new q.AccessTokenMissingError;if((0,$.isValidAccessToken)(G,z?.expirationBufferMs))return G.token;if(!G.refreshToken)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError("No refresh token available");try{let H=await(0,e.refreshTokenRequest)({refresh_token:G.refreshToken}),[Q,K]=await(0,e.processTokenResponse)(H);if(Q||!K)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError(Q);let Y={token:K.access_token,expiresAt:Math.floor(Date.now()/1000)+K.expires_in};if(K.refresh_token)Y.refreshToken=K.refresh_token;return(0,$.writeAuthConfig)(Y),Y.token}catch(H){if((0,$.writeAuthConfig)({}),H instanceof q.AccessTokenMissingError||H instanceof q.RefreshAccessTokenFailedError)throw H;throw new q.RefreshAccessTokenFailedError(H)}}async function KG(z,G,H){let Q=`https://api.vercel.com/v1/projects/${G}/token?source=vercel-oidc-refresh${H?`&teamId=${H}`:""}`,K=await fetch(Q,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!K.ok)throw new v.VercelOidcTokenError(`Failed to refresh OIDC token: ${K.statusText}`);let Y=await K.json();return M(Y),Y}function M(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function QG(){let z=(0,J.findRootDir)();if(!z)throw new v.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let G=U.join(z,".vercel","project.json");if(!X.existsSync(G))throw new v.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let H=JSON.parse(X.readFileSync(G,"utf8"));if(typeof H.projectId!=="string"&&typeof H.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:H.projectId,teamId:H.orgId}}function WG(z,G){let H=(0,J.getUserDataDir)();if(!H)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Q=U.join(H,"com.vercel.token",`${G}.json`),K=JSON.stringify(z);X.mkdirSync(U.dirname(Q),{mode:504,recursive:!0}),X.writeFileSync(Q,K),X.chmodSync(Q,432);return}function XG(z){let G=(0,J.getUserDataDir)();if(!G)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=U.join(G,"com.vercel.token",`${z}.json`);if(!X.existsSync(H))return null;let Q=JSON.parse(X.readFileSync(H,"utf8"));return M(Q),Q}function YG(z){let G=z.split(".");if(G.length!==3)throw new v.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let H=G[1].replace(/-/g,"+").replace(/_/g,"/"),Q=H.padEnd(H.length+(4-H.length%4)%4,"=");return JSON.parse(Buffer.from(Q,"base64").toString("utf8"))}function ZG(z,G=0){return z.exp*1000<Date.now()+G}});
|
|
2
2
|
export{R as a,f as b};
|