@cortexkit/opencode-openai-auth 1.11.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +8 -8
- package/dist/{codex-request-DFeGDzpN.d.ts → codex-request-Bu2sjxQn.d.ts} +1 -0
- package/dist/{index-4rzatybc.js → index-0bh5fs56.js} +1 -1
- package/dist/{index-d5v2rn54.js → index-2ccfywax.js} +1 -1
- package/dist/index-2g95z7kb.js +64 -0
- package/dist/index-4s50rsec.js +8 -0
- package/dist/index-7s8g79dd.js +91 -0
- package/dist/{index-2p3st53v.js → index-cs0tey1r.js} +2 -2
- package/dist/index-khqwa7g2.js +76 -0
- package/dist/{index-dp68014q.js → index-p8v28mh9.js} +2 -2
- package/dist/{index-smzgsx6x.js → index-r8y79mzp.js} +1 -1
- package/dist/{index-7at0fc03.js → index-rhe4jm5t.js} +2 -2
- package/dist/{index-bxxjwt4q.js → index-th0bzvpn.js} +2 -2
- package/dist/{index-4daebegf.js → index-tzrf3ax2.js} +1 -1
- package/dist/{index-afpxnan1.js → index-zmerz2yv.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-wgntcjq1.js → token-2qht8n50.js} +1 -1
- package/dist/token-util-20g3fwxd.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +3 -3
- package/package.json +4 -3
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +89 -31
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +19 -13
- package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +49 -607
- package/src/tui-compiled/raw/shared/723b00f96290a097-lock-record.js +55 -0
- package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +9 -1
- package/src/tui-compiled/raw/shared/a75d0d866c227b3f-index.tsx +681 -0
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +33 -2
- package/src/tui-compiled/raw/shared/c97089ed4243981c-host.js +11 -7
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +148 -92
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +1 -1
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +89 -31
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +19 -13
- package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +36 -674
- package/src/tui-compiled/runtime/shared/723b00f96290a097-lock-record.js +55 -0
- package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +9 -1
- package/src/tui-compiled/runtime/shared/a75d0d866c227b3f-index.js +678 -0
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +33 -2
- package/src/tui-compiled/runtime/shared/c97089ed4243981c-host.js +11 -7
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +148 -92
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +1 -1
- package/dist/index-0kpq9310.js +0 -76
- package/dist/index-3x7q1rj8.js +0 -8
- package/dist/index-cy6km6cz.js +0 -64
- package/dist/index-h2z9jb3g.js +0 -91
- package/dist/token-util-e49kkftr.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 u extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(
|
|
2
|
+
import{c as e0}from"./index-2ccfywax.js";import{Ha as m0,Ia as g,Ja as F,Ka as f,Tb as o0,jc as t0,ta as r0,ua as v,va as j0,wa as d,wc as J1,xa as p0}from"./index-khqwa7g2.js";import{Nd as S,Od as l,Qd as N0,Sd as p,Td as _,Ud as i0,Vd as m,Wd as I0,se as s0}from"./index-7s8g79dd.js";import"./index-4s50rsec.js";import"./index-cs0tey1r.js";import"./index-th0bzvpn.js";import{Rf as Y0,Xf as X0,Zf as W0,ag as n0}from"./index-rhe4jm5t.js";import"./index-p8v28mh9.js";import"./index-r8y79mzp.js";import"./index-tzrf3ax2.js";import{spawn as Z1}from"node:child_process";var k=4096,$1=1048576;class D0{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 Z=(this.start+this.length)%k,$=Math.min(z.length,k-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,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 Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var w={run(z,J,Z={}){return new Promise(($)=>{let G=performance.now(),Q=Z.timeoutMs??15000,K=new D0,X=[],W=0,b=!1,D=!1,Y=!1,B;try{B=Z1(z,[...J],{env:Z.env??process.env,windowsHide:!0,windowsVerbatimArguments:Z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{$({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-G});return}let q=Q>0?setTimeout(()=>{Y=!0,B.kill("SIGTERM")},Q):void 0;B.stdout?.on("data",(U)=>{let C=$1-W,j=Math.min(C,U.length);if(j>0)X.push(U.subarray(0,j)),W+=j;if(U.length>C)b=!0,B.kill("SIGTERM")}),B.stderr?.on("data",(U)=>K.push(U));let V=!1,H=(U,C)=>{if(V)return;if(V=!0,q)clearTimeout(q);$({exitCode:D?1:b?1:U??1,stdout:Buffer.concat(X,W).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...D?{spawnError:!0}:{},signal:C??null,timedOut:Y,durationMs:performance.now()-G})};B.once("error",()=>{if(D=!0,B.pid===void 0)H(null,null)}),B.once("close",(U,C)=>H(U,C))})}};function c(z,J,Z,$,G,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:G,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:G,timeoutMs:Q})}var G1="Pi install failed; run pi install after checking your npm connection.";function Q1(z){let J=Buffer.from(z,"utf8");if(J.length<=k)return z;let Z=J.length-k;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function K1(z){let J=z.indexOf(`
|
|
3
|
+
`);return J<0?"":z.slice(J+1)}class u extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(G1);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?K1(z.stderrTail):z.stderrTail,Z=Y0(J);this.stderrTail=Q1(typeof Z==="string"?Z:"")}}var b1={opencode:"OpenCode",pi:"Pi"},q1={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function B0({host:z,outcome:J}){return`${b1[z]}: ${q1[J]}`}var X1=new WeakMap;function V0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;X1.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as B1,constants as V1,existsSync as x1,readFileSync as U1,realpathSync as F1,statSync as H1}from"node:fs";import{mkdtemp as M1,rm as O1}from"node:fs/promises";import{tmpdir as C1}from"node:os";import{join as R1}from"node:path";import{parse as k1}from"jsonc-parser";import{homedir as W1}from"node:os";import{posix as j1,win32 as D1}from"node:path";import{fileURLToPath as Y1}from"node:url";function N(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?D1:j1,G=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??W1(),Q=z.cwd??process.cwd(),K=(D)=>$.resolve(Q,D),X=J.OPENCODE_CONFIG_DIR?.trim(),W=J.XDG_CONFIG_HOME?.trim(),b=J.PI_CODING_AGENT_DIR?.trim()||$.join(G,".pi","agent");if(b==="~")b=G;else if(/^~[/\\]/.test(b))b=$.join(G,b.slice(2));if(b.startsWith("file://"))b=Y1(b);return{env:J,platform:Z,path:$,home:G,cwd:Q,opencode:X?K(X):W?$.join(K(W),"opencode"):$.join(G,".config","opencode"),pi:K(b)}}function o(z,J){try{return H1(z)[J]()}catch{return!1}}var T={exists:x1,isFile:(z)=>o(z,"isFile"),isDirectory:(z)=>o(z,"isDirectory"),isExecutable(z){try{return B1(z,V1.X_OK),o(z,"isFile")}catch{return!1}},readText:(z)=>U1(z,"utf8"),realpath:F1};function A(z,J={}){let{env:Z,platform:$,path:G,cwd:Q}=N(J),K=J.fs??T,X=Object.entries(Z).find(([b])=>$==="win32"?b.toUpperCase()==="PATH":b==="PATH")?.[1]??"",W=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let b of X.split($==="win32"?";":":")){let D=b.trim().replace(/^"|"$/g,"");if(!D)continue;for(let Y of W){let B=G.resolve(Q,D,z+Y);if($==="win32"?K.isFile(B):K.isExecutable(B))return B}}return null}function x0(z={}){let{platform:J,home:Z,env:$,path:G}=N(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",G.join(Z,"Applications","OpenCode.app"),G.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.LOCALAPPDATA||G.join(Z,"AppData","Local");return[G.join(Q,"Programs","opencode"),G.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",G.join(Z,".local","share","applications","opencode.desktop")]}function t(z,J){let Z=J.fs??T,{path:$}=N(J);try{let G=Z.readText(z);if(G.length>65536)return z;let Q=[...G.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...G.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Q.at(-1)?.[1];if(K){let X=$.join($.dirname(z),...K.split(/[/\\]+/));if(Z.isFile(X))return Z.realpath(X)}return Z.realpath(z)}catch{return z}}function N1(z,J){let Z=J.fs??T,{path:$}=N(J),G=$.dirname(t(z,J));for(;;){try{let K=JSON.parse(Z.readText($.join(G,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(K.name))return"2";if(K.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(K.version??"")?"2":"1"}catch{}let Q=$.dirname(G);if(Q===G)return null;G=Q}}function U0(z={}){let J=A("opencode",z),Z=A("opencode2",z),$=J&&Z&&t(J,z)===t(Z,z),G=z.fs??T,{path:Q,opencode:K}=N(z),X="1";for(let b of["jsonc","json"]){let D=Q.join(K,`opencode.${b}`);if(!G.exists(D))continue;try{if(Object.hasOwn(k1(G.readText(D))??{},"plugins"))X="2"}catch{}break}let W=J?N1(J,z)??($?"2":X):null;if(Z&&W==="1"&&!$)return"ambiguous";return Z||$?"2":W??X}async function e(z,J={}){let Z=J.fs??T,{env:$,platform:G,opencode:Q,pi:K}=N(J),X=J.runner??w,W=A("opencode",J)??A("opencode2",J),b=A("pi",J),D=A("ck",J),Y=async(H)=>{if(!H)return null;let U;try{U=await M1(R1(C1(),"common-auth-setup-version-"));let C={...$,HOME:U,USERPROFILE:U,XDG_CONFIG_HOME:U,XDG_DATA_HOME:U,XDG_STATE_HOME:U,XDG_CACHE_HOME:U,OPENCODE_CONFIG_DIR:U,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:U},j=await c(X,G,H,["--version"],C,2000);return j.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(j.stdout)?.[0]??null:null}catch{return null}finally{if(U)await O1(U,{recursive:!0,force:!0}).catch(()=>{})}},B=!1;if(D&&Z.exists(z.vault.connectionFile))try{(await(J.connect??p)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),B=!0}catch{B=!1}let[q,V]=await Promise.all([Y(W),Y(b)]);return{opencode:{installed:Z.isDirectory(Q)||x0(J).some((H)=>Z.exists(H))||W!==null,executable:W,version:q,directory:Q,generation:U0(J)},pi:{installed:b!==null||Z.isDirectory(K),executable:b,version:V,directory:K},claustrum:{available:B,executable:D}}}import{setTimeout as S1}from"node:timers/promises";import{writeEnrollmentTokenFile as v1}from"@cortexkit/claustrum-client";var F0=45000,z0=new Set(["opencode","litecode","opencode2","pi"]),M0=new Set(["node","bun"]),I1=[...z0,...M0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),A1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${I1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,w1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function _1(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function H0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var T1=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"]),L1=new Set(["-e","--eval","-p","--print"]);function P1(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(L1.has($))return;if($.startsWith("-")){if(!$.includes("=")&&T1.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function O0(z){let[J,...Z]=_1(z);if(J===void 0)return null;let $=H0(J);if(z0.has($))return $;if(!M0.has($))return null;let G=P1($,Z);if(G===void 0)return null;let Q=H0(G);if(z0.has(Q))return Q;return w1.test(G)?"pi":null}class O extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.exitCode=z.exitCode,this.signal=z.signal,this.timedOut=z.timedOut,this.durationMs=z.durationMs}get refusalText(){let z=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${z} after ${Math.round(this.durationMs)} ms.`}}class P extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:O0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
|
|
4
4
|
${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
|
|
5
5
|
`)}
|
|
6
6
|
|
|
7
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function z1(z=w,J={}){let Z=(J.platform??process.platform)==="win32",$=J.selfPid??process.pid,G={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(K,q,W,b)=>{let Y=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let D=await z.run(q,W,{env:J.env,timeoutMs:b});return G={step:K,exitCode:D.exitCode,signal:D.signal??null,timedOut:D.timedOut??!1,durationMs:D.durationMs??performance.now()-Y},D}finally{if(G.exitCode===null)G.durationMs=performance.now()-Y;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let b=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",N0],x1);if(b.exitCode!==0)throw new O(G);let Y=JSON.parse(b.stdout);if(!Y||typeof Y!=="object"||!("complete"in Y)||Y.complete!==!0||!("processes"in Y))throw new O(G);let D=Y.processes,B=D===null?[]:Array.isArray(D)?D:[D],X=[];for(let V of B){if(!V||typeof V!=="object"||!("Name"in V)||typeof V.Name!=="string"||!("ProcessId"in V)||!Number.isSafeInteger(V.ProcessId)||V.ProcessId<0||!("CommandLine"in V))throw new O(G);let F=V.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(V.Name))X.push({pid:F,command:V.Name});else if(typeof V.CommandLine==="string")X.push({pid:F,command:V.CommandLine});else if(F!==$)throw new O(G)}return X}let K=await Q(Z?"tasklist":"ps",Z?"tasklist.exe":"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new O(G);let q=[];for(let b of K.stdout.split(/\r?\n/)){let Y=b.trim();if(!Y)continue;let D,B;if(Z){let X=/^"([^"]+)","(\d+)"(?:,|$)/.exec(Y);if(!X)throw new O(G);B=X[1]??"",D=Number(X[2])}else{let X=/^(\d+)\s+(.+)$/.exec(Y);if(!X){if(/^PID\s+COMMAND$/i.test(Y))continue;throw new O(G)}D=Number(X[1]),B=X[2]??""}if(!Number.isSafeInteger(D)||D<0)throw new O(G);q.push({pid:D,command:B})}if(!q.length)throw new O(G);let W=q.filter((b)=>b.pid!==$&&/^(?:node|bun)\.exe$/i.test(b.command));if(Z&&W.length&&J.inspectRuntimes!==!1){let b=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],x1);if(b.exitCode!==0)throw new O(G);let Y=JSON.parse(b.stdout||"null"),D=Y===null?[]:Array.isArray(Y)?Y:[Y],B=new Map;for(let X of D){if(!X||typeof X!=="object"||!("ProcessId"in X)||!("CommandLine"in X)||!Number.isSafeInteger(X.ProcessId))throw new O(G);if(typeof X.CommandLine==="string")B.set(Number(X.ProcessId),X.CommandLine);else if(W.some((V)=>V.pid===X.ProcessId))throw new O(G)}for(let X of W)X.command=B.get(X.pid)??""}return q}catch(K){if(K instanceof O)throw K;throw new O(G)}}function E(z=w,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&H1(G.command)!==null;return{async listRunningHosts(G){return(await z1(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await z1(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((q)=>q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(q.command)).length:0}}}}async function f(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var S0="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",N1='This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',I1=300000,M1=1000,O1=[1000,2000,4000,8000,16000,30000];function J1(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class I extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=J1(J.lastErrorCode)}}function C1(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function A1(z,J,Z,$,G){if(l())throw Error(S);let{name:Q,paths:K}=z.vault.hosts[J],q=_(K);await G();let W=await(Z.connect??p)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new I("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),b=Z.now??(()=>performance.now()),Y=Z.wait??L0;try{let D=new k1({proposedName:Q,paths:q,client:W,writeTokenFile:async(x,M)=>{await G(),await P0(x,M)}});await G();let B=await D.status();if(B.state==="approved"){H($,`Already connected as ${B.approvedName??B.proposedName}.`);return}H($,`Asking the vault to connect ${Q}…`);let X=b()+I1,V,F,U,C=0;for(;;){let x=await D.reconcile();if(x.state==="approved"){H($,`Connected ${J} to Claustrum.`);return}if(x.state==="unavailable"&&x.code===R1)throw new I(N1,{reason:"unsupported-vault",lastErrorCode:x.code});if(x.state!=="pending"&&x.state!=="busy")throw new I("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in x&&{lastErrorCode:x.code}});let M=M1;if(x.state==="busy")F="busy";else if(x.retryCode)F=x.retryCode;if(x.state==="pending"&&x.requestId){if(C=0,x.requestId!==V){if(!/^[a-zA-Z0-9_-]+$/.test(x.requestId))throw new I("Invalid enrollment request id.",{reason:"invalid-request"});V=x.requestId,H($,"Waiting for approval. In another terminal, run:"),H($,` ${C1(x.requestId,Q)}`),H($,`Enrollment files: ${q.statePath}, ${q.tokenPath}`)}}else if(x.state==="pending"&&x.retryCode){M=O1[Math.min(C,O1.length-1)]??M1,C++;let v=J1(x.retryCode);if(v!==U)U=v,H($,`The vault has not created the request yet (${v}); retrying.`)}let N=X-b();if(N<=0)break;await Y(Math.min(M,N)),await G()}if(V)throw new I(`Claustrum approval is still pending. In another terminal, run: ${C1(V,Q)} and then rerun setup.`,{reason:"approval-pending",...F!==void 0&&{lastErrorCode:F}});let j=J1(F);throw new I(`The vault never created the enrollment request (last error: ${j}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:j})}catch(D){if(D instanceof P||D instanceof O||D instanceof I)throw D;let B=D?.code;throw new I(S0,{reason:"incomplete",...typeof B==="string"&&{lastErrorCode:B}})}finally{W.close()}}var w1="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",y0=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function a(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function _1(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let Z=0;Z<z.length;Z++){let $=z[Z],G=$.indexOf("="),Q=G===-1?$:$.slice(0,G),K=y0.find((W)=>W.name===Q);if(!K)throw a($);if(!("values"in K)){if(G!==-1)throw a($);J[K.key]=!0;continue}let q;if(G!==-1)q=$.slice(G+1);else if(K.spaceForm)q=z[++Z];else throw a($);if(q===void 0||!K.values.includes(q))throw K.invalid?Error(K.invalid):a($);if(K.key==="hosts")J.hosts.push(q);else J.opencode=q}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function T1(z,J){let Z=new Set(J);for(;;){let $=await g(z,[...["opencode","pi"].map((G)=>({value:G,label:`[${Z.has(G)?"x":" "}] ${G==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(G)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if($===null)return null;if($==="done")return[...Z];if(Z.has($))Z.delete($);else Z.add($)}}import{domainToUnicode as l0}from"node:url";import{applyEdits as Z1,createScanner as a0,findNodeAtLocation as i0,modify as P1,parse as s0,parseTree as r0}from"jsonc-parser";import{randomUUID as v0}from"node:crypto";import{mkdir as E0,open as f0,rename as g0,stat as m0,unlink as d0}from"node:fs/promises";import{basename as h0,dirname as c0,join as u0}from"node:path";import{setTimeout as p0}from"node:timers/promises";async function L1(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=c0(z);await E0(G,{recursive:!0});let Q;if(!$)try{Q=(await m0(z)).mode&4095}catch(W){if(W.code!=="ENOENT")throw W}let K=u0(G,`.${h0(z)}.${(Z.stageName??v0)()}.tmp`),q=!1;try{let W=await f0(K,"wx",Q??438);q=!0;try{if(await W.writeFile(J,"utf8"),Q!==void 0)await W.chmod(Q)}finally{await W.close()}let b=Z.now??(()=>performance.now()),Y=b();for(let D=0;;D++){await Z.beforeRename?.();try{await(Z.rename??g0)(K,z),q=!1;return}catch(B){let X=B.code,V=2000-(b()-Y);if(!$||!["EPERM","EBUSY","EACCES"].includes(X??"")||V<=0||D>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??p0)(Math.min(V,25*2**Math.min(D,2)))}}}finally{if(q)await d0(K).catch(()=>{})}}function y1(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function $1(z){let J=y1(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function n0(z,J){let Z=new URL(z);if(/%2f/i.test(Z.pathname)||J&&/%5c/i.test(Z.pathname))throw Error("Encoded path separators are not valid in a file URL.");let $=decodeURIComponent(Z.pathname);if(!J){if(Z.hostname)throw Error("A POSIX file URL must be local.");return $}let G=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${l0(Z.hostname)}${G}`;if(!/^\\[a-z]:/i.test(G))throw Error("A Windows file URL must have an absolute drive path.");return G.slice(1)}function o0(z,J,Z){let{path:$,platform:G}=k(Z);try{let Q=/^file:\/\//i.test(z)?n0(z,G==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let K=JSON.parse((Z.fs??T).readText($.join(Q,"package.json")));return K&&typeof K==="object"&&"name"in K&&typeof K.name==="string"?K.name:null}catch{return null}}function v1(z,J){let Z=[],$=s0(z,Z,{allowTrailingComma:!0});if(Z.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");if($[J]!==void 0&&!Array.isArray($[J]))throw Error(`OpenCode ${J} must be an array.`);return $}function S1(z,J,Z){let $=r0(z),G=$&&i0($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let q=[{offset:K.offset,length:K.length,content:""}],W=(b,Y)=>{let D=a0(z.slice(b,Y),!0);if(D.scan(),z[b+D.getTokenOffset()]===",")q.push({offset:b+D.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let b=Q[Z-1];if(b)W(b.offset+b.length,K.offset);W(K.offset+K.length,G.offset+G.length-1)}else W(K.offset+K.length,Q[Z+1]?.offset??K.offset+K.length);return Z1(z,q)}function E1(z,J,Z,$){let G=v1(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
|
|
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
8
|
`)?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`}},K=z,
|
|
11
|
-
`,V=
|
|
12
|
-
${j.content}`);if(!$.enrollOnly&&b.includes("pi"))
|
|
13
|
-
ck auth grant --principal enrolled:${b} --selector-kind category --selector ${
|
|
14
|
-
${
|
|
10
|
+
`}},K=z,X=G[J],W=Array.isArray(X)?[...X]:[],b=W.flatMap((B,q)=>G0(B)===Z?[q]:[]),D=`${Z}@${$}`;if(!b.length)K=$0(K,v0(K,X===void 0?[J]:[J,W.length],X===void 0?[D]:D,Q));else{let B=b[0],q=W[B],V=Array.isArray(q)?[D,...q.slice(1)]:q&&typeof q==="object"?{...q,package:D}:D;if(JSON.stringify(q)!==JSON.stringify(V))K=$0(K,v0(K,[J,B],V,Q));for(let H of b.slice(1).reverse())K=y0(K,J,H)}let Y=J==="plugin"?"plugins":"plugin";if(Array.isArray(G[Y])){let B=G[Y];for(let q=B.length-1;q>=0;q--)if(G0(B[q])===Z)K=y0(K,Y,q)}return K}function Q0(z,J,Z={}){let $=Z.fs??T,{path:G,opencode:Q}=N(Z),K=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((W)=>{let b=G.join(Q,`${W}.jsonc`),D=G.join(Q,`${W}.json`),Y=$.exists(b)?b:$.exists(D)?D:b,B=$.exists(Y),q=B?$.readText(Y):`${JSON.stringify({$schema:`https://opencode.ai/${W==="tui"?"tui":"config"}.json`},null,2)}
|
|
11
|
+
`,V=f0(q,K),H=[],U=[];for(let j of["plugin","plugins"]){if(!Array.isArray(V[j]))continue;for(let M of V[j]){let x=E0(M);if(x===null)continue;if(e1(x,Y,Z)===z.packages.opencode)H.push(JSON.stringify(M));else if(G0(M)===z.packages.opencode)U.push(JSON.stringify(M))}}if(H.length>0)return{path:Y,content:q,changed:!1,existingLocalEntries:H,existingNpmEntries:U};let C=g0(q,K,z.packages.opencode,z.version);return{path:Y,content:C,changed:!B||C!==q}})}async function K0(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await S0(Z.path,Z.content,{beforeRename:J})}}async function b0(z,J,Z={}){let{platform:$,env:G}=N(Z),Q=await c(Z.runner??w,$,J,["install",`npm:${z.packages.pi}@${z.version}`],G);if(Q.exitCode!==0||Q.timedOut)throw new u({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var d0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function z2(z){for(let J of Object.values(z.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(J))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(z.version))throw Error("Setup requires a concrete package version.");for(let J of Object.values(z.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(J.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function J2(z,J,Z){let $=[];for(let G of J){let Q=Z.get(G)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:X}=z.vault.hosts[G],W=await m(_(X),K).catch(()=>"unreadable");if(W==="vault"||W==="host")Q="enrolled";else if(W==="local")Q="not-enrolled"}$.push({host:G,outcome:Q})}return $}async function q0(z,J=[],Z={}){let $=L0(J);if(l())throw Error(S);z2(z);let G=Z.terminal??m0(),Q=await e(z,Z);F(G,`${z.displayName} setup`);for(let[j,M]of[["OpenCode",Q.opencode],["Pi",Q.pi]])F(G,`${j}: ${M.installed?`found (version ${M.version??"unknown"})`:"not found"} — ${M.directory}`);F(G,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)F(G,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let X=["opencode","pi"].filter((j)=>Q[j].installed&&!(j==="pi"&&K));if($.hosts.some((j)=>!X.includes(j)))throw Error(T0);let W=$.yes||$.dryRun&&!g(G);if(!W&&!g(G))throw Error("Setup requires a TTY or --yes.");let b=$.hosts.length?X.filter((j)=>$.hosts.includes(j)):W?X:await P0(G,X)??[],D=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(b.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(W||!g(G))throw Error(d0);let j=await f(G,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(j===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};D=j}if(!b.length)return F(G,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:b,dryRun:$.dryRun,mode:"local",detection:Q};let{env:Y,platform:B}=N(Z),q=Z.fence??y(Z.runner??w,{platform:B}),V=async()=>{try{await E(q,Y)}catch(j){if(j instanceof O)F(G,j.refusalText);throw j}};if(F(G,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let j=q.previewRunningHosts?await q.previewRunningHosts(Y):{hosts:await q.listRunningHosts(Y),uncheckedRuntimes:0},M=j.hosts;if(j.uncheckedRuntimes>0)F(G,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let x=new Set(new P(M).activeHosts.map((R)=>R.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let R of x)F(G,`${R} is running; setup will ask you to quit it.`)}catch(j){if(F(G,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),j instanceof O)F(G,j.refusalText)}else await V();if(($.claustrum||$.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let H=$.claustrum||$.enrollOnly;if(!H&&!$.login&&!$.noClaustrum&&!W&&Q.claustrum.available&&g(G)){let j=await f(G,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(j===null)return F(G,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};H=j===!0}let U=H?"claustrum":"local",C=!$.enrollOnly&&b.includes("opencode")?Q0(z,D,Z):[];for(let j of C){for(let x of j.existingLocalEntries??[])F(G,`OpenCode: already registered from ${x} in ${j.path}.`);let M=[...j.existingLocalEntries??[],...j.existingNpmEntries??[]];if(M.length>1)F(G,`Warning: ${z.displayName} may load twice in ${j.path}: ${M.join(", ")}. Entries were left unchanged.`)}if($.dryRun){F(G,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let j of b){if(z.beforeSignIn)F(G,`Would run beforeSignIn(${j}, ${U}).`);if(H){let M=_(z.vault.hosts[j].paths);F(G,`Would Connect ${j}: write ${M.statePath} and ${M.tokenPath}; wait for ck auth enroll approve.`)}else F(G,`Would sign in locally for ${j}.`);if(!$.enrollOnly&&z.beforeRegister)F(G,`Would run beforeRegister(${j}, ${U}).`)}for(let j of C)F(G,`${j.changed?"Would write":"Unchanged"} ${j.path}:
|
|
12
|
+
${j.content}`);if(!$.enrollOnly&&b.includes("pi"))F(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let j of b)F(G,`Would migrate ${j} using the plugin callback (provider-specific writes).`)}else{let j={opencodeGeneration:D,mode:U,hosts:Object.freeze([...b]),piAgentDir:Q.pi.directory},M=new Map;try{for(let x of b){if(await V(),await z.beforeSignIn?.(x,j),await V(),H){M.set(x,"unknown");try{await _0(z,x,Z,G,V)}catch(R){if(R instanceof I)M.set(x,"not-enrolled");throw R}M.set(x,"enrolled")}else await z.signInLocal(x,j);if(await V(),$.enrollOnly)continue;if(await z.beforeRegister?.(x,U,j),await V(),x==="opencode")await K0(C,V);else await b0(z,Q.pi.executable,Z);await V(),await z.migrate?.(x,j)}}catch(x){if(M.size===0)throw x;try{let R=await J2(z,b,M);V0(x,R);for(let h of R)F(G,B0(h))}catch{}throw x}}if(F(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${b.join(", ")} (${U}).`),$.enrollOnly)F(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(G,`Next: ${b.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:b,dryRun:$.dryRun,mode:U,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.13.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.43.0","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.1.0","@opencode/plugin":"2.2.5"},dependencies:{"@cortexkit/claustrum-client":"^0.17.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.7.0","@opentui/solid":">=0.7.0",ai:"^7.0.159","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as b2}from"node:path";import{resolveClaustrumConnectionPath as q2}from"@cortexkit/claustrum-client";var h0={name:"@cortexkit/pi-openai-auth",version:"1.13.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.43.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.17.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as i}from"node:fs";import{homedir as s}from"node:os";import{join as r,resolve as c0}from"node:path";import{fileURLToPath as G2}from"node:url";var u0=new Set;function Q2(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return r(s(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return s();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return r(s(),z.slice(2));return z.startsWith("file://")?G2(z):z}function l0(z=Q2()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=r(z,X0),$=r(s(),".pi","agent",X0),G=(K)=>{let X=W0(K),W=p0(d(X),"pi");return i(K)||i(X)||i(W.tokenPath)||i(W.statePath)};if(c0(Z)===c0($)||G(Z)||!G($))return Z;let Q=`${Z}\x00${$}`;if(!u0.has(Q))u0.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${$} (${Z} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return $}function K2(z=l0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||W0(z)}function a0(z=l0()){return{configPath:z,statePath:K2(z)}}function z1(z={}){let J=z.print??console.log,Z=z.fence??y(),$={opencode:{stateDir:d(o0().statePath),host:"opencode"},pi:{stateDir:d(a0().statePath),host:"pi"}},G=async(Q)=>{let K=await m(_($[Q]),v(Q));if(K==="host")throw Error(S);if(K!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:h0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:q2(),hosts:{opencode:{name:v("opencode"),displayName:j0("opencode"),paths:$.opencode},pi:{name:v("pi"),displayName:j0("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(await m(_($[Q]),v(Q))==="host")throw Error(S);if(K==="claustrum"){let X=await i0(_($[Q]),v(Q)),W=X.state==="approved"?X.approvedName:void 0,b=W??("proposedName"in X?X.proposedName:v(Q));if(!W)J("The enrollment state does not record an approved name. The command below uses the proposed name; if the vault approved a different name, substitute it.");if(J(`Allow this host to read OpenAI accounts with:
|
|
13
|
+
ck auth grant --principal enrolled:${b} --selector-kind category --selector ${r0.category} --operation read`),Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await G(Q)},async signInLocal(Q,K){if(await G(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let U=b2(A("opencode2",z.io)??A("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${U} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(K.opencodeGeneration==="2")return;if(t0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let X=e0(),W={path:{id:"openai"}};if(await X.get(W)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let b=z.beginLogin??s0,D=new AbortController,Y=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),B={version:L.version,signal:D.signal},q,V=!Y;try{q=await b({...B,headless:Y})}catch(U){if(Y)throw U;V=!1,J("Browser callback unavailable; using device-code sign-in."),q=await b({version:L.version,headless:!0})}if(V){if(!(z.openBrowser??n0)(q.url))D.abort(),await q.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),q=await b({version:L.version,headless:!0})}J(`${q.url}
|
|
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}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{rg as Z,tg as W}from"./index-tzrf3ax2.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};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ic as X,kc as V}from"./index-khqwa7g2.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
|
|
2
2
|
`,{mode:W??384}),await $(B,W??384),await L(B,b)}catch(Y){throw await T(B,{force:!0}).catch(()=>{}),Y}return z.set(q,R(j.body)),!0},async all(){let j=await Q(b);if(!j||Object.keys(j).length===0)return{[x]:!0};return j}}}
|
|
3
3
|
export{_ as c};
|