@cortexkit/opencode-anthropic-auth 2.0.1 → 2.0.2
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/cli.js +84 -84
- package/dist/{index-52r2e1h9.js → index-1tbpt45x.js} +1 -1
- package/dist/index-227rsmfv.js +42 -0
- package/dist/{index-zdgceztz.js → index-74r84r5f.js} +1 -1
- package/dist/{index-p4wvcwhh.js → index-fn0zqnnw.js} +1 -1
- package/dist/index-j0wsgy54.js +449 -0
- package/dist/{index-04syas8a.js → index-jc8p0tkv.js} +1 -1
- package/dist/{index-3xqv3rw3.js → index-mge0rw54.js} +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/transform.d.ts +17 -2
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/adapter.d.ts +3 -2
- package/dist/v2/server.js +4 -4
- package/dist/v2/tui.js +1 -1
- package/package.json +5 -5
- package/dist/index-ynq181e8.js +0 -42
- package/dist/index-yxtdke11.js +0 -449
package/dist/cli.js
CHANGED
|
@@ -1,109 +1,109 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as k1,B as U9,C as q9,D as L9,E as f9,u as l0,v as X1,w as C9,x as E0,y as G2,z as v0}from"./index-b3mxpp4w.js";import{$ as o0,Aa as w9,Bd as d0,Cd as Y2,Dd as A1,Ed as L2,Fd as b9,Jb as F2,Pd as E1,Qd as T3,Wb as P9,Xb as Z2,_ as F1,aa as H3,ba as R1,fe as g9,he as h9,id as f1,jd as K2,kd as T9,md as N0,qa as i1,qd as j2,ra as a1,rb as k9,sa as S3,ta as z2,wd as x3,xa as x9,xb as M2,yb as D2}from"./index-yxtdke11.js";import"./index-p4wvcwhh.js";import{Se as p2,Te as p4,Ue as j1}from"./index-3xqv3rw3.js";var u3=p4((QJ,y2)=>{var d3={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},d4={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},u4={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?d3.up():"");if($)Z+=d3.left;return Z}};y2.exports={cursor:d3,scroll:d4,erase:u4,beep:"\x07"}});import{stdin as v8,stdout as c8}from"node:process";import{createInterface as p8}from"node:readline/promises";import{randomUUID as $4}from"node:crypto";import{constants as S1}from"node:fs";import{lstat as Z4,mkdir as J4,open as Q4}from"node:fs/promises";import{homedir as z4}from"node:os";import{isAbsolute as U2,join as h3}from"node:path";import{types as y3}from"node:util";import{readFile as t7}from"node:fs/promises";import{appendFileSync as a9,chmodSync as n9,existsSync as $3,renameSync as V$,statSync as s9}from"node:fs";import{open as o9}from"node:fs/promises";import{dirname as r9,resolve as t9}from"node:path";import{randomUUID as y9}from"node:crypto";import{lstat as j$,readFile as H$,rename as m9,unlink as W$}from"node:fs/promises";import{dirname as q0,resolve as t}from"node:path";var A=process.platform==="win32",X$=new Set;function t1($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var K$;function x0(){return K$??=import("./index-zdgceztz.js"),K$}class l extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let Q=J;super(`Private file refused at ${Z}: ${$} (${Q?.reason??Q?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=t1(Q),this.win32Code=Q?.win32Code,this.reason=Q?.reason}}async function r($,Z,J){try{return await J()}catch(Q){if(Q instanceof l)throw Q;throw new l($,Z,Q)}}var v9;async function H0($,Z){$=t($),Z??=v9,await r($,"safe-parent",async()=>{let J=await(await x0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await j$($);throw new l(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function n($,Z,J=!1){if($=t($),Z==="directory")return H0($);await r($,"verify",async()=>{let Q=await x0(),z=await Q.verifyOwnerOnly($),Y=!1;if(!z.ok){let{reason:G}=z.refusal;if(G==="io-error")await Q.verifyPrivatePath($,Z);if(J&&[Q.EXTRA_ACE,Q.NOT_PROTECTED,Q.NULL_DACL,Q.EMPTY_DACL].includes(G))await H0(q0($)),await Q.securePrivatePath($,Z),Y=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:G,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await Q.verifyPrivatePath($,Z),Y&&!X$.has($))X$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function z0($,Z=!1,J){$=t($),await r($,"directory",async()=>{let Q=await x0();try{return await j$($),await H0($,J)}catch(Y){if(t1(Y)!=="ENOENT")throw Y}let z=q0($);if(z===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await z0(z,!1,J);try{await Q.createOwnerOnly($,{kind:"dir"})}catch(Y){if(t1(Y)!=="EEXIST")throw Y}await H0($,J)})}async function Y0($,Z=!1){if(!A)return H$($,"utf8");return(await c9($,Z)).toString("utf8")}async function c9($,Z=!1){if(!A)return H$($);if($=t($),Z)await H0(q0($)),await n($,"file",!0);return r($,"read",async()=>(await x0()).readOwnerOnly($))}async function w0($,Z){await H0(q0(t($))),await r($,"create",async()=>{await(await x0()).createPrivateFile(t($),Z)})}async function U$($){await H0(q0(t($))),await r($,"directory-create",async()=>{await(await x0()).createOwnerOnly(t($),{kind:"dir"})})}async function e1($,Z,J={}){$=t($),Z=t(Z);let Q=J.now??(()=>performance.now()),z=Q(),Y=Math.min(z+500,J.deadline??1/0),G=[0,10,20,40,80,100],W,X=0;for(let H of G){if(Q()>=Y)break;if(H)await(J.sleep??((j)=>new Promise((U)=>setTimeout(U,j))))(Math.min(H,Math.max(0,Y-Q())));if(Q()>=Y)break;if(await J.beforeRename?.(),Q()>=Y)break;X++;try{return await(J.rename??m9)($,Z),{attempts:X,elapsedMs:Q()-z}}catch(j){W??=j;let U=j;if(!(U.win32Code!==void 0?U.win32Code===32||U.win32Code===33:["EBUSY","EPERM","EACCES"].includes(U.code??"")&&!U.reason))break}}let K=new l(Z,"rename",W??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw K.attempts=X,K.elapsedMs=Q()-z,K}async function T0($,Z,J={}){$=t($),await z0(q0($));try{await n($,"file",!0)}catch(K){if(K.code!=="ENOENT")throw K}let Q=t(J.stagePath??`${$}.${y9()}.tmp`);if(q0(Q)!==q0($))throw new l($,"stage-directory",{code:"EXDEV"});let z=!1,Y=!1,G={attempts:0,elapsedMs:0},W="stage-create",X=(K)=>{try{J.onOutcome?.({path:$,stage:K?.stage??"published",published:Y,fileDurable:Y,durabilityConfirmed:!1,attempts:K?.attempts??G.attempts,elapsedMs:K?.elapsedMs??G.elapsedMs,...K&&{code:K.code,win32Code:K.win32Code}})}catch{}};try{if(await w0(Q,Z),z=!0,W="before-rename",G=await e1(Q,$,J),z=!1,Y=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await n($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new l($,"directory-sync-unsupported",{code:"ENOTSUP"});X()}catch(K){let H=K instanceof l?K:new l($,W,K);if(H.published=Y,H.fileDurable=Y,Y)Object.assign(H,G);if(z){try{await W$(Q)}catch{H.orphanPath=Q}z=!1}throw X(H),H}finally{if(z)await W$(Q).catch(()=>{})}}var p9=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,d9=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function u9($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function g0($={}){let Z=[d9,...$.extraValuePatterns??[]].map((Y)=>new RegExp(Y.source,Y.flags.includes("g")?Y.flags:`${Y.flags}g`));function J(Y){let G=Y.toLowerCase().replace(/[-_]/g,"");return p9.test(Y)||G.includes("apikey")||G.endsWith("secret")||G.endsWith("password")||G.endsWith("token")&&!G.endsWith("tokens")||!!$.extraSecretKeys?.(G)}function Q(Y){let G=Y,W=[["name",Y.name],["message",Y.message],["stack",Y.stack]];for(let K of["code","status","cause"])if(G[K]!==void 0)W.push([K,G[K]]);let X=new Set(W.map(([K])=>K));for(let K of Object.entries(Y))if(!X.has(K[0]))W.push(K);return W}function z(Y,G,W,X=0){if(typeof Y==="string")return Z.reduce((K,H)=>K.replace(H,"***REDACTED***"),Y);if(!Y||typeof Y!=="object")return Y;if(W.has(Y))return"[Circular]";W.add(Y);try{if(Array.isArray(Y))return Y.map((j)=>z(j,G,W,X));let K=u9(Y);if(K&&X>=8)return"[Truncated]";let H=K?X+1:X;return Object.fromEntries((K?Q(Y):Object.entries(Y)).map(([j,U])=>[j,G&&J(j)?"***REDACTED***":z(U,G,W,H)]))}finally{W.delete(Y)}}return{redact:(Y)=>z(Y,!0,new WeakSet),redactStrings:(Y)=>z(Y,!1,new WeakSet)}}var q$=g0(),l9=q$.redact,i9=q$.redactStrings;var H1={error:0,warn:1,info:2,debug:3,trace:4},D$=5242880,F$=3;function Z3($){try{n9($,384)}catch{}}function e9($){try{if(!($3($)&&s9($).size>=D$))return;for(let J=F$-1;J>=1;J--)if($3(`${$}.${J}`)){let Q=`${$}.${J+1}`;V$(`${$}.${J}`,Q),Z3(Q)}let Z=`${$}.1`;V$($,Z),Z3(Z)}catch{}}async function U0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await r(Z,"log-close",()=>J.close())}async function M$($,Z){await z0(r9(Z));try{await n(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await w0(Z,"")}catch(Q){if(Q.code!=="EEXIST")throw Q;await n(Z,"file",!0)}}return $.handle=await r(Z,"log-open",()=>o9(Z,"a")),$.file=Z,$.handle}async function $7($,Z,J){Z=t9(Z);try{if($.file!==Z)await U0($);let Q=$.handle??await M$($,Z);if((await r(Z,"log-stat",()=>Q.stat())).size>=D$){await U0($);for(let Y=F$-1;Y>=0;Y--){let G=Y===0?Z:`${Z}.${Y}`,W=`${Z}.${Y+1}`;try{await n(G,"file",!0)}catch(X){if(X.code==="ENOENT")continue;throw X}try{await n(W,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X}await e1(G,W),await n(W,"file")}Q=await M$($,Z)}await r(Z,"log-append",()=>Q.appendFile(J,"utf8"))}catch(Q){throw await U0($).catch(()=>{}),Q}}function Z7($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function J7($){let Z,J,Q,z=g0(),Y,G=[],W,X=Promise.resolve(),K,H={};function j(q){let P=X.then(q);return X=P.catch((O)=>{K=O}),P}function U(q){if(A&&q.file!==Z)j(()=>U0(H)).catch(()=>{});Z=q.file,J=q.level,z=g0(q),Y=q.captureSink}function M(q){if(q===void 0||q in H1)Q=q}function D(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function B(){if(Q)return Q;let q=typeof J==="function"?J():J;if(q&&q in H1)return q;return"info"}function I(q=!0){if(W)clearTimeout(W),W=void 0;if(!G.length){if(A)return j(async()=>{if(q)await U0(H);if(K)throw K});return}let P;try{P=D()}catch{if(G=[],A&&q)return j(()=>U0(H));return}let O=G.join("");if(G=[],!P){if(A&&q)return j(()=>U0(H));return}if(A)return j(async()=>{try{await $7(H,P,O)}finally{if(q)await U0(H)}});try{if(e9(P),$3(P))Z3(P);a9(P,O,{encoding:"utf8",mode:384})}catch{}}function T(){if(!W)W=setTimeout(()=>{W=void 0;let q=I(!1);if(q instanceof Promise)q.catch(()=>{})},500)}function m(q,P,O,E){if(Z===void 0&&Y===void 0)return;try{if(H1[P]>H1[B()])return;let S=z.redactStrings(O),h;try{h=z.redact(E)}catch{h="[unserializable]"}let w=`[${new Date().toISOString()}] ${P.toUpperCase()} [${q}] ${S}`+(E===void 0?"":Z7(h))+`
|
|
3
|
-
`;try{
|
|
4
|
-
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??
|
|
5
|
-
`,"utf8"),await
|
|
6
|
-
`,{deadline:performance.now()+Math.max(0,u),beforeRename:async()=>{let
|
|
7
|
-
`,"utf8"),await
|
|
8
|
-
`;if(A)await
|
|
9
|
-
`;if(A)await
|
|
10
|
-
`)){if(
|
|
11
|
-
`;if(Buffer.byteLength(z)>M1)throw new R("invalid-state","Claustrum enrollment state is too large");if(A)return T0($,z);let Y=B7(Q,`.${N7($)}.${process.pid}.${V7()}.tmp`),G,W=!1;try{G=await E$(Y,"wx",384),W=!0,await G.writeFile(z,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await L7(Y,$),W=!1}finally{if(await G?.close().catch(()=>{}),W)await x$(Y).catch(()=>{})}}async function L1($,Z){let J=await k0($.tokenPath),Q=J===void 0?void 0:M3(J),z=await k0($.statePath),Y=z===void 0?void 0:V3(z);if(Q)return{state:"approved",proposedName:Y?.proposedName??Z,...Y?.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:Q.token_generation};if(!Y)return{state:"idle"};if(Y.phase==="approved")return{state:"blocked",proposedName:Y.proposedName,code:"missing_token"};return M0(Y)}async function D3($){let Z=await k0($);if(Z===void 0)throw new R("not-enrolled","Claustrum enrollment is not configured");return M3(Z)}function M0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function c$(){return new R("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class N1{#$;#J;#Z;#Y;#X;#z;#Q;constructor($){this.#Q=$.ancestorOptions??{},this.#$=$.client,this.#J=$.paths,this.#Z=$.proposedName,this.#Y=$.now??Date.now,this.#X=$.mintSecret??(()=>q7(32).toString("hex")),this.#z=$.writeTokenFile??F1}async status(){return L1(this.#J,this.#Z)}async resetTerminal(){return p$(this.#J,this.#Z)}async#G($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Y()};return await b0(this.#J.statePath,J,this.#Q),M0(J)}async reconcile(){await D1(A0(this.#J.statePath),this.#Q);let $=await V0({name:"ceremony",path:this.#J.statePath,ttlMs:w$,renew:!0});if(!$)return{state:"busy"};try{let Z=await k0(this.#J.tokenPath),J=Z===void 0?void 0:M3(Z),Q=await k0(this.#J.statePath),z=Q===void 0?void 0:V3(Q);if(z&&z.proposedName!==this.#Z)throw c$();if(J){if(!z||z.phase==="pending"){let G={version:1,phase:"approved",proposedName:z?.proposedName??this.#Z,tokenGeneration:J.token_generation,updatedAt:this.#Y()};await b0(this.#J.statePath,G,this.#Q),z=G}return{state:"approved",proposedName:z.proposedName,...z.phase==="approved"&&z.approvedName!==void 0&&{approvedName:z.approvedName},tokenGeneration:J.token_generation}}if(z?.phase==="approved"){let G={version:1,phase:"blocked",proposedName:z.proposedName,errorCode:"missing_token",updatedAt:this.#Y()};return await b0(this.#J.statePath,G,this.#Q),M0(G)}if(z&&z.phase!=="pending")return M0(z);if(!z){let G=this.#Y();if(z={version:1,phase:"pending",proposedName:this.#Z,requestSecret:this.#X(),createdAt:G,updatedAt:G},!U3.test(z.requestSecret))throw new R("invalid-state","invalid minted Claustrum enrollment secret");await b0(this.#J.statePath,z,this.#Q)}if(!z.requestId)try{let G=U7("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:G});z={...z,requestId:W.requestId,updatedAt:this.#Y()},await b0(this.#J.statePath,z,this.#Q)}catch(G){let W=j3(G);if(!W)throw G;if(W.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:W.code};return this.#G(z,W.code)}let Y=z.requestId;if(!Y)return M0(z);try{let G=await this.#$.enrollPoll({requestId:Y,requestSecret:z.requestSecret});if(G.status==="pending")return M0(z);if(G.status==="denied"){let X={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#Y()};return await b0(this.#J.statePath,X,this.#Q),M0(X)}await D1(A0(this.#J.tokenPath),this.#Q),await v$(A0(this.#J.tokenPath),this.#Q),await this.#z(this.#J.tokenPath,{token:G.token,token_generation:G.tokenGeneration});let W={version:1,phase:"approved",proposedName:z.proposedName,approvedName:G.name,tokenGeneration:G.tokenGeneration,updatedAt:this.#Y()};return await b0(this.#J.statePath,W,this.#Q),M0(W)}catch(G){let W=j3(G);if(!W)throw G;if(W.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:Y,retryCode:W.code};return this.#G(z,W.code)}}finally{await $.release()}}}async function p$($,Z){await D1(A0($.statePath));let J=await V0({name:"ceremony",path:$.statePath,ttlMs:w$,renew:!0});if(!J)return"busy";try{if(await k0($.tokenPath)!==void 0)return"refused-approved";let Q=await k0($.statePath);if(Q===void 0)return"idle";let z=V3(Q);if(z.proposedName!==Z)throw c$();if(z.phase==="pending")return"refused-pending";return await J.assertOwned(),await x$($.statePath),"reset"}finally{await J.release()}}var F3="claustrum-tombstone:v1:";function d$($,Z){return Z!==void 0&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function C7($,Z){if(Z===void 0)return"reauthorize-failed";if(Z.credentialId!==$.credentialId)return"credential-changed";if(Z.accountIdentity!==$.accountIdentity)return"account-changed";if(Z.recordVersion===$.recordVersion)return"version-unchanged";return"rotated"}var u$=n0("claustrum");function B3($,Z,J,Q=u$){let z=d$(Z,J);return Q.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:z,reason:C7(Z,J)}),z}var N3=300000;function L3(){return new R("invalid-material","Claustrum returned invalid credential material")}function R7($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw L3()}if(!J||typeof J!=="object")throw L3();let Q=J,z=Q.access_token??Q.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(F3))throw L3();return Z}function b7($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}class B1{#$;#J;#Z;#Y;#X;#z;#Q;#G=new WeakMap;#H=new WeakMap;#W=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#J=$.readToken;else if(Z)this.#J=()=>D3(Z);else throw new R("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#Y=$.family,this.#X=$.parseIdentity,this.#z=$.requireAssertion??!1,this.#Z=$.now??Date.now,this.#Q=$.logger??u$}#K($){if(this.#W)throw new R("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#j($){this.#K($);let Z=await this.#J();if(this.#K($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new R("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#U($,Z){this.#K(Z);let J,Q;try{let z=$();J=Z?await Promise.race([z,new Promise((Y,G)=>{let W=()=>G(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),Q=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await z}catch(z){if(this.#K(Z),z instanceof o0)throw z;throw new R("unavailable","Claustrum scoped operation unavailable")}finally{Q?.()}return this.#K(Z),J}async discover($){let Z=await this.#j($),J=await this.#U(()=>this.#$.listScoped(Z),$),Q=[],z=[],Y=new Map;for(let W of J.rows){let X=b7(W,this.#Y);if(!X)continue;z.push({row:W,type:X}),Y.set(W.id,(Y.get(W.id)??0)+1)}let G=[];for(let{row:W,type:X}of z){let K;if(!W.id.trim())K="empty credential id";else if((Y.get(W.id)??0)>1)K="duplicate credential id";else if(W.accountId!==void 0&&!W.accountId.trim())K="blank account identity";else if(!W.state.trim())K="empty state";if(K){Q.push({...W.id.trim()&&{credentialId:W.id},reason:K});continue}G.push(Object.freeze({credentialId:W.id,credentialType:X,...W.accountId!==void 0&&{accountIdentity:W.accountId},state:W.state,...W.email!==void 0&&{email:W.email},...W.orgName!==void 0&&{orgName:W.orgName}}))}for(let W of Q)this.#Q.warn("skipped malformed vault record",W);return{view:J.view,credentials:Object.freeze(G),skipped:Object.freeze(Q)}}async authorize($,Z){if(!$.credentialId)throw new R("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:J,credentialType:Q,accountIdentity:z}=$;if(this.#z&&z===void 0)throw new R("identity-unasserted","Claustrum dispatch requires a known account identity");let Y=await this.#j(Z),G=await this.#U(()=>this.#$.getScoped({credentialId:J,enrollmentToken:Y,...Q==="oauth"&&{minTtlMs:N3}}),Z);if(G.credentialId!==void 0&&G.credentialId!==J)throw new R("identity-changed","Claustrum served credential identity changed");let W=G.expiresAtMs;if(!Number.isSafeInteger(G.recordVersion)||G.recordVersion<0||W===null&&Q==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#Z()<N3))throw new R("insufficient-validity","Claustrum served credential has insufficient validity");let X=R7(G.material),K=G.accountId?.trim()?G.accountId:void 0;if(this.#z&&(G.credentialId===void 0||K===void 0))throw new R("identity-unasserted","Claustrum served credential did not assert its identity");let H=K===void 0?this.#X?.(X):void 0,j=K??H;if(z!==void 0&&j!==void 0&&j!==z)throw new R("identity-changed","Claustrum served credential identity changed");let U=j??z,D=Object.freeze(Object.defineProperty({credentialId:J,credentialType:Q,...U!==void 0&&{accountIdentity:U},accountIdentitySource:K!==void 0?"asserted":H!==void 0?"parsed":z!==void 0?"expected":"none",...z!==void 0&&{expectedAccountIdentity:z},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...K!==void 0&&{assertedAccountIdentity:K},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:W},"accessToken",{value:X,enumerable:!1}));return this.#G.set(D,Y),D}async reportFailure($,Z,J){if(Z!==401)return;this.#K();let Q=this.#G.get($);if(!Q)throw new R("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#H.get($);if(z)return z;let Y=this.#U(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:Q,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#H.set($,Y);try{await Y,this.#Q.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(G){throw this.#H.delete($),G}}close(){if(this.#W)return;this.#W=!0,this.#$.close()}}import{createHash as h7}from"node:crypto";var _0="all",A7=Object.freeze(["primary"]);function i$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function y0($,Z){return JSON.stringify([$,Z])}function O3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Q0($){return typeof $==="number"&&Number.isFinite($)}function l$($){return typeof $==="string"&&$.length>0}function G0($,Z,J){return $[Z]===void 0||J($[Z])}function k7($){return Q0($)&&$>0}function I3($){return typeof $==="string"}function _7($){if(!O3($)||!l$($.scope)||!l$($.label))return!1;switch($.kind){case"reading":return Q0($.checkedAt)&&Q0($.usedPercent)&&G0($,"resetsAt",I3)&&G0($,"windowMinutes",k7);case"retired":return Q0($.retiredAt);case"absent":return Q0($.checkedAt);default:return!1}}function f7($){if(!O3($)||!Q0($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&G0($,"remainingPercent",Q0)&&G0($,"usedPercent",Q0)&&G0($,"resetsAt",I3)&&G0($,"limit",Q0)&&G0($,"used",Q0)&&G0($,"remaining",Q0)&&G0($,"unit",I3)}function f0($){if(!O3($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!_7(J))return!1;let Q=y0(J.scope,J.label);if(Z.has(Q))return!1;Z.add(Q)}return G0($,"budget",f7)}class I1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function P1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function O1($){return typeof $==="number"&&Number.isFinite($)}function a$($){return $===void 0||typeof $==="string"&&$!==""}function n$($){return typeof $==="string"&&$!==""}function r0($,Z){return $[Z]===void 0||O1($[Z])}function P3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function E7($){return P1($)&&a$($.scope)&&n$($.label)&&O1($.usedPercent)&&P3($,"resetsAt")&&($.windowMinutes===void 0||O1($.windowMinutes)&&$.windowMinutes>0)}function S7($){return P1($)&&a$($.scope)&&n$($.label)}function x7($){if(!P1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&r0($,"remainingPercent")&&r0($,"usedPercent")&&P3($,"resetsAt")&&r0($,"limit")&&r0($,"used")&&r0($,"remaining")&&P3($,"unit")}function s$($){if(!P1($)||!O1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let Q=new Set;for(let z of Z){if(!E7(z))return!1;let Y=y0(z.scope??_0,z.label);if(Q.has(Y))return!1;Q.add(Y)}if(!J.every(S7))return!1;return $.budget===void 0||x7($.budget)}function w7($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function T7($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function t0($,Z){if($!==void 0&&!f0($))throw new I1("stored quota map is malformed");if(!s$(Z))throw new I1("quota observation is malformed");let J=$??{limits:[]},Q=Z.checkedAt,z=new Map;for(let j of J.limits)z.set(y0(j.scope,j.label),j);let Y=(j)=>{let U=z.get(j);return U===void 0||Q>=i$(U)},G=new Set;for(let j of Z.readings??[]){let U=j.scope??_0,M=y0(U,j.label);if(G.add(M),!Y(M))continue;z.set(M,{scope:U,label:j.label,kind:"reading",checkedAt:Q,usedPercent:j.usedPercent,...j.resetsAt===void 0?{}:{resetsAt:j.resetsAt},...j.windowMinutes===void 0?{}:{windowMinutes:j.windowMinutes}})}for(let j of Z.coverage??[]){let U=j.scope??_0,M=y0(U,j.label);if(G.has(M)||!Y(M))continue;let D=z.get(M);z.set(M,D===void 0||D.kind==="absent"?{scope:U,label:j.label,kind:"absent",checkedAt:Q}:{scope:U,label:j.label,kind:"retired",retiredAt:Q})}let{limits:W,budget:X,...K}=J,H=T7(J.budget,Z.budget,Q);return{...K,limits:[...z.values()].sort(w7),...H===void 0?{}:{budget:H}}}var g7=Object.freeze({validate:f0,merge:t0});function o$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function C3($,Z,J){return $.some((Q)=>o$(Q,Z,J))}function R3($,Z,J){let Q={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==J),Q]}function b3($,Z,J){return $.filter((Q)=>!Z.some((z)=>o$(Q,z,J)))}var t$="vault:";function y7($){return h7("sha256").update($).digest("hex")}function m7($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function v7($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function D0($){return[$.credentialId,...$.aliases??[]]}function e$($,Z,J={}){let Q=J.now??Date.now(),z=J.routePrefix??t$,Y=J.reservedRouteIds??new Set,G=$?.rows??[],W=[...$?.declined??[]],X=Z.skipped.length===0,K=new Set(Z.credentials.map((F)=>F.credentialId)),H=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),j=Z.skipped.some((F)=>F.credentialId===void 0),U=(F)=>!K.has(F)&&(H.has(F)||j),M=new Map;for(let F of G){if(F.accountIdentity===void 0)continue;for(let q of D0(F))if(!M.has(q))M.set(q,F.accountIdentity)}let D=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:M.get(F.credentialId),claimed:!1},P=v7(q),O=D.get(P)??[];O.push(q),D.set(P,O)}let B=new Set,I=new Set(Y),T=[],m=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),p=[...D.values()].map((F)=>F.toSorted(m)).sort((F,q)=>F[0]&&q[0]?m(F[0],q[0]):0);for(let F of p){let q=F[0]?.identity,P=F.filter((x)=>x.credential.state==="active"),O=P.length?P:F,E=O.filter((x)=>x.claimed),S=E.length?E:O,h=new Set(F.map((x)=>x.credential.credentialId)),w=G.find((x)=>!B.has(x)&&D0(x).some((J0)=>h.has(J0))&&(x.accountIdentity===void 0||x.accountIdentity===q)),k=S.find((x)=>x.credential.credentialId===w?.credentialId)??S[0];if(!k)continue;let _=k.credential,b=w??(q===void 0?void 0:G.find((x)=>!B.has(x)&&x.accountIdentity===q));if(b)B.add(b);let c=b?.routeId;if(!c||Y.has(c)){let x=`${z}${_.credentialId}${q===void 0?"":`~${y7(q).slice(0,10)}`}`;c=x;for(let J0=2;I.has(c);J0++)c=`${x}~${J0}`}I.add(c);let o=b?D0(b).filter(U):[],i=[...new Set([...F.map((x)=>x.credential.credentialId),...o])].filter((x)=>x!==_.credentialId).sort((x,J0)=>x.localeCompare(J0)),j0=J.mapAccount?.(_)??{};T.push({previousIndex:b?G.indexOf(b):1/0,row:{routeId:c,credentialId:_.credentialId,credentialType:_.credentialType,...q!==void 0&&{accountIdentity:q},...i.length&&{aliases:i},state:_.state,label:j0.label?.trim()||m7(_),..._.email!==void 0&&{email:_.email},..._.orgName!==void 0&&{orgName:_.orgName},enabled:![_.credentialId,...i].some((x)=>C3(W,x,q)),addedAt:b?.addedAt??Q,...b?.quota!==void 0&&{quota:b.quota},...!k.claimed&&q!==void 0&&{unclaimed:!0}}})}return G.forEach((F,q)=>{if(B.has(F)||!D0(F).some(U))return;if(I.has(F.routeId))return;let[P,...O]=D0(F).filter((h)=>!K.has(h));if(P===void 0)return;I.add(F.routeId);let{aliases:E,...S}=F;T.push({previousIndex:q,row:{...S,credentialId:P,...O.length&&{aliases:O},stale:!0}})}),T.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,complete:X,...!X&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:T.map((F)=>F.row),declined:W}}function A3($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function C1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function m0($){return $===void 0||typeof $==="string"}function c7($){if(!C1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!m0($.accountIdentity)||!m0($.email)||!m0($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((Z)=>typeof Z==="string"))||$.quota!==void 0&&!f0($.quota)||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return $}var p7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function r$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!C1(J)||!m0(J.credentialId)||typeof J.reason!=="string"||!p7.has(J.reason))return;Z.push(J)}return Z}function d7($){if(!C1($)||$.version!==1||!m0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!r$($.rejected))throw new R("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let Y=c7(z);if(!Y)throw new R("invalid-state","Claustrum roster file is not valid");Z.push(Y)}let J=[];for(let z of $.declined){if(!C1(z)||typeof z.credentialId!=="string"||!m0(z.accountIdentity))throw new R("invalid-state","Claustrum roster file is not valid");J.push(z)}let Q=r$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...Q&&{rejected:Q},rows:Z,declined:J}}async function F0($){let Z;try{Z=await Y0($,A)}catch(Q){if(Q.code==="ENOENT")return;throw Q}let J;try{J=JSON.parse(Z)}catch{throw new R("invalid-state","Claustrum roster file is not valid")}return d7(J)}var u7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},l7={name:"claustrum-roster",ttlMs:30000};async function e0($,Z,J={}){return W3($,u7,async(Q)=>{let z=await F0($),{next:Y,result:G}=await Z(z,{assertOwned:()=>Q.assertOwned()});if(Y)await Q.assertOwned(),await z3($,Y,{beforeRename:async()=>{await J.beforePublish?.(),await Q.assertOwned()}});return G})}function k3($,Z){return e0($,(J)=>{let Q=J?.rows.find((Y)=>Y.routeId===Z);if(!J||!Q)throw new R("route-unavailable","Claustrum route is not in the roster");let z=R3(J.declined,Q.credentialId,Q.accountIdentity);return{next:{...J,declined:z,rows:J.rows.map((Y)=>Y===Q?{...Y,enabled:!1}:Y)},result:void 0}})}function _3($,Z){return e0($,(J)=>{let Q=J?.rows.find((z)=>z.routeId===Z);if(!J||!Q)throw new R("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:b3(J.declined,D0(Q),Q.accountIdentity),rows:J.rows.map((z)=>z===Q?{...z,enabled:!0}:z)},result:void 0}})}function i7($,Z){if(!D0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&D0($).length===1)return"bind";return"refuse"}function f3($,Z){return e0($,(J)=>{let Q=J?.rows.find((W)=>W.routeId===Z.routeId),z=!J||!Q?"refuse":i7(Q,Z);if(!J||!Q||z==="refuse")return{result:!1};let Y=t0(Q.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...J,rows:J.rows.map((W)=>W===Q?{...W,...G,quota:Y}:W)},result:!0}})}async function E3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let J=await V0({...l7,path:$.path,renew:!0});if(!J){let Q=await F0($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new R("roster-busy","Claustrum account discovery is already in progress");return Q}try{let Q=await $.custody.discover($.signal);return $.signal?.throwIfAborted(),await e0($.path,async(z)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let Y=typeof $.projection==="function"?$.projection():$.projection,G=e$(z,Q,Y);return{...JSON.stringify(z)!==JSON.stringify(G)&&{next:G},result:G}})}finally{await J.release()}}class $2{#$;#J=new AbortController;#Z;#Y;#X;#z;#Q;#G;#H=!1;constructor($){this.#$=$,this.#Z=$.logger??n0("claustrum")}#W($){this.#J.signal.throwIfAborted(),$?.throwIfAborted()}async#K(){return await this.#$.isCustodyActive?.()??!0}#j($,Z){let J=J3([this.#J.signal,...Z?[Z]:[]]);return new Promise((Q,z)=>{let Y=()=>{J.signal.removeEventListener("abort",G),J.dispose()},G=()=>{Y(),z(J.signal.reason)};if(J.signal.addEventListener("abort",G,{once:!0}),$.then((W)=>{if(Y(),J.signal.aborted)z(J.signal.reason);else Q(W)},(W)=>{Y(),z(W)}),J.signal.aborted)G()})}async#U(){if(this.#W(),this.#Y)return this.#Y;if(!this.#X)this.#X=this.#$.connect().then(($)=>{if(this.#J.signal.aborted)$.close(),this.#W();return this.#Y=new B1({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z}),this.#Y}).finally(()=>{this.#X=void 0});return this.#j(this.#X)}snapshot(){return this.#Q}routingRows(){return A3(this.#Q)}refresh(){if(this.#W(),this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#K()){this.#Q=void 0,this.#Y?.close(),this.#Y=void 0;return}let $=await this.#U(),Z=await E3({path:this.#$.rosterPath,custody:$,isActive:()=>this.#K(),signal:this.#J.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#W();let J=Z?.view!==this.#Q?.view;if(this.#Q=Z,Z&&J)this.#$.onRoster?.(Z);return Z})().finally(()=>{this.#z=void 0}),this.#z}start(){if(this.#H)return;this.#W(),this.#H=!0;let $=async()=>{try{await this.refresh()}catch(J){if(!this.#J.signal.aborted)this.#$.onError?.(J)}if(this.#J.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#G=void 0,$()},Z),this.#G.unref?.()};$()}async authorize($,Z){this.#W(Z);let J=this.#Q??await this.#j(this.refresh(),Z);if(!J||!await this.#K())throw new R("not-active","Claustrum scoped custody is not active");let Q=await F0(this.#$.rosterPath);this.#W(Z);let z=J.rows.find((X)=>X.routeId===$),Y=Q?.rows.find((X)=>X.routeId===$);if(Y&&!Y.enabled)throw new R("route-declined","Claustrum route is disabled");if(!z||!Y||Y.state!=="active"||Y.credentialId!==z.credentialId||Y.accountIdentity!==z.accountIdentity)throw new R("route-unavailable","Claustrum route is disabled, removed or changed");let G=await this.#j(this.#U(),Z),W=J3([this.#J.signal,...Z?[Z]:[]]);try{return await G.authorize({credentialId:Y.credentialId,credentialType:Y.credentialType,...Y.accountIdentity!==void 0&&{accountIdentity:Y.accountIdentity}},W.signal)}finally{W.dispose()}}async reportFailure($,Z,J){if(this.#W(),!this.#Y)throw new R("no-receipt","Claustrum dispatch receipt has no active owner");await this.#Y.reportFailure($,Z,J)}async send($,Z,J){let Q=J.signal,z=await this.authorize($,Q),Y=await Z(z,Q);if(Y.status===401&&!Q?.aborted){let G;try{G=await this.authorize($,Q)}catch{}if(B3(J.site,z,G,this.#Z))await Y.body?.cancel().catch(()=>{}),z=G,Y=await Z(G,Q)}if(Y.status===401)await this.reportFailure(z,401,J.reporterSource??"direct").catch((G)=>this.#$.onError?.(G)),Promise.resolve().then(()=>this.refresh()).catch((G)=>{if(!this.#J.signal.aborted)this.#$.onError?.(G)});return Y}async decline($){this.#W(),await k3(this.#$.rosterPath,$),this.#Q=await F0(this.#$.rosterPath)}async accept($){this.#W(),await _3(this.#$.rosterPath,$),this.#Q=await F0(this.#$.rosterPath)}async recordQuota($,Z,J){this.#W();let Q=await f3(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:J.credentialId,accountIdentitySource:J.accountIdentitySource,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity},...J.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:J.expectedAccountIdentity}});if(Q)this.#Q=await F0(this.#$.rosterPath);return Q}close(){if(this.#J.signal.aborted)return;if(this.#J.abort(new R("closed","Claustrum consumer is closed")),this.#G)(this.#$.clearTimeoutImpl??clearTimeout)(this.#G);this.#G=void 0,this.#Y?.close(),this.#Q=void 0}}class W0 extends Error{code;constructor($){super(`Native vault setup: ${$}`);this.code=$;this.name="NativeVaultEnrollmentError"}}async function J2($,Z){let J={...Z.env},Q=Z.paths??Z2($,J),z=`anthropic-auth-${$}`,Y=Z.processFence,G=Z.runner,W=Z.ckBinary??"ck",X,K=Z.client;try{await Y();let H=await L1(Q,z),j=new Set(["superseded","not_found","already_consumed"]);if(H.state==="idle"||H.state==="pending"||H.state==="blocked"&&j.has(H.code)){if(!K)X=await q3({connectionFile:R1(Z.connectionFile??($==="pi"?J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0),$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:J)}),K=X;let M=K,D=new N1({paths:Q,proposedName:z,client:{enrollPropose:async(B)=>{return await Y(),M.enrollPropose(B)},enrollPoll:async(B)=>{return await Y(),M.enrollPoll(B)}},writeTokenFile:async(B,I)=>{await Y(),await F1(B,I)}});if(H.state==="blocked"){if(await Y(),await D.resetTerminal()!=="reset")throw new W0("enrollment-refused");throw new W0("enrollment-reset")}if(await Y(),H=await D.reconcile(),H.state==="pending"&&H.requestId){if(await Y(),(await G.run(W,["auth","enroll","approve","--request-id",H.requestId,"--name",z],{env:J})).exitCode!==0)throw new W0("approval-refused");await Y(),H=await D.reconcile()}}if(H.state!=="approved")throw new W0("enrollment-refused");if(await Y(),(await G.run(W,["auth","grant","--principal",`enrolled:${z}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"],{env:J})).exitCode!==0)throw new W0("permission-refused")}catch(H){if(H instanceof W0)throw H;throw new W0("enrollment-refused")}finally{X?.close()}}import{dirname as a7,join as Q2,resolve as b1}from"node:path";async function c0($,Z){let J=$==="pi"?v0(Z):E0(Z),Q=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),z=b1(Q||Q2(J,S3)),Y=b1(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(z.endsWith(S3)?Q2(a7(z),z2):`${z}.state.json`)),G=await A1(z,Y),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:G,legacyConfigPath:z,legacyStatePath:Y,hostAuthPath:$==="pi"?k1(Z):G2(Z),routingSourcePath:b1(W||x3(z)),routingDestinationPath:b1(W||x3(G.config))}}async function W2($){let Z=new Map;for(let J of $)for(let Q of[J.paths.legacyConfig,J.paths.legacyState,J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.hostAuthPath,J.routingSourcePath,J.routingDestinationPath]){let z=await Y2(Q),Y=Z.get(z);if(Y!==void 0&&Y!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(z,J.host)}}import{execFile as n7}from"node:child_process";import{promisify as s7}from"node:util";var o7=s7(n7),e={async run($,Z,J={}){try{let Q=J.env?{...process.env,...J.env}:process.env,{stdout:z,stderr:Y}=await o7($,Z,{env:Q,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof z==="string"?z:String(z),stderr:typeof Y==="string"?Y:String(Y)}}catch(Q){let z=Q;return{exitCode:typeof z?.code==="number"?z.code:1,stdout:typeof z?.stdout==="string"?z.stdout:z?.stdout!=null?String(z.stdout):"",stderr:typeof z?.stderr==="string"?z.stderr:z?.stderr!=null?String(z.stderr):String(z?.message??Q)}}}};var X2=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class L0 extends Error{code="process-inspection-failed";constructor(){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError"}}class _1 extends Error{activeHosts;constructor($){let Z=$.map((Q)=>({pid:Q.pid,command:X2.exec(Q.command)?.[1]??"host"})),J=Z.map((Q)=>` - PID ${Q.pid}: ${Q.command}`).join(`
|
|
2
|
+
import{A as S1,B as C9,C as R9,D as f9,E as p9,u as s0,v as U1,w as g9,x as x0,y as L2,z as u0}from"./index-b3mxpp4w.js";import{$ as $1,Aa as i9,Cd as a0,Dd as F2,Ed as E1,Fd as f2,Gd as y9,Kb as _2,Qd as T1,Rd as p3,Xb as T9,Yb as q2,_ as I1,aa as L3,ba as _1,ge as n9,ie as s9,jd as w1,kd as O2,ld as a9,nd as B0,qa as o1,ra as r1,rb as v9,rd as I2,sa as m3,ta as D2,xa as l9,xb as A2,xd as v3,yb as k2}from"./index-j0wsgy54.js";import"./index-fn0zqnnw.js";import{Te as $9,Ue as J8,Ve as M1}from"./index-mge0rw54.js";var r3=J8((AJ,o2)=>{var o3={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},z8={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},Y8={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?o3.up():"");if($)Z+=o3.left;return Z}};o2.exports={cursor:o3,scroll:z8,erase:Y8,beep:"\x07"}});import{stdin as $6,stdout as Z6}from"node:process";import{createInterface as J6}from"node:readline/promises";import{randomUUID as V4}from"node:crypto";import{constants as g1}from"node:fs";import{lstat as M4,mkdir as D4,open as F4}from"node:fs/promises";import{homedir as L4}from"node:os";import{isAbsolute as C2,join as u3}from"node:path";import{types as l3}from"node:util";import{readFile as U4}from"node:fs/promises";import{resolve as V$}from"node:path";var Y3=60000,o9=4*Y3,J3=new Map,V1=new Map;function z3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class M${transport;key;#$=[];#Z;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Z)return this.#Z;for(let[J,z]of V1)if($-z>=Y3)V1.delete(J);let Z=V1.get(this.key);if(Z!==void 0&&$-Z<Y3)return Promise.resolve();return V1.set(this.key,$),this.#Z=(async()=>{try{let J=await this.transport.getUsage();if(!z3(J)||!Array.isArray(J.result)||J.error!==void 0)throw Error("unavailable insula usage");this.#$=J.result.filter((z)=>z3(z)&&typeof z.provider==="string")}catch{this.#$=[]}})().finally(()=>{this.#Z=void 0}),this.#Z}current($,Z,J){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!z3(z.usage))continue;let Y=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||J-Y>=o9)continue;return{entry:z,context:{fetchedAt:Y,...typeof z.source==="string"&&{source:z.source}}}}return}}function D$($,Z){let J=JSON.stringify([V$($.connectionFile),V$(Z)]),z=J3.get(J);if(!z)z={source:new M$($,J),refs:0},J3.set(J,z);z.refs++;let Y=!1;return{source:z.source,release(){if(Y)return;if(Y=!0,--z.refs===0)J3.delete(J)}}}import{appendFileSync as G7,chmodSync as W7,existsSync as W3,renameSync as C$,statSync as X7}from"node:fs";import{open as K7}from"node:fs/promises";import{dirname as H7,resolve as j7}from"node:path";import{randomUUID as r9}from"node:crypto";import{lstat as N$,readFile as O$,rename as t9,unlink as F$}from"node:fs/promises";import{dirname as V0,resolve as e}from"node:path";var A=process.platform==="win32",L$=new Set;function Q3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var B$;function T0(){return B$??=import("./index-74r84r5f.js"),B$}class l extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let z=J;super(`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=Q3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function r($,Z,J){try{return await J()}catch(z){if(z instanceof l)throw z;throw new l($,Z,z)}}var e9;async function U0($,Z){$=e($),Z??=e9,await r($,"safe-parent",async()=>{let J=await(await T0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await N$($);throw new l(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function n($,Z,J=!1){if($=e($),Z==="directory")return U0($);await r($,"verify",async()=>{let z=await T0(),Y=await z.verifyOwnerOnly($),Q=!1;if(!Y.ok){let{reason:G}=Y.refusal;if(G==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(G))await U0(V0($)),await z.securePrivatePath($,Z),Q=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:G,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),Q&&!L$.has($))L$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function Q0($,Z=!1,J){$=e($),await r($,"directory",async()=>{let z=await T0();try{return await N$($),await U0($,J)}catch(Q){if(Q3(Q)!=="ENOENT")throw Q}let Y=V0($);if(Y===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await Q0(Y,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(Q){if(Q3(Q)!=="EEXIST")throw Q}await U0($,J)})}async function G0($,Z=!1){if(!A)return O$($,"utf8");return(await $7($,Z)).toString("utf8")}async function $7($,Z=!1){if(!A)return O$($);if($=e($),Z)await U0(V0($)),await n($,"file",!0);return r($,"read",async()=>(await T0()).readOwnerOnly($))}async function g0($,Z){await U0(V0(e($))),await r($,"create",async()=>{await(await T0()).createPrivateFile(e($),Z)})}async function I$($){await U0(V0(e($))),await r($,"directory-create",async()=>{await(await T0()).createOwnerOnly(e($),{kind:"dir"})})}async function G3($,Z,J={}){$=e($),Z=e(Z);let z=J.now??(()=>performance.now()),Y=z(),Q=Math.min(Y+500,J.deadline??1/0),G=[0,10,20,40,80,100],W,X=0;for(let j of G){if(z()>=Q)break;if(j)await(J.sleep??((H)=>new Promise((M)=>setTimeout(M,H))))(Math.min(j,Math.max(0,Q-z())));if(z()>=Q)break;if(await J.beforeRename?.(),z()>=Q)break;X++;try{return await(J.rename??t9)($,Z),{attempts:X,elapsedMs:z()-Y}}catch(H){W??=H;let M=H;if(!(M.win32Code!==void 0?M.win32Code===32||M.win32Code===33:["EBUSY","EPERM","EACCES"].includes(M.code??"")&&!M.reason))break}}let K=new l(Z,"rename",W??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw K.attempts=X,K.elapsedMs=z()-Y,K}async function h0($,Z,J={}){$=e($),await Q0(V0($));try{await n($,"file",!0)}catch(K){if(K.code!=="ENOENT")throw K}let z=e(J.stagePath??`${$}.${r9()}.tmp`);if(V0(z)!==V0($))throw new l($,"stage-directory",{code:"EXDEV"});let Y=!1,Q=!1,G={attempts:0,elapsedMs:0},W="stage-create",X=(K)=>{try{J.onOutcome?.({path:$,stage:K?.stage??"published",published:Q,fileDurable:Q,durabilityConfirmed:!1,attempts:K?.attempts??G.attempts,elapsedMs:K?.elapsedMs??G.elapsedMs,...K&&{code:K.code,win32Code:K.win32Code}})}catch{}};try{if(await g0(z,Z),Y=!0,W="before-rename",G=await G3(z,$,J),Y=!1,Q=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await n($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new l($,"directory-sync-unsupported",{code:"ENOTSUP"});X()}catch(K){let j=K instanceof l?K:new l($,W,K);if(j.published=Q,j.fileDurable=Q,Q)Object.assign(j,G);if(Y){try{await F$(z)}catch{j.orphanPath=z}Y=!1}throw X(j),j}finally{if(Y)await F$(z).catch(()=>{})}}var Z7=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,J7=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function z7($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function y0($={}){let Z=[J7,...$.extraValuePatterns??[]].map((Q)=>new RegExp(Q.source,Q.flags.includes("g")?Q.flags:`${Q.flags}g`));function J(Q){let G=Q.toLowerCase().replace(/[-_]/g,"");return Z7.test(Q)||G.includes("apikey")||G.endsWith("secret")||G.endsWith("password")||G.endsWith("token")&&!G.endsWith("tokens")||!!$.extraSecretKeys?.(G)}function z(Q){let G=Q,W=[["name",Q.name],["message",Q.message],["stack",Q.stack]];for(let K of["code","status","cause"])if(G[K]!==void 0)W.push([K,G[K]]);let X=new Set(W.map(([K])=>K));for(let K of Object.entries(Q))if(!X.has(K[0]))W.push(K);return W}function Y(Q,G,W,X=0){if(typeof Q==="string")return Z.reduce((K,j)=>K.replace(j,"***REDACTED***"),Q);if(!Q||typeof Q!=="object")return Q;if(W.has(Q))return"[Circular]";W.add(Q);try{if(Array.isArray(Q))return Q.map((H)=>Y(H,G,W,X));let K=z7(Q);if(K&&X>=8)return"[Truncated]";let j=K?X+1:X;return Object.fromEntries((K?z(Q):Object.entries(Q)).map(([H,M])=>[H,G&&J(H)?"***REDACTED***":Y(M,G,W,j)]))}finally{W.delete(Q)}}return{redact:(Q)=>Y(Q,!0,new WeakSet),redactStrings:(Q)=>Y(Q,!1,new WeakSet)}}var P$=y0(),Y7=P$.redact,Q7=P$.redactStrings;var D1={error:0,warn:1,info:2,debug:3,trace:4},b$=5242880,A$=3;function X3($){try{W7($,384)}catch{}}function U7($){try{if(!(W3($)&&X7($).size>=b$))return;for(let J=A$-1;J>=1;J--)if(W3(`${$}.${J}`)){let z=`${$}.${J+1}`;C$(`${$}.${J}`,z),X3(z)}let Z=`${$}.1`;C$($,Z),X3(Z)}catch{}}async function q0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await r(Z,"log-close",()=>J.close())}async function R$($,Z){await Q0(H7(Z));try{await n(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await g0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await n(Z,"file",!0)}}return $.handle=await r(Z,"log-open",()=>K7(Z,"a")),$.file=Z,$.handle}async function q7($,Z,J){Z=j7(Z);try{if($.file!==Z)await q0($);let z=$.handle??await R$($,Z);if((await r(Z,"log-stat",()=>z.stat())).size>=b$){await q0($);for(let Q=A$-1;Q>=0;Q--){let G=Q===0?Z:`${Z}.${Q}`,W=`${Z}.${Q+1}`;try{await n(G,"file",!0)}catch(X){if(X.code==="ENOENT")continue;throw X}try{await n(W,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X}await G3(G,W),await n(W,"file")}z=await R$($,Z)}await r(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await q0($).catch(()=>{}),z}}function V7($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function M7($){let Z,J,z,Y=y0(),Q,G=[],W,X=Promise.resolve(),K,j={};function H(U){let P=X.then(U);return X=P.catch((I)=>{K=I}),P}function M(U){if(A&&U.file!==Z)H(()=>q0(j)).catch(()=>{});Z=U.file,J=U.level,Y=y0(U),Q=U.captureSink}function D(U){if(U===void 0||U in D1)z=U}function q(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function B(){if(z)return z;let U=typeof J==="function"?J():J;if(U&&U in D1)return U;return"info"}function N(U=!0){if(W)clearTimeout(W),W=void 0;if(!G.length){if(A)return H(async()=>{if(U)await q0(j);if(K)throw K});return}let P;try{P=q()}catch{if(G=[],A&&U)return H(()=>q0(j));return}let I=G.join("");if(G=[],!P){if(A&&U)return H(()=>q0(j));return}if(A)return H(async()=>{try{await q7(j,P,I)}finally{if(U)await q0(j)}});try{if(U7(P),W3(P))X3(P);G7(P,I,{encoding:"utf8",mode:384})}catch{}}function x(){if(!W)W=setTimeout(()=>{W=void 0;let U=N(!1);if(U instanceof Promise)U.catch(()=>{})},500)}function m(U,P,I,E){if(Z===void 0&&Q===void 0)return;try{if(D1[P]>D1[B()])return;let S=Y.redactStrings(I),h;try{h=Y.redact(E)}catch{h="[unserializable]"}let T=`[${new Date().toISOString()}] ${P.toUpperCase()} [${U}] ${S}`+(E===void 0?"":V7(h))+`
|
|
3
|
+
`;try{Q?.({channel:U,level:P,message:S,data:h})}catch{}if(Z===void 0)return;if(G.push(T),G.length>=50){let k=N(!1);if(k instanceof Promise)k.catch(()=>{})}else x()}catch{}}function p(U){return{error:(P,I)=>m(U,"error",P,I),warn:(P,I)=>m(U,"warn",P,I),info:(P,I)=>m(U,"info",P,I),debug:(P,I)=>m(U,"debug",P,I),trace:(P,I)=>m(U,"trace",P,I)}}function F(){if(A)H(()=>q0(j)).catch(()=>{});if(K=void 0,G=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,Y=y0(),Q=void 0}if($)M($);return{configure:M,createLogger:p,setLogLevel:D,flushLogs:N,reset:F}}var D7=M7();function t0($){return D7.createLogger($)}function K3($){let Z=new AbortController,J=[],z=!1,Y=()=>{if(z)return;z=!0;for(let{source:W,listener:X}of J)W.removeEventListener("abort",X);J.length=0},Q=(W)=>{if(z||Z.signal.aborted)return;Z.abort(W),Y()},G=$.find((W)=>W.aborted);if(G)return Z.abort(G.reason),{signal:Z.signal,dispose:Y};for(let W of $){if(Z.signal.aborted)break;let X=()=>Q(W.reason);if(J.push({source:W,listener:X}),W.addEventListener("abort",X,{once:!0}),W.aborted)Q(W.reason)}return{signal:Z.signal,dispose:Y}}import{createHash as R7,randomBytes as b7,randomUUID as A7}from"node:crypto";import{constants as y$}from"node:fs";import{chmod as k7,mkdir as _7,open as c$,readFile as D3,realpath as f7,rename as E7,stat as p$,unlink as d$}from"node:fs/promises";import{basename as S7,dirname as A0,extname as V5,isAbsolute as M5,join as x7,resolve as D5}from"node:path";import{randomUUID as k$}from"node:crypto";import{mkdir as F7,open as _$,rename as L7,rm as B7}from"node:fs/promises";import{dirname as f$}from"node:path";class H3 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function j3($,Z,J={}){await N7($,Z,J)}async function N7($,Z,J,z){if(A)return h0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??k$)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await F7(f$($),{recursive:!0});let Y=`${$}.${(J.stageName??k$)()}.tmp`,Q,G=!1;try{if(Q=await _$(Y,"wx",384),G=!0,await Q.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
5
|
+
`,"utf8"),await Q.chmod(384),J.durable)try{await Q.sync()}catch(W){throw new H3(W)}if(await Q.close(),Q=void 0,await J.beforeRename?.(),await L7(Y,$),G=!1,z?.(),J.durable){let W=await _$(f$($),"r");try{await W.sync()}catch(X){throw new H3(X)}finally{await W.close()}}}finally{if(await Q?.close().catch(()=>{}),G)await B7(Y,{force:!0}).catch(()=>{})}}var O7=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});import{randomUUID as F1}from"node:crypto";import{mkdir as E$,open as I7,readFile as S$,rename as x$,rm as L1,stat as w$,writeFile as T$}from"node:fs/promises";import{dirname as M3,join as g$}from"node:path";function U3($,Z){return`${$}.${Z}.lock`}class q3 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class m0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function V3($,Z,J){let z=performance.now();for(;;){let Y=await M0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(Y)try{return await J(Y)}finally{await Y.release()}let Q=Z.timeoutMs-(performance.now()-z);if(Q<=0)throw new q3({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((G)=>setTimeout(G,Math.min(25,Math.ceil(Q))))}}var P7=globalThis.setTimeout.bind(globalThis),C7=globalThis.clearTimeout.bind(globalThis);function h$($){let Z=$?.code;return Z==="ENOENT"||!A&&(Z==="EINVAL"||Z==="ENOTDIR")}async function M0($){let Z=U3($.path,$.name),J=g$(Z,"owner.json"),z=F1(),Y=$.now??Date.now,Q=null,G=!1,W=!1,X,K,j=new Promise((L)=>{K=L});function H(L){try{let O=$.onRenewalTimer?.(L);if(O&&(typeof O==="object"||typeof O==="function")&&"then"in O&&typeof O.then==="function")Promise.resolve(O).catch(()=>{})}catch{}}function M(){if(!Q)return;C7(Q),Q=null,H("cancelled")}function D(L,O){if(X||G)return;X=Object.freeze({reason:L,expectedOwnerId:z,...typeof O?.ownerId==="string"?{observedOwnerId:O.ownerId}:{},...typeof O?.expiresAt==="number"?{observedExpiresAt:O.expiresAt}:{}}),M(),K(X)}let q,B=null,N=`${Z}.evicting`,x=g$(N,"owner.json"),m=F1(),p=5000,F=8;async function U(){if(A)try{return JSON.parse(await G0(Z,!0))}catch(L){if(L.code!=="EISDIR"&&L.reason!=="wrong-kind")throw L;return await n(Z,"directory",!0),JSON.parse(await G0(J,!0))}try{return JSON.parse(await S$(Z,"utf8"))}catch(L){if(L.code!=="EISDIR")throw L;return JSON.parse(await S$(J,"utf8"))}}async function P(){if(A){let v=await U(),u=Number(v?.expiresAt)-Y();await h0(Z,`${JSON.stringify({ownerId:z,expiresAt:Y()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,u),beforeRename:async()=>{let q1=await U();if(q1?.ownerId!==z||!(Number(q1?.expiresAt)>Y())||!await _())throw new m0({target:$.path,name:$.name})}});return}let L=`${Z}.${F1()}.tmp`,O,C=!1;try{O=await I7(L,"wx",384),C=!0,await O.writeFile(`${JSON.stringify({ownerId:z,expiresAt:Y()+$.ttlMs})}
|
|
7
|
+
`,"utf8"),await O.chmod(384),await O.close(),O=void 0;let v=await U();if(v?.ownerId!==z||!(Number(v?.expiresAt)>Y())||!await _())throw new m0({target:$.path,name:$.name});await x$(L,Z),C=!1}finally{if(await O?.close().catch(()=>{}),C)await L1(L,{force:!0}).catch(()=>{})}}async function I(){let L=`${JSON.stringify({ownerId:z,expiresAt:Y()+$.ttlMs})}
|
|
8
|
+
`;if(A)await g0(Z,L);else await T$(Z,L,{encoding:"utf8",mode:384,flag:"wx"})}async function E(L){let O=L.code;if(O==="EEXIST"){if(A)await U();return!0}if(O==="EISDIR"){if(A)await n(Z,"directory",!0),await G0(J,!0);return!0}return!1}async function S(){if(A)await Q0(M3(Z));try{return await I(),!0}catch(L){let O=L.code;if(await E(L))return!1;if(O==="ENOENT"){if(A)await Q0(M3(Z));else await E$(M3(Z),{recursive:!0});try{return await I(),!0}catch(C){if(await E(C))return!1;throw C}}throw L}}async function h(){await new Promise((L)=>setTimeout(L,Math.floor(Math.random()*4)))}async function T(L=!0){if(L&&$.onStep)await $.onStep("lock-read-ready");let O;try{O=await U()}catch(v){if(A&&v.code!=="ENOENT")throw v}let C=Number(O?.expiresAt);if(Number.isFinite(C)&&C>Y())return{status:"live"};if(typeof O?.ownerId==="string"&&Number.isFinite(C))return{status:"stale",identity:{kind:"owner",ownerId:O.ownerId,expiresAt:C}};try{let v=await w$(Z),u=Number.isFinite(C)?C:v.mtimeMs+$.ttlMs;if(u>Y())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:v.dev,ino:v.ino,mtimeMs:v.mtimeMs,expiresAt:u}}}catch(v){if(v.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw v}}function k(L,O){if(O.status!=="stale")return!1;let C=O.identity;if(L.kind==="owner"&&C.kind==="owner")return L.ownerId===C.ownerId&&L.expiresAt===C.expiresAt;return L.kind==="stat"&&C.kind==="stat"&&L.dev===C.dev&&L.ino===C.ino&&L.mtimeMs===C.mtimeMs&&L.expiresAt===C.expiresAt}async function _(){try{return JSON.parse(await G0(x,A))?.ownerId===m}catch(L){if(A&&L.code!=="ENOENT")throw L;return!1}}async function b(L){if(A)await r(L,"remove",()=>L1(L,{recursive:!0,force:!0}));else await L1(L,{recursive:!0,force:!0}).catch(()=>{})}async function c(){if(await _())await b(N)}async function o(){if(A)await I$(N);else await E$(N);try{let L=`${JSON.stringify({ownerId:m,createdAt:Y()})}
|
|
9
|
+
`;if(A)await g0(x,L);else await T$(x,L,{encoding:"utf8",mode:384,flag:"wx"})}catch(L){if(h$(L))return!1;throw await c(),L}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function i(){let L;try{L=await w$(N)}catch(C){if(C.code==="ENOENT")return"missing";throw C}if(A)await n(N,"directory",!0);if(L.mtimeMs+p>Y())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let O=`${N}.${F1()}`;try{await x$(N,O)}catch(C){if(C.code==="ENOENT")return"missing";throw C}if($.onStep)await $.onStep("stale-marker-claimed");return await b(O),"recovered"}async function j0(L){try{if(!await o())return!1}catch(O){if(O.code==="EEXIST"){if(A){await n(N,"directory",!0);try{await G0(x,!0)}catch(C){if(C.code!=="ENOENT")throw C}}return!1}throw O}try{await L()}finally{await c()}return!0}async function w(){for(let L=0;L<F;L++){if($.onStep)await $.onStep("relinquish-read");let O;try{O=await U()}catch(C){if(A)throw C;return}if(O?.ownerId!==z)return;try{await L1(Z,{recursive:!0,force:!0});return}catch(C){if(A)throw C;await h()}}}function z0(){if(!$.renew||G||X)return;let L=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(Q=P7(()=>{Q=null;let O=(async()=>{let C=!G;try{if(!await j0(async()=>{let u=await U(),q1=Y();if(G||X){C=!1;return}if(u?.ownerId!==z){D("taken-over",u),C=!1;return}if(!(Number(u?.expiresAt)>q1)){D("expired",u),C=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(G||X){C=!1;return}if(!await _())return;if($.onStep)await $.onStep("renewal-write-fenced");if(G||X){C=!1;return}if(!await _())return;if($.onStep)await $.onStep("renewal-write-ready");if(G||X){C=!1;return}if(await P(),$.onStep)await $.onStep("renewal-write-finished");if(!await _()){D("marker-lost"),C=!1,await w();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(v){if(A&&v instanceof l)q=v,D("renewal-failed"),C=!1;try{let u=await U();if(u?.ownerId!==z)D("taken-over",u);else if(!(Number(u?.expiresAt)>Y()))D("expired",u)}catch{D("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(C&&!G&&!X)z0()}})();B=O,O.finally(()=>{if(B===O)B=null})},L),"unref"in Q)Q.unref();H("scheduled")}function q$(){try{let L=$.onContended?.();if(L&&(typeof L==="object"||typeof L==="function")&&"then"in L&&typeof L.then==="function")Promise.resolve(L).catch(()=>{})}catch{}return null}let R0=await S();if(!R0)for(let L=0;L<F;L++){if(R0=await S(),R0)break;let O=await T();if(O.status==="live")return q$();if(O.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await o()){await h();continue}}catch(C){if(C.code!=="EEXIST")throw C;if(await i()==="fresh")return null;await h();continue}try{let C=await T();if(C.status==="live")return q$();if(!k(O.identity,C))continue;if(!await _())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await _())return null;let v=await T(!1);if(!k(O.identity,v))continue;if(await b(Z),!await _())return null;if($.onStep)await $.onStep("stale-lock-removed");if(R0=await S(),!R0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await _())return await w(),R0=!1,null;break}finally{await c()}}if(!R0)return null;return z0(),{ownerId:z,whenLost:()=>j,hasLost:()=>X!==void 0,assertOwned:async()=>{if(q)throw q;let L;try{let O=await U();if(L=O,!G&&!X&&O?.ownerId===z&&Number(O?.expiresAt)>Y())return;D(O?.ownerId!==z?"taken-over":"expired",O)}catch(O){if(D("unreadable"),A&&O instanceof l)throw O}throw new m0({target:$.path,name:$.name,expectedOwnerId:z,...typeof L?.ownerId==="string"?{observedOwnerId:L.ownerId}:{},...typeof L?.expiresAt==="number"?{observedExpiresAt:L.expiresAt}:{}})},release:async()=>{if(A&&W)return;G=!0,M(),await B;for(let L=0;L<F;L++){try{let O=!1;if(await j0(async()=>{let v;try{v=await U()}catch(u){if(A&&u.code==="ENOENT"){O=!0;return}throw u}if(v?.ownerId!==z){O=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await _())return;await b(Z),O=!0})){if(A&&!O)throw new l(Z,"release-not-confirmed",{code:"EIO"});W=O;return}await i()}catch(O){if(A)throw O;return}await h()}if(A)throw new l(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}class R extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var w7=1,N1=16384,u$=30000,B3=/^[0-9a-f]{64}$/,l$=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),i$=new Set(["pending_queue_full"]);function F3($){if(!($ instanceof $1))return;if(l$.has($.code))return{code:$.code,disposition:"terminal"};if(i$.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function N3($){return L3.connect($)}function a$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function B1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function n$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function e0(){return new R("invalid-state","invalid Claustrum enrollment state")}function O3($){if(!a$($)||$.version!==w7||typeof $.proposedName!=="string"||$.proposedName.length===0)throw e0();if($.phase==="pending"){if(!B3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!B1($.createdAt)||!B1($.updatedAt))throw e0();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!n$($.tokenGeneration)||!B1($.updatedAt))throw e0();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!B1($.updatedAt))throw e0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw e0()}function I3($){if(!a$($)||!B3.test(String($.token??""))||!n$($.token_generation))throw new R("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function T7($){if(!$.isFile())throw new R("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new R("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new R("unsafe-file","Claustrum enrollment file must be owned by the current user")}function m$($){try{return JSON.parse($)}catch{throw new R("invalid-state","Claustrum enrollment file is not valid JSON")}}async function k0($){if(A)try{await Q0(A0($));let J=await G0($,!0);if(Buffer.byteLength(J)>N1)throw new R("unsafe-file","Claustrum enrollment file is too large");return m$(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await c$($,y$.O_RDONLY|y$.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new R("unsafe-file","Claustrum enrollment file could not be opened safely")}try{T7(await Z.stat());let J=Buffer.alloc(N1+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>N1)throw new R("unsafe-file","Claustrum enrollment file is too large");return m$(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function v$($,Z){let J=[];for(let z of $.split(`
|
|
10
|
+
`)){if(z.trim()===""||z.startsWith("#"))continue;let Y=z.split(":");if(Y.length!==Z||!/^[^\s:,]+$/.test(Y[0]??"")||!/^\d+$/.test(Y[2]??"")||!Number.isSafeInteger(Number(Y[2]))||Z===7&&(!/^\d+$/.test(Y[3]??"")||!Number.isSafeInteger(Number(Y[3])))||Z===4&&Y[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(Y[3]??""))return;J.push(Y)}return J}async function g7($,Z,J){try{let[z,Y]=await Promise.all([D3(J.passwdPath??"/etc/passwd","utf8"),D3(J.groupPath??"/etc/group","utf8")]),Q=v$(z,7),G=v$(Y,4);if(!Q||!G)return!1;let W=Q.filter((H)=>Number(H[2])===$),X=G.filter((H)=>Number(H[2])===Z);if(W.length!==1||X.length!==1)return!1;let K=W[0]?.[0],j=X[0]?.[3]??"";return(j===""||j.split(",").every((H)=>H===K))&&!Q.some((H)=>Number(H[2])!==$&&Number(H[3])===Z)}catch{return!1}}function s$($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>D3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function o$($,Z={}){if(!A){let J=process.geteuid?.();if(J===void 0)return;let z=process.getegid?.(),Y;try{Y=await f7($)}catch{return}let Q;for(;;){let G=await p$(Y).catch(()=>{return});if(G&&(G.mode&18)!==0&&(G.mode&512)===0){if(Q===void 0)Q=z!==void 0&&await g7(J,z,Z);if((G.mode&2)!==0||G.uid!==J||G.gid!==z||!Q)throw new R("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let W=A0(Y);if(W===Y)return;Y=W}}try{await U0($,s$(Z))}catch(J){if(!(J instanceof l))throw J;throw new R("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function O1($,Z={}){if(A){await Q0($,!1,s$(Z));return}await _7($,{recursive:!0,mode:448});let J=await p$($),z=process.geteuid?.();if(z!==void 0&&J.uid!==z)throw new R("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((J.mode&63)!==0)await k7($,448)}async function b0($,Z,J={}){let z=A0($);await O1(z,J),await o$(z,J);let Y=`${JSON.stringify(Z)}
|
|
11
|
+
`;if(Buffer.byteLength(Y)>N1)throw new R("invalid-state","Claustrum enrollment state is too large");if(A)return h0($,Y);let Q=x7(z,`.${S7($)}.${process.pid}.${A7()}.tmp`),G,W=!1;try{G=await c$(Q,"wx",384),W=!0,await G.writeFile(Y,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await E7(Q,$),W=!1}finally{if(await G?.close().catch(()=>{}),W)await d$(Q).catch(()=>{})}}async function P1($,Z){let J=await k0($.tokenPath),z=J===void 0?void 0:I3(J),Y=await k0($.statePath),Q=Y===void 0?void 0:O3(Y);if(z)return{state:"approved",proposedName:Q?.proposedName??Z,...Q?.phase==="approved"&&Q.approvedName!==void 0&&{approvedName:Q.approvedName},tokenGeneration:z.token_generation};if(!Q)return{state:"idle"};if(Q.phase==="approved")return{state:"blocked",proposedName:Q.proposedName,code:"missing_token"};return D0(Q)}async function _0($){let Z=await k0($);if(Z===void 0)throw new R("not-enrolled","Claustrum enrollment is not configured");return I3(Z)}function D0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function r$(){return new R("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class C1{#$;#Z;#J;#Q;#K;#Y;#z;constructor($){this.#z=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#J=$.proposedName,this.#Q=$.now??Date.now,this.#K=$.mintSecret??(()=>b7(32).toString("hex")),this.#Y=$.writeTokenFile??I1}async status(){return P1(this.#Z,this.#J)}async resetTerminal(){return t$(this.#Z,this.#J)}async#W($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Q()};return await b0(this.#Z.statePath,J,this.#z),D0(J)}async reconcile(){await O1(A0(this.#Z.statePath),this.#z);let $=await M0({name:"ceremony",path:this.#Z.statePath,ttlMs:u$,renew:!0});if(!$)return{state:"busy"};try{let Z=await k0(this.#Z.tokenPath),J=Z===void 0?void 0:I3(Z),z=await k0(this.#Z.statePath),Y=z===void 0?void 0:O3(z);if(Y&&Y.proposedName!==this.#J)throw r$();if(J){if(!Y||Y.phase==="pending"){let G={version:1,phase:"approved",proposedName:Y?.proposedName??this.#J,tokenGeneration:J.token_generation,updatedAt:this.#Q()};await b0(this.#Z.statePath,G,this.#z),Y=G}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:J.token_generation}}if(Y?.phase==="approved"){let G={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#Q()};return await b0(this.#Z.statePath,G,this.#z),D0(G)}if(Y&&Y.phase!=="pending")return D0(Y);if(!Y){let G=this.#Q();if(Y={version:1,phase:"pending",proposedName:this.#J,requestSecret:this.#K(),createdAt:G,updatedAt:G},!B3.test(Y.requestSecret))throw new R("invalid-state","invalid minted Claustrum enrollment secret");await b0(this.#Z.statePath,Y,this.#z)}if(!Y.requestId)try{let G=R7("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:Y.proposedName,requestSecretHash:G});Y={...Y,requestId:W.requestId,updatedAt:this.#Q()},await b0(this.#Z.statePath,Y,this.#z)}catch(G){let W=F3(G);if(!W)throw G;if(W.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:W.code};return this.#W(Y,W.code)}let Q=Y.requestId;if(!Q)return D0(Y);try{let G=await this.#$.enrollPoll({requestId:Q,requestSecret:Y.requestSecret});if(G.status==="pending")return D0(Y);if(G.status==="denied"){let X={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#Q()};return await b0(this.#Z.statePath,X,this.#z),D0(X)}await O1(A0(this.#Z.tokenPath),this.#z),await o$(A0(this.#Z.tokenPath),this.#z),await this.#Y(this.#Z.tokenPath,{token:G.token,token_generation:G.tokenGeneration});let W={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:G.name,tokenGeneration:G.tokenGeneration,updatedAt:this.#Q()};return await b0(this.#Z.statePath,W,this.#z),D0(W)}catch(G){let W=F3(G);if(!W)throw G;if(W.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:Q,retryCode:W.code};return this.#W(Y,W.code)}}finally{await $.release()}}}async function t$($,Z){await O1(A0($.statePath));let J=await M0({name:"ceremony",path:$.statePath,ttlMs:u$,renew:!0});if(!J)return"busy";try{if(await k0($.tokenPath)!==void 0)return"refused-approved";let z=await k0($.statePath);if(z===void 0)return"idle";let Y=O3(z);if(Y.proposedName!==Z)throw r$();if(Y.phase==="pending")return"refused-pending";return await J.assertOwned(),await d$($.statePath),"reset"}finally{await J.release()}}var P3="claustrum-tombstone:v1:";function e$($,Z){return Z!==void 0&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function h7($,Z){if(Z===void 0)return"reauthorize-failed";if(Z.credentialId!==$.credentialId)return"credential-changed";if(Z.accountIdentity!==$.accountIdentity)return"account-changed";if(Z.recordVersion===$.recordVersion)return"version-unchanged";return"rotated"}var $2=t0("claustrum");function b3($,Z,J,z=$2){let Y=e$(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:Y,reason:h7(Z,J)}),Y}var R3=300000;function C3(){return new R("invalid-material","Claustrum returned invalid credential material")}function y7($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw C3()}if(!J||typeof J!=="object")throw C3();let z=J,Y=z.access_token??z.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(P3))throw C3();return Z}function m7($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}class R1{#$;#Z;#J;#Q;#K;#Y;#z;#W=new WeakMap;#U=new WeakMap;#X=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>_0(Z);else throw new R("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#Q=$.family,this.#K=$.parseIdentity,this.#Y=$.requireAssertion??!1,this.#J=$.now??Date.now,this.#z=$.logger??$2}#G($){if(this.#X)throw new R("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#H($){this.#G($);let Z=await this.#Z();if(this.#G($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new R("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#j($,Z){this.#G(Z);let J,z;try{let Y=$();J=Z?await Promise.race([Y,new Promise((Q,G)=>{let W=()=>G(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await Y}catch(Y){if(this.#G(Z),Y instanceof $1)throw Y;throw new R("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#G(Z),J}async discover($){let Z=await this.#H($),J=await this.#j(()=>this.#$.listScoped(Z),$),z=[],Y=[],Q=new Map;for(let W of J.rows){let X=m7(W,this.#Q);if(!X)continue;Y.push({row:W,type:X}),Q.set(W.id,(Q.get(W.id)??0)+1)}let G=[];for(let{row:W,type:X}of Y){let K;if(!W.id.trim())K="empty credential id";else if((Q.get(W.id)??0)>1)K="duplicate credential id";else if(W.accountId!==void 0&&!W.accountId.trim())K="blank account identity";else if(!W.state.trim())K="empty state";if(K){z.push({...W.id.trim()&&{credentialId:W.id},reason:K});continue}G.push(Object.freeze({credentialId:W.id,credentialType:X,...W.accountId!==void 0&&{accountIdentity:W.accountId},state:W.state,...W.email!==void 0&&{email:W.email},...W.orgName!==void 0&&{orgName:W.orgName}}))}for(let W of z)this.#z.warn("skipped malformed vault record",W);return{view:J.view,credentials:Object.freeze(G),skipped:Object.freeze(z)}}async authorize($,Z){if(!$.credentialId)throw new R("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:J,credentialType:z,accountIdentity:Y}=$;if(this.#Y&&Y===void 0)throw new R("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#H(Z),G=await this.#j(()=>this.#$.getScoped({credentialId:J,enrollmentToken:Q,...z==="oauth"&&{minTtlMs:R3}}),Z);if(G.credentialId!==void 0&&G.credentialId!==J)throw new R("identity-changed","Claustrum served credential identity changed");let W=G.expiresAtMs;if(!Number.isSafeInteger(G.recordVersion)||G.recordVersion<0||W===null&&z==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#J()<R3))throw new R("insufficient-validity","Claustrum served credential has insufficient validity");let X=y7(G.material),K=G.accountId?.trim()?G.accountId:void 0;if(this.#Y&&(G.credentialId===void 0||K===void 0))throw new R("identity-unasserted","Claustrum served credential did not assert its identity");let j=K===void 0?this.#K?.(X):void 0,H=K??j;if(Y!==void 0&&H!==void 0&&H!==Y)throw new R("identity-changed","Claustrum served credential identity changed");let M=H??Y,q=Object.freeze(Object.defineProperty({credentialId:J,credentialType:z,...M!==void 0&&{accountIdentity:M},accountIdentitySource:K!==void 0?"asserted":j!==void 0?"parsed":Y!==void 0?"expected":"none",...Y!==void 0&&{expectedAccountIdentity:Y},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...K!==void 0&&{assertedAccountIdentity:K},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:W},"accessToken",{value:X,enumerable:!1}));return this.#W.set(q,Q),q}async reportFailure($,Z,J){if(Z!==401)return;this.#G();let z=this.#W.get($);if(!z)throw new R("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#U.get($);if(Y)return Y;let Q=this.#j(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#U.set($,Q);try{await Q,this.#z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(G){throw this.#U.delete($),G}}close(){if(this.#X)return;this.#X=!0,this.#$.close()}}import{createHash as r7}from"node:crypto";var f0="all",v7=Object.freeze(["primary"]);function J2($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function v0($,Z){return JSON.stringify([$,Z])}function E0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function t($){return typeof $==="number"&&Number.isFinite($)}function Z2($){return typeof $==="string"&&$.length>0}function Y0($,Z,J){return $[Z]===void 0||J($[Z])}function c7($){return t($)&&$>0}function A3($){return typeof $==="string"}function p7($){if(!E0($)||!Z2($.scope)||!Z2($.label))return!1;switch($.kind){case"reading":return t($.checkedAt)&&t($.usedPercent)&&Y0($,"resetsAt",A3)&&Y0($,"windowMinutes",c7);case"retired":return t($.retiredAt);case"absent":return t($.checkedAt);default:return!1}}function d7($){if(!E0($)||!t($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&Y0($,"remainingPercent",t)&&Y0($,"usedPercent",t)&&Y0($,"resetsAt",A3)&&Y0($,"limit",t)&&Y0($,"used",t)&&Y0($,"remaining",t)&&Y0($,"unit",A3)}function z2($){return E0($)&&t($.value)&&Number.isInteger($.value)&&$.value>=0&&t($.checkedAt)}function k3($){return E0($)&&Object.values($).every(z2)}function Y2($){if(!E0($))return;let Z=Object.entries($).filter(([,J])=>z2(J));return Z.length===0?void 0:Object.fromEntries(Z)}function S0($){if(Z1($))return $;if(!E0($))return;let{counters:Z,...J}=$;if(!Z1(J))return;let z=Y2(Z);return{...J,...z===void 0?{}:{counters:z}}}function Z1($){if(!E0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!p7(J))return!1;let z=v0(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return Y0($,"budget",d7)&&Y0($,"counters",k3)}class b1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function k1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function A1($){return typeof $==="number"&&Number.isFinite($)}function Q2($){return $===void 0||typeof $==="string"&&$!==""}function G2($){return typeof $==="string"&&$!==""}function J1($,Z){return $[Z]===void 0||A1($[Z])}function _3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function u7($){return k1($)&&Q2($.scope)&&G2($.label)&&A1($.usedPercent)&&_3($,"resetsAt")&&($.windowMinutes===void 0||A1($.windowMinutes)&&$.windowMinutes>0)}function l7($){return k1($)&&Q2($.scope)&&G2($.label)}function i7($){if(!k1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&J1($,"remainingPercent")&&J1($,"usedPercent")&&_3($,"resetsAt")&&J1($,"limit")&&J1($,"used")&&J1($,"remaining")&&_3($,"unit")}function W2($){if(!k1($)||!A1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let Y of Z){if(!u7(Y))return!1;let Q=v0(Y.scope??f0,Y.label);if(z.has(Q))return!1;z.add(Q)}if(!J.every(l7))return!1;return($.budget===void 0||i7($.budget))&&($.counters===void 0||k3($.counters))}function a7($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function n7($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function s7($,Z){let J=new Map(Object.entries($??{}));for(let[z,Y]of Object.entries(Z??{})){let Q=J.get(z);if(Q===void 0||Y.checkedAt>=Q.checkedAt)J.set(z,Y)}return J.size===0?void 0:Object.fromEntries(J)}function c0($,Z){let J=$===void 0?void 0:S0($);if($!==void 0&&J===void 0)throw new b1("stored quota map is malformed");if(!W2(Z))throw new b1("quota observation is malformed");let z=J??{limits:[]},Y=Z.checkedAt,Q=new Map;for(let q of z.limits)Q.set(v0(q.scope,q.label),q);let G=(q)=>{let B=Q.get(q);return B===void 0||Y>=J2(B)},W=new Set;for(let q of Z.readings??[]){let B=q.scope??f0,N=v0(B,q.label);if(W.add(N),!G(N))continue;Q.set(N,{scope:B,label:q.label,kind:"reading",checkedAt:Y,usedPercent:q.usedPercent,...q.resetsAt===void 0?{}:{resetsAt:q.resetsAt},...q.windowMinutes===void 0?{}:{windowMinutes:q.windowMinutes}})}for(let q of Z.coverage??[]){let B=q.scope??f0,N=v0(B,q.label);if(W.has(N)||!G(N))continue;let x=Q.get(N);Q.set(N,x===void 0||x.kind==="absent"?{scope:B,label:q.label,kind:"absent",checkedAt:Y}:{scope:B,label:q.label,kind:"retired",retiredAt:Y})}let{limits:X,budget:K,counters:j,...H}=z,M=n7(z.budget,Z.budget,Y),D=s7(z.counters,Z.counters);return{...H,limits:[...Q.values()].sort(a7),...M===void 0?{}:{budget:M},...D===void 0?{}:{counters:D}}}var o7=Object.freeze({validate:Z1,decode:S0,merge:c0});function X2($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function f3($,Z,J){return $.some((z)=>X2(z,Z,J))}function E3($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==J),z]}function S3($,Z,J){return $.filter((z)=>!Z.some((Y)=>X2(z,Y,J)))}var H2="vault:";function t7($){return r7("sha256").update($).digest("hex")}function e7($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function $4($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function F0($){return[$.credentialId,...$.aliases??[]]}function j2($,Z,J={}){let z=J.now??Date.now(),Y=J.routePrefix??H2,Q=J.reservedRouteIds??new Set,G=$?.rows??[],W=[...$?.declined??[]],X=Z.skipped.length===0,K=new Set(Z.credentials.map((F)=>F.credentialId)),j=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),H=Z.skipped.some((F)=>F.credentialId===void 0),M=(F)=>!K.has(F)&&(j.has(F)||H),D=new Map;for(let F of G){if(F.accountIdentity===void 0)continue;for(let U of F0(F))if(!D.has(U))D.set(U,F.accountIdentity)}let q=new Map;for(let F of Z.credentials){let U=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:D.get(F.credentialId),claimed:!1},P=$4(U),I=q.get(P)??[];I.push(U),q.set(P,I)}let B=new Set,N=new Set(Q),x=[],m=(F,U)=>F.credential.credentialId.localeCompare(U.credential.credentialId),p=[...q.values()].map((F)=>F.toSorted(m)).sort((F,U)=>F[0]&&U[0]?m(F[0],U[0]):0);for(let F of p){let U=F[0]?.identity,P=F.filter((w)=>w.credential.state==="active"),I=P.length?P:F,E=I.filter((w)=>w.claimed),S=E.length?E:I,h=new Set(F.map((w)=>w.credential.credentialId)),T=G.find((w)=>!B.has(w)&&F0(w).some((z0)=>h.has(z0))&&(w.accountIdentity===void 0||w.accountIdentity===U)),k=S.find((w)=>w.credential.credentialId===T?.credentialId)??S[0];if(!k)continue;let _=k.credential,b=T??(U===void 0?void 0:G.find((w)=>!B.has(w)&&w.accountIdentity===U));if(b)B.add(b);let c=b?.routeId;if(!c||Q.has(c)){let w=`${Y}${_.credentialId}${U===void 0?"":`~${t7(U).slice(0,10)}`}`;c=w;for(let z0=2;N.has(c);z0++)c=`${w}~${z0}`}N.add(c);let o=b?F0(b).filter(M):[],i=[...new Set([...F.map((w)=>w.credential.credentialId),...o])].filter((w)=>w!==_.credentialId).sort((w,z0)=>w.localeCompare(z0)),j0=J.mapAccount?.(_)??{};x.push({previousIndex:b?G.indexOf(b):1/0,row:{routeId:c,credentialId:_.credentialId,credentialType:_.credentialType,...U!==void 0&&{accountIdentity:U},...i.length&&{aliases:i},state:_.state,label:j0.label?.trim()||e7(_),..._.email!==void 0&&{email:_.email},..._.orgName!==void 0&&{orgName:_.orgName},enabled:![_.credentialId,...i].some((w)=>f3(W,w,U)),addedAt:b?.addedAt??z,...b?.quota!==void 0&&{quota:b.quota},...!k.claimed&&U!==void 0&&{unclaimed:!0}}})}return G.forEach((F,U)=>{if(B.has(F)||!F0(F).some(M))return;if(N.has(F.routeId))return;let[P,...I]=F0(F).filter((h)=>!K.has(h));if(P===void 0)return;N.add(F.routeId);let{aliases:E,...S}=F;x.push({previousIndex:U,row:{...S,credentialId:P,...I.length&&{aliases:I},stale:!0}})}),x.sort((F,U)=>F.previousIndex===U.previousIndex?F.row.credentialId.localeCompare(U.row.credentialId):F.previousIndex-U.previousIndex),{version:1,view:Z.view,complete:X,...!X&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:x.map((F)=>F.row),declined:W}}function x3($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function z1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function p0($){return $===void 0||typeof $==="string"}function Z4($){let Z=z1($)?S0($.quota):void 0;if(!z1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!p0($.accountIdentity)||!p0($.email)||!p0($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((J)=>typeof J==="string"))||$.quota!==void 0&&Z===void 0||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return{...$,...Z===void 0?{}:{quota:Z}}}var J4=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function K2($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!z1(J)||!p0(J.credentialId)||typeof J.reason!=="string"||!J4.has(J.reason))return;Z.push(J)}return Z}function z4($){if(!z1($)||$.version!==1||!p0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!K2($.rejected))throw new R("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let Q=Z4(Y);if(!Q)throw new R("invalid-state","Claustrum roster file is not valid");Z.push(Q)}let J=[];for(let Y of $.declined){if(!z1(Y)||typeof Y.credentialId!=="string"||!p0(Y.accountIdentity))throw new R("invalid-state","Claustrum roster file is not valid");J.push(Y)}let z=K2($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},rows:Z,declined:J}}async function W0($){let Z;try{Z=await G0($,A)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new R("invalid-state","Claustrum roster file is not valid")}return z4(J)}var Y4={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},Q4={name:"claustrum-roster",ttlMs:30000};async function d0($,Z,J={}){return V3($,Y4,async(z)=>{let Y=await W0($),{next:Q,result:G}=await Z(Y,{assertOwned:()=>z.assertOwned()});if(Q)await z.assertOwned(),await j3($,Q,{beforeRename:async()=>{await J.beforePublish?.(),await z.assertOwned()}});return G})}function w3($,Z){return d0($,(J)=>{let z=J?.rows.find((Q)=>Q.routeId===Z);if(!J||!z)throw new R("route-unavailable","Claustrum route is not in the roster");let Y=E3(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:Y,rows:J.rows.map((Q)=>Q===z?{...Q,enabled:!1}:Q)},result:void 0}})}function T3($,Z){return d0($,(J)=>{let z=J?.rows.find((Y)=>Y.routeId===Z);if(!J||!z)throw new R("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:S3(J.declined,F0(z),z.accountIdentity),rows:J.rows.map((Y)=>Y===z?{...Y,enabled:!0}:Y)},result:void 0}})}function G4($,Z){if(!F0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&F0($).length===1)return"bind";return"refuse"}function g3($,Z){return d0($,(J)=>{let z=J?.rows.find((W)=>W.routeId===Z.routeId),Y=!J||!z?"refuse":G4(z,Z);if(!J||!z||Y==="refuse")return{result:!1};let Q=c0(z.quota,Z.observation),G=Y==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...J,rows:J.rows.map((W)=>W===z?{...W,...G,quota:Q}:W)},result:!0}})}function h3($,Z){return d0($,(J)=>{let z=J?.rows.find((Q)=>Q.routeId===Z.routeId);if(!J||!z||z.accountIdentity===void 0||z.accountIdentity!==Z.accountIdentity)return{result:!1};let Y=c0(z.quota,Z.observation);return{next:{...J,rows:J.rows.map((Q)=>Q===z?{...Q,quota:Y}:Q)},result:!0}})}async function y3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let J=await M0({...Q4,path:$.path,renew:!0});if(!J){let z=await W0($.path);if($.signal?.throwIfAborted(),!z?.view)throw new R("roster-busy","Claustrum account discovery is already in progress");return z}try{let z=await $.custody.discover($.signal);return $.signal?.throwIfAborted(),await d0($.path,async(Y)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let Q=typeof $.projection==="function"?$.projection():$.projection,G=j2(Y,z,Q);return{...JSON.stringify(Y)!==JSON.stringify(G)&&{next:G},result:G}})}finally{await J.release()}}class U2{#$;#Z=new AbortController;#J;#Q;#K;#Y;#z;#W;#U=!1;#X;constructor($){this.#$=$,this.#J=$.logger??t0("claustrum")}#G($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}async#H(){return await this.#$.isCustodyActive?.()??!0}#j($,Z){let J=K3([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,Y)=>{let Q=()=>{J.signal.removeEventListener("abort",G),J.dispose()},G=()=>{Q(),Y(J.signal.reason)};if(J.signal.addEventListener("abort",G,{once:!0}),$.then((W)=>{if(Q(),J.signal.aborted)Y(J.signal.reason);else z(W)},(W)=>{Q(),Y(W)}),J.signal.aborted)G()})}async#q(){if(this.#G(),this.#Q)return this.#Q;if(!this.#K)this.#K=this.#$.connect().then(($)=>{if(this.#Z.signal.aborted)$.close(),this.#G();if(this.#Q=new R1({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#J}),this.#$.insula&&$.insula)this.#X=D$($.insula,this.#$.tokenPath);return this.#Q}).finally(()=>{this.#K=void 0});return this.#j(this.#K)}snapshot(){return this.#z}routingRows(){return x3(this.#z)}refresh(){if(this.#G(),this.#Y)return this.#Y;return this.#Y=(async()=>{if(!await this.#H()){this.#z=void 0,this.#Q?.close(),this.#Q=void 0,this.#X?.release(),this.#X=void 0;return}let $=await this.#q(),Z=await y3({path:this.#$.rosterPath,custody:$,isActive:()=>this.#H(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#G();let J=Z?.view!==this.#z?.view;if(this.#z=Z,Z&&J)this.#$.onRoster?.(Z);return Z})().finally(()=>{this.#Y=void 0}),this.#Y}start(){if(this.#U)return;this.#G(),this.#U=!0;let $=async()=>{try{await this.refresh(),await this.refreshInsulaQuota()}catch(J){if(!this.#Z.signal.aborted)this.#$.onError?.(J)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#W=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#W=void 0,$()},Z),this.#W.unref?.()};$()}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#H())return;try{await _0(this.#$.tokenPath),await this.#q(),await this.#X?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#H())return;try{return await _0(this.#$.tokenPath),this.#V($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#H())return;try{await _0(this.#$.tokenPath);let J=(await W0(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#V(J?.accountIdentity)}catch{return}}#V($){if(!this.#$.insula||!$)return;let Z=this.#X?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#G(Z);let J=this.#z??await this.#j(this.refresh(),Z);if(!J||!await this.#H())throw new R("not-active","Claustrum scoped custody is not active");let z=await W0(this.#$.rosterPath);this.#G(Z);let Y=J.rows.find((X)=>X.routeId===$),Q=z?.rows.find((X)=>X.routeId===$);if(Q&&!Q.enabled)throw new R("route-declined","Claustrum route is disabled");if(!Y||!Q||Q.state!=="active"||Q.credentialId!==Y.credentialId||Q.accountIdentity!==Y.accountIdentity)throw new R("route-unavailable","Claustrum route is disabled, removed or changed");let G=await this.#j(this.#q(),Z),W=K3([this.#Z.signal,...Z?[Z]:[]]);try{return await G.authorize({credentialId:Q.credentialId,credentialType:Q.credentialType,...Q.accountIdentity!==void 0&&{accountIdentity:Q.accountIdentity}},W.signal)}finally{W.dispose()}}async reportFailure($,Z,J){if(this.#G(),!this.#Q)throw new R("no-receipt","Claustrum dispatch receipt has no active owner");await this.#Q.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,Y=await this.authorize($,z),Q=await Z(Y,z);if(Q.status===401&&!z?.aborted){let G;try{G=await this.authorize($,z)}catch{}if(b3(J.site,Y,G,this.#J))await Q.body?.cancel().catch(()=>{}),Y=G,Q=await Z(G,z)}if(Q.status===401)await this.reportFailure(Y,401,J.reporterSource??"direct").catch((G)=>this.#$.onError?.(G)),Promise.resolve().then(()=>this.refresh()).catch((G)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(G)});return Q}async decline($){this.#G(),await w3(this.#$.rosterPath,$),this.#z=await W0(this.#$.rosterPath)}async accept($){this.#G(),await T3(this.#$.rosterPath,$),this.#z=await W0(this.#$.rosterPath)}async recordQuota($,Z,J){this.#G();let z=await g3(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:J.credentialId,accountIdentitySource:J.accountIdentitySource,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity},...J.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:J.expectedAccountIdentity}});if(z)this.#z=await W0(this.#$.rosterPath);return z}async recordAccountQuota($,Z,J){this.#G();let z=await h3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J});if(z)this.#z=await W0(this.#$.rosterPath);return z}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new R("closed","Claustrum consumer is closed")),this.#W)(this.#$.clearTimeoutImpl??clearTimeout)(this.#W);this.#W=void 0,this.#Q?.close(),this.#X?.release(),this.#X=void 0,this.#z=void 0}}class X0 extends Error{code;constructor($){super(`Native vault setup: ${$}`);this.code=$;this.name="NativeVaultEnrollmentError"}}async function V2($,Z){let J={...Z.env},z=Z.paths??q2($,J),Y=`anthropic-auth-${$}`,Q=Z.processFence,G=Z.runner,W=Z.ckBinary??"ck",X,K=Z.client;try{await Q();let j=await P1(z,Y),H=new Set(["superseded","not_found","already_consumed"]);if(j.state==="idle"||j.state==="pending"||j.state==="blocked"&&H.has(j.code)){if(!K)X=await N3({connectionFile:_1(Z.connectionFile??($==="pi"?J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0),$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:J)}),K=X;let D=K,q=new C1({paths:z,proposedName:Y,client:{enrollPropose:async(B)=>{return await Q(),D.enrollPropose(B)},enrollPoll:async(B)=>{return await Q(),D.enrollPoll(B)}},writeTokenFile:async(B,N)=>{await Q(),await I1(B,N)}});if(j.state==="blocked"){if(await Q(),await q.resetTerminal()!=="reset")throw new X0("enrollment-refused");throw new X0("enrollment-reset")}if(await Q(),j=await q.reconcile(),j.state==="pending"&&j.requestId){if(await Q(),(await G.run(W,["auth","enroll","approve","--request-id",j.requestId,"--name",Y],{env:J})).exitCode!==0)throw new X0("approval-refused");await Q(),j=await q.reconcile()}}if(j.state!=="approved")throw new X0("enrollment-refused");if(await Q(),(await G.run(W,["auth","grant","--principal",`enrolled:${Y}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"],{env:J})).exitCode!==0)throw new X0("permission-refused")}catch(j){if(j instanceof X0)throw j;throw new X0("enrollment-refused")}finally{X?.close()}}import{dirname as W4,join as M2,resolve as f1}from"node:path";async function l0($,Z){let J=$==="pi"?u0(Z):x0(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),Y=f1(z||M2(J,m3)),Q=f1(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(Y.endsWith(m3)?M2(W4(Y),D2):`${Y}.state.json`)),G=await E1(Y,Q),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:G,legacyConfigPath:Y,legacyStatePath:Q,hostAuthPath:$==="pi"?S1(Z):L2(Z),routingSourcePath:f1(W||v3(Y)),routingDestinationPath:f1(W||v3(G.config))}}async function B2($){let Z=new Map;for(let J of $)for(let z of[J.paths.legacyConfig,J.paths.legacyState,J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.hostAuthPath,J.routingSourcePath,J.routingDestinationPath]){let Y=await F2(z),Q=Z.get(Y);if(Q!==void 0&&Q!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(Y,J.host)}}import{execFile as X4}from"node:child_process";import{promisify as K4}from"node:util";var H4=K4(X4),$0={async run($,Z,J={}){try{let z=J.env?{...process.env,...J.env}:process.env,{stdout:Y,stderr:Q}=await H4($,Z,{env:z,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof Y==="string"?Y:String(Y),stderr:typeof Q==="string"?Q:String(Q)}}catch(z){let Y=z;return{exitCode:typeof Y?.code==="number"?Y.code:1,stdout:typeof Y?.stdout==="string"?Y.stdout:Y?.stdout!=null?String(Y.stdout):"",stderr:typeof Y?.stderr==="string"?Y.stderr:Y?.stderr!=null?String(Y.stderr):String(Y?.message??z)}}}};var N2=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class L0 extends Error{code="process-inspection-failed";constructor(){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError"}}class x1 extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:N2.exec(z.command)?.[1]??"host"})),J=Z.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
|
|
12
12
|
`);super(`OpenCode or Pi processes are currently running:
|
|
13
13
|
${J}
|
|
14
14
|
|
|
15
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}function
|
|
16
|
-
`,$.length-
|
|
17
|
-
`,
|
|
15
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}function j4($=$0,Z={}){let J=(Z.platform??process.platform)==="win32";return{async listRunningHosts(z){let Y=J?"tasklist":"ps",Q=J?["/fo","csv","/nh"]:["-eo","pid,command"],G;try{G=await $.run(Y,Q,{env:z})}catch{throw new L0}if(G.exitCode!==0)throw new L0;let W=G.stdout.split(/\r?\n/),X=[],K=process.pid;for(let j of W){let H=j.trim();if(!H)continue;let M,D;if(J){let q=H.split(",").map((B)=>B.replace(/^"|"$/g,""));if(q.length<2)throw new L0;D=q[0]??"",M=Number(q[1])}else{let q=/^(\d+)\s+(.+)$/.exec(H);if(!q){if(/^PID\s+COMMAND$/i.test(H))continue;throw new L0}M=Number(q[1]),D=q[2]??""}if(!Number.isInteger(M)||M<0)throw new L0;if(M===K)continue;if(N2.test(D))X.push({pid:M,command:D})}return X}}}var c3=j4($0);async function i0($=c3){let Z=await $.listRunningHosts();if(Z.length>0)throw new x1(Z)}class w0 extends Error{code;constructor($){super({"auth-content-refused":"Run setup without OPENCODE_AUTH_CONTENT in the environment.","host-auth-invalid":"The host auth file could not be read safely.","primary-conflict":"Pi has a stored Anthropic API key, which would take precedence over the vault account. Remove it in Pi, then rerun setup.","consent-required":"Pi has stored Anthropic authentication. Explicit consent is required to move it aside for vault use.","primary-unverified":"The vault has no verified default Claude account. Sign in through the vault and rerun setup."}[$]);this.code=$;this.name="NativeVaultActivationError"}}async function q4($){try{return JSON.parse(await U4($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new w0("host-auth-invalid")}}async function P2($,Z){let J={...Z.env},z=async()=>{try{w1(J)}catch{throw new w0("auth-content-refused")}await i0(Z.fence)};await z();let Y=Z.paths??await l0($,J);if($==="pi"){let X=O2("pi",await q4(Y.hostAuthPath)),K=await p3({env:J,authPath:Y.hostAuthPath}).inspect();if(K.slot==="placeholder"&&K.stash==="missing")throw new T1("missing-stash");if(X.kind!=="absent"&&K.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new w0("consent-required")}let Q=await B0($,J);await V2($,{env:J,runner:Z.runner,processFence:z,...Z.enrollment});let G=Z.discover??(()=>I2({paths:Y.paths,host:$,env:$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:J})),W=a0({paths:Y.paths,host:$,vault:{env:J,discover:G}});try{await z(),await W.vault.refresh();let X=await W.read(),K=X.accounts.find((j)=>j.id==="main");if(X.mode!=="claustrum"||!K?.accountIdentity||K.source!=="vault")throw new w0("primary-unverified");if(await z(),$==="pi")await p3({env:J,authPath:Y.hostAuthPath}).enterVault();return Q==="claustrum"?"already-vault":"committed"}finally{W.close()}}var B4={"setup-activation":"Vault custody setup","setup-opencode-config":"OpenCode configuration","setup-pi-install":"Pi extension installation","setup-pi":"Pi setup","setup-process-check":"Host process check","cli-setup":"Setup","cli-login":"Login","cli-api-add":"API route setup","cli-list":"Account listing","cli-relay-setup":"Relay setup","cli-relay-workers-dev":"Workers.dev enablement","cli-command":"Command"};function Y1(){return($)=>$}var N4=Y1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified"]),O4=Y1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),I4=Y1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused"]),P4=Y1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),C4=Y1()(["closed","not-enrolled","invalid-token","unavailable","identity-changed","identity-unasserted","insufficient-validity","invalid-material","not-active","route-unavailable","route-declined","no-receipt","unsafe-file","invalid-state","wrong-consumer","roster-busy","host-slot-login","host-slot-placeholder","placeholder-refresh"]),R4=new Set([new L0().message,...N4.map(($)=>new w0($).message),...O4.map(($)=>new X0($).message),...I4.map(($)=>new f2($).message),...P4.map(($)=>new T1($).message),...C4.map(($)=>`Native custody refused: ${$}`),"Disconnect from the vault first.","Native account changes require offline setup without OPENCODE_AUTH_CONTENT","Local login cannot be verified while OPENCODE_AUTH_CONTENT is set","Authentication failed","API fallback base URL must be an http(s) URL without embedded credentials","API key is required","Vault routes cannot be replaced with a local API key","Cloudflare API token is required","Cloudflare account ID is required","Relay Worker URL is required","Claude sign-in did not establish an account UUID","Native setup storage paths overlap between selected hosts","Anthropic account storage paths overlap; migration requires separate files","Anthropic account migration is required. Stop OpenCode, LiteCode and Pi, then run bunx @cortexkit/opencode-anthropic-auth@2.0.0 setup","Anthropic account migration is incomplete; resume setup","Anthropic account migration journal is invalid","Anthropic account migration journal changed","Anthropic runtime state is invalid","Anthropic runtime file is not owner-only regular storage","Anthropic runtime storage is unavailable","Anthropic runtime observation is older than persisted state","Anthropic runtime publication was refused","OAuth metadata read failed"]),b4=new Set(["opencode","litecode","opencode2","pi","host"]),A4=64,k4=256,_4=4096,d3=65536,f4=4096,E4=3,R2="[output beyond the diagnostic limit omitted]",S4="[output withheld: no line break within the inspected window]",x4="[detail withheld: the known credentials could not be read safely]",i3=new TextEncoder,E2=new TextDecoder;function Z0($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function Q1($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!l3.isProxy($)}function S2($,Z){if(!Q1($)||!Array.isArray($))return;let J=Z0($,"length");if(typeof J!=="number"||J>Z)return;let z=[];for(let Y=0;Y<J;Y+=1){let Q=Object.getOwnPropertyDescriptor($,String(Y));if(Q===void 0||!("value"in Q))return;z.push(Q.value)}return z}function w4($){let Z=S2($,A4);if(Z===void 0||Z.length===0)return;let J=[];for(let z of Z){if(!Q1(z))return;let Y=Z0(z,"pid"),Q=Z0(z,"command");if(typeof Y!=="number"||!Number.isSafeInteger(Y)||Y<0)return;if(typeof Q!=="string"||!b4.has(Q.toLowerCase()))return;J.push({pid:Y,command:Q})}return J}function T4($){try{if(!Q1($))return;let Z=Z0($,"message");if(typeof Z!=="string")return;if(R4.has(Z))return Z;let J=Z0($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let z=w4(Z0($,"activeHosts"));if(z&&Z===new x1(z).message)return Z}catch{}return}function g4($,Z=[]){try{let J=new Set,z=S2(Z,k4);if(z===void 0)return;for(let Q of z){if(typeof Q!=="string")return;if(Q!=="")J.add(Q)}if(!Q1($))return;let Y=Reflect.ownKeys($);if(Y.length>_4)return;for(let Q of Y){if(typeof Q!=="string"||!A2(Q))continue;let G=Object.getOwnPropertyDescriptor($,Q);if(G===void 0)continue;if(!("value"in G))return;if(G.value===void 0||G.value==="")continue;if(typeof G.value!=="string")return;J.add(G.value)}return[...J]}catch{return}}function h4($,Z){let J=i3.encode($);if(J.length<=Z)return $;let z=Math.max(0,Z);while(z>0&&((J[z]??0)&192)===128)z-=1;return E2.decode(J.subarray(0,z))}function y4($,Z){let J=i3.encode($);if(J.length<=Z)return $;let z=J.length-Math.max(0,Z);while(z<J.length&&((J[z]??0)&192)===128)z+=1;return E2.decode(J.subarray(z))}function m4($,Z,J){let z=$,Y=!1;if($.length>d3){if(Y=!0,J==="tail"){let X=$.indexOf(`
|
|
16
|
+
`,$.length-d3);z=X===-1?"":$.slice(X+1)}else{let X=$.lastIndexOf(`
|
|
17
|
+
`,d3);z=X===-1?"":$.slice(0,X)}if(z==="")return[S4]}let Q=Z.redactText(z).split(/\r?\n/);if(Q.length>1&&Q[Q.length-1]==="")Q.pop();if(J==="tail")Q.reverse();let G=[],W=f4;for(let X of Q){let K=i3.encode(X).length+1;if(K<=W){G.push(X),W-=K;continue}if(G.length===0)G.push(J==="tail"?y4(X,W-1):h4(X,W-1));Y=!0;break}if(J==="tail")G.reverse();if(Y)if(J==="tail")G.unshift(R2);else G.push(R2);return G}function v4($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(l3.isProxy(Z))break;let z=Z0(Z,"name");if(typeof z==="string")return z;Z=Object.getPrototypeOf(Z)}return"object"}function x2($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(l3.isProxy($))return["thrown proxy (not inspected)"];let J=[],z=v4($),Y=Z0($,"message");J.push(typeof Y==="string"?`${z}: ${Y}`:`${z} (no message)`);let Q=Z0($,"code");if(typeof Q==="string"||typeof Q==="number")J.push(`code: ${Q}`);let G=Z0($,"stack");if(typeof G==="string")J.push(G);let W=Z0($,"cause");if(W!==void 0)if(Z>=E4)J.push("caused by: [not described]");else J.push("caused by:",...x2(W,Z+1));return J}function b2($,Z){let J=Z0($,Z);return typeof J==="string"&&J!==""?J:void 0}function c4($){if(!Q1($))return;let Z=b2($,"XDG_STATE_HOME"),J=b2($,"HOME"),z=Z&&C2(Z)?Z:u3(J&&C2(J)?J:L4(),".local","state");return u3(z,"cortexkit","anthropic-auth","diagnostics")}async function p4($,Z,J){try{let z=c4($);if(z===void 0)return;await D4(z,{recursive:!0,mode:448});let Y=await M4(z);if(!Y.isDirectory())return;if(process.platform!=="win32"){if((Y.mode&63)!==0)return;if(Y.uid!==process.getuid?.())return}let Q=u3(z,`${Z}-${Date.now()}-${process.pid}-${V4()}.log`),G=await F4(Q,g1.O_WRONLY|g1.O_CREAT|g1.O_EXCL|(g1.O_NOFOLLOW??0),384);try{await G.writeFile(J,"utf8")}finally{await G.close()}return Q}catch{return}}async function w2($,Z,J,z,Y,Q){let G,W=g4(J,z);if(W===void 0)G=[x4];else try{let H=_2(W);try{let{text:M,keep:D}=Q();G=m4(M,H,D)}finally{H.dispose()}}catch{G=["[failure detail could not be recorded]"]}let X=B4[$],K=k2("error","cli",`${X} failed`,{stage:$,code:Z,...Y}),j=await p4(J,$,`${[K,...G].join(`
|
|
18
18
|
`)}
|
|
19
|
-
`);return
|
|
20
|
-
`),keep:"head"}))}async function
|
|
21
|
-
`),
|
|
22
|
-
`){if(
|
|
23
|
-
`){if(
|
|
24
|
-
`)}var a
|
|
25
|
-
`),
|
|
26
|
-
`),
|
|
27
|
-
`),
|
|
28
|
-
`).map((W,X,K)=>{let
|
|
29
|
-
`)}function
|
|
30
|
-
`),
|
|
31
|
-
`).length-1;this.output.write(a.cursor.move(-999,$*-1))}render(){let $=
|
|
32
|
-
`);this.output.write(G[
|
|
33
|
-
`).slice(
|
|
34
|
-
`)),this._prevFrame=$;return}}this.output.write(a.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function r4($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((Q)=>Q.value===$);return J!==-1?J:0}function t4($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function e4($,Z){if(Z)return $?Z:Z[0]}var $8=class extends P0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#J="";#Z;#Y;#X;#z;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return h1(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let Z=this.userInput.slice(0,this.cursor),J=this.userInput.slice(this.cursor,this.cursor+1),Q=this.userInput.slice(this.cursor+1);return`${Z}${h1("inverse",J)}${Q}`}get options(){return typeof this.#Y=="function"?this.#Y():this.#Y}constructor(Z){super(Z),this.#Y=Z.options,this.#X=Z.placeholder,this.#z=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#Z=typeof Z.options=="function"?Z.filter:Z.filter??t4;let Q;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?Q=Z.initialValue:Q=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(Q=[this.options[0]?.value]),Q)for(let z of Q){let Y=J.findIndex((G)=>G.value===z);Y!==-1&&(this.toggleSelected(z),this.#$=Y)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(z,Y)=>this.#Q(z,Y)),this.on("userInput",(z)=>this.#G(z))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#Q(Z,J){let Q=J.name==="up",z=J.name==="down",Y=J.name==="return",G=this.userInput===""||this.userInput==="\t",W=this.#X,X=this.options,K=W!==void 0&&W!==""&&X.some((H)=>!H.disabled&&(this.#Z?this.#Z(W,H):!0));if(J.name==="tab"&&G&&K){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#z&&!this.multiple&&this.focusedValue!==void 0){let H=String(this.focusedValue);this._clearUserInput(),this._setUserInput(H,!0),this.isNavigating=!1;return}Q||z?(this.#$=u0(this.#$,Q?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):Y?this.value=e4(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((J)=>J!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#G(Z){if(Z!==this.#J){this.#J=Z;let J=this.options;Z&&this.#Z?this.filteredOptions=J.filter((Y)=>this.#Z?.(Z,Y)):this.filteredOptions=[...J];let Q=r4(this.focusedValue,this.filteredOptions);this.#$=u0(Q,0,this.filteredOptions);let z=this.filteredOptions[this.#$];z&&!z.disabled?this.focusedValue=z.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class o3 extends P0{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor($){super($,!1),this.value=!!$.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(Z)=>{this.output.write(a.cursor.move(0,-1)),this.value=Z,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Z8={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function v2($){return[...$].map((Z)=>Z8[Z])}function J8($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],Q="/";for(let z of Z)z.type==="literal"?Q=z.value.trim()||z.value:(z.type==="year"||z.type==="month"||z.type==="day")&&J.push({type:z.type,len:z.type==="year"?4:2});return{segments:J,separator:Q}}function l3($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function g1($){return{year:l3($.year),month:l3($.month),day:l3($.day)}}function i3($,Z){return new Date($||2001,Z||1,0).getDate()}function i2($){let{year:Z,month:J,day:Q}=g1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!Q||Q<1)return;let z=new Date(Date.UTC(Z,J-1,Q));if(!(z.getUTCFullYear()!==Z||z.getUTCMonth()!==J-1||z.getUTCDate()!==Q))return{year:Z,month:J,day:Q}}function c2($){let Z=i2($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function Q8($,Z,J,Q){let z=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,Y=Q?{year:Q.getUTCFullYear(),month:Q.getUTCMonth()+1,day:Q.getUTCDate()}:null;return $==="year"?{min:z?.year??1,max:Y?.year??9999}:$==="month"?{min:z&&Z.year===z.year?z.month:1,max:Y&&Z.year===Y.year?Y.month:12}:{min:z&&Z.year===z.year&&Z.month===z.month?z.day:1,max:Y&&Z.year===Y.year&&Z.month===Y.month?Y.day:i3(Z.year,Z.month)}}class a2 extends P0{#$;#J;#Z;#Y;#X;#z={segmentIndex:0,positionInSegment:0};#Q=!0;#G=null;inlineError="";get segmentCursor(){return{...this.#z}}get segmentValues(){return{...this.#Z}}get segments(){return this.#$}get separator(){return this.#J}get formattedValue(){return this.#H(this.#Z)}#H($){return this.#$.map((Z)=>$[Z.type]).join(this.#J)}#W(){this._setUserInput(this.#H(this.#Z)),this._setValue(c2(this.#Z)??void 0)}constructor($){let Z=$.format?{segments:v2($.format),separator:$.separator??"/"}:J8($.locale),J=$.separator??Z.separator,Q=$.format?v2($.format):Z.segments,z=$.initialValue??$.defaultValue,Y=z?{year:String(z.getUTCFullYear()).padStart(4,"0"),month:String(z.getUTCMonth()+1).padStart(2,"0"),day:String(z.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},G=Q.map((W)=>Y[W.type]).join(J);super({...$,initialUserInput:G},!1),this.#$=Q,this.#J=J,this.#Z=Y,this.#Y=$.minDate,this.#X=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#V(W)),this.on("key",(W,X)=>this.#M(W,X)),this.on("finalize",()=>this.#D($))}#K(){let $=Math.max(0,Math.min(this.#z.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#z.positionInSegment=Math.max(0,Math.min(this.#z.positionInSegment,Z.len-1)),{segment:Z,index:$}}#j($){this.inlineError="",this.#G=null;let Z=this.#K();Z&&(this.#z.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#z.positionInSegment=0,this.#Q=!0)}#U($){let Z=this.#K();if(!Z)return;let{segment:J}=Z,Q=this.#Z[J.type],z=!Q||Q.replace(/_/g,"")==="",Y=Number.parseInt((Q||"0").replace(/_/g,"0"),10)||0,G=Q8(J.type,g1(this.#Z),this.#Y,this.#X),W;z?W=$===1?G.min:G.max:W=Math.max(Math.min(G.max,Y+$),G.min),this.#Z={...this.#Z,[J.type]:W.toString().padStart(J.len,"0")},this.#Q=!0,this.#G=null,this.#W()}#V($){if($)switch($){case"right":return this.#j(1);case"left":return this.#j(-1);case"up":return this.#U(1);case"down":return this.#U(-1)}}#M($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#K();if(!J)return;if(!this.#Z[J.segment.type].replace(/_/g,"")){this.#j(-1);return}this.#Z[J.segment.type]="_".repeat(J.segment.len),this.#Q=!0,this.#z.positionInSegment=0,this.#W();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#K();if(!J)return;let Q=Z.shift?-1:1,z=J.index+Q;z>=0&&z<this.#$.length&&(this.#z.segmentIndex=z,this.#z.positionInSegment=0,this.#Q=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#K();if(!J)return;let{segment:Q}=J,z=!this.#Z[Q.type].replace(/_/g,"");if(this.#Q&&this.#G!==null&&!z){let U=this.#G+$,M={...this.#Z,[Q.type]:U},D=this.#q(M,Q);if(D){this.inlineError=D,this.#G=null,this.#Q=!1;return}this.inlineError="",this.#Z[Q.type]=U,this.#G=null,this.#Q=!1,this.#W(),J.index<this.#$.length-1&&(this.#z.segmentIndex=J.index+1,this.#z.positionInSegment=0,this.#Q=!0);return}this.#Q&&!z&&(this.#Z[Q.type]="_".repeat(Q.len),this.#z.positionInSegment=0),this.#Q=!1,this.#G=null;let Y=this.#Z[Q.type],G=Y.indexOf("_"),W=G>=0?G:Math.min(this.#z.positionInSegment,Q.len-1);if(W<0||W>=Q.len)return;let X=Y.slice(0,W)+$+Y.slice(W+1),K=!1;if(W===0&&Y==="__"&&(Q.type==="month"||Q.type==="day")){let U=Number.parseInt($,10);X=`0${$}`,K=U<=(Q.type==="month"?1:2)}if(Q.type==="year"&&(X=(Y.replace(/_/g,"")+$).padStart(Q.len,"_")),!X.includes("_")){let U={...this.#Z,[Q.type]:X},M=this.#q(U,Q);if(M){this.inlineError=M;return}}this.inlineError="",this.#Z[Q.type]=X;let H=X.includes("_")?void 0:i2(this.#Z);if(H){let{year:U,month:M}=H,D=i3(U,M);this.#Z={year:String(Math.max(0,Math.min(9999,U))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,M))).padStart(2,"0"),day:String(Math.max(1,Math.min(D,H.day))).padStart(2,"0")}}this.#W();let j=X.indexOf("_");K?(this.#Q=!0,this.#G=$):j>=0?this.#z.positionInSegment=j:G>=0&&J.index<this.#$.length-1?(this.#z.segmentIndex=J.index+1,this.#z.positionInSegment=0,this.#Q=!0):this.#z.positionInSegment=Math.min(W+1,Q.len-1)}}#q($,Z){let{month:J,day:Q}=g1($);if(Z.type==="month"&&(J<0||J>12))return d.date.messages.invalidMonth;if(Z.type==="day"&&(Q<0||Q>31))return d.date.messages.invalidDay(31,"any month")}#D($){let{year:Z,month:J,day:Q}=g1(this.#Z);if(Z&&J&&Q){let z=i3(Z,J);this.#Z={...this.#Z,day:String(Math.min(Q,z)).padStart(2,"0")}}this.value=c2(this.#Z)??$.defaultValue??void 0}}var z8=class extends P0{options;cursor=0;#$;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),Q=this.value;return Q===void 0?!1:J.every((z)=>Q.includes(z.value))}toggleValue(){let Z=this.options[this.cursor];if(Z!==void 0)if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,Q=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter((z)=>Q.findIndex((Y)=>Y.value===z)===-1):this.value=[...this.value,...Q.map((z)=>z.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((Q)=>Q!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#$=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Q,z])=>[{value:Q,group:!0,label:Q},...z.map((Y)=>({...Y,group:Q}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Q})=>Q===Z.cursorAt),this.#$?0:1),this.on("cursor",(Q)=>{switch(Q){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let z=this.options[this.cursor]?.group===!0;!this.#$&&z&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let z=this.options[this.cursor]?.group===!0;!this.#$&&z&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Y8=new Set(["up","down","left","right"]);class n2 extends P0{#$=!1;#J;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${$}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),Q=$.slice(this.cursor+1);return J===`
|
|
19
|
+
`);return j===void 0?`${X} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${X} failed (${Z}). Details were written to ${j}`}async function N0($,Z,J,z=[]){let Y=T4(Z);if(Y!==void 0)return Y;return w2($,`${$}/unexpected-error`,J,z,{},()=>({text:x2(Z,0).join(`
|
|
20
|
+
`),keep:"head"}))}async function T2($,Z,J){return w2($,`${$}/installer-exit`,J,[],{exitCode:Number.isInteger(Z.exitCode)?Z.exitCode:null},()=>({text:typeof Z.stderr==="string"?Z.stderr:"",keep:"tail"}))}import{styleText as c1}from"node:util";import{stdout as $$,stdin as Z9}from"node:process";import*as O0 from"node:readline";import Q8 from"node:readline";var g2=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),h2=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},y2=($)=>{return $===8987||$===9001||$>=12272&&$<=12287||$>=12289&&$<=12350||$>=12441&&$<=12543||$>=12549&&$<=12591||$>=12593&&$<=12686||$>=12688&&$<=12771||$>=12783&&$<=12830||$>=12832&&$<=12871||$>=12880&&$<=19903||$>=65040&&$<=65049||$>=65072&&$<=65106||$>=65108&&$<=65126||$>=65128&&$<=65131||$>=127488&&$<=127490||$>=127504&&$<=127547||$>=127552&&$<=127560||$>=131072&&$<=196605||$>=196608&&$<=262141};var d4=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,u4=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,m2=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,l4=/\t{1,1000}/y,v2=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,i4=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,a4=/\p{M}+/gu,n4={limit:1/0,ellipsis:""},c2=($,Z={},J={})=>{let z=Z.limit??1/0,Y=Z.ellipsis??"",Q=Z?.ellipsisWidth??(Y?c2(Y,n4,J).width:0),G=0,W=J.controlWidth??0,X=J.tabWidth??8,K=J.emojiWidth??2,j=2,H=J.regularWidth??1,M=J.wideWidth??2,D=[[i4,H],[d4,0],[u4,W],[l4,X],[v2,K],[m2,M]],q=0,B=0,N=$.length,x=0,m=!1,p=N,F=Math.max(0,z-Q),U=0,P=0,I=0,E=0;$:while(!0){if(P>U||B>=N&&B>q){let S=$.slice(U,P)||$.slice(q,B);x=0;for(let h of S.replaceAll(a4,"")){let T=h.codePointAt(0)||0;if(h2(T))E=2;else if(y2(T))E=M;else E=H;if(I+E>F)p=Math.min(p,Math.max(U,q)+x);if(I+E>z){m=!0;break $}x+=h.length,I+=E}U=P=0}if(B>=N)break $;for(let S=0,h=D.length;S<h;S++){let[T,k]=D[S];if(T.lastIndex=B,T.test($)){if(x=T===m2?g2($.slice(B,T.lastIndex)):T===v2?1:T.lastIndex-B,E=x*k,I+E>F)p=Math.min(p,B+Math.floor((F-I)/k));if(I+E>z){m=!0;break $}I+=E,U=q,P=B,B=q=T.lastIndex;continue $}}B+=1}return{width:m?F:I,index:m?p:N,truncated:m,ellipsed:m&&z>=Q}},p2=c2;var s4={limit:1/0,ellipsis:"",ellipsisWidth:0},o4=($,Z={})=>{return p2($,s4,Z).width},s=o4;var h1="\x1B",a2="",r4=39,n3="\x07",n2="[",t4="]",s2="m",s3=`${t4}8;;`,d2=new RegExp(`(?:\\${n2}(?<code>\\d+)m|\\${s3}(?<uri>.*)${n3})`,"y"),u2=($)=>{if($>=30&&$<=37)return 39;if($>=90&&$<=97)return 39;if($>=40&&$<=47)return 49;if($>=100&&$<=107)return 49;if($===1||$===2)return 22;if($===3)return 23;if($===4)return 24;if($===7)return 27;if($===8)return 28;if($===9)return 29;if($===0)return 0;return},l2=($)=>`${h1}${n2}${$}${s2}`,i2=($)=>`${h1}${s3}${$}${n3}`,a3=($,Z,J)=>{let z=Z[Symbol.iterator](),Y=!1,Q=!1,G=$.at(-1),W=G===void 0?0:s(G),X=z.next(),K=z.next(),j=0;while(!X.done){let H=X.value,M=s(H);if(W+M<=J)$[$.length-1]+=H;else $.push(H),W=0;if(H===h1||H===a2)Y=!0,Q=Z.startsWith(s3,j+1);if(Y){if(Q){if(H===n3)Y=!1,Q=!1}else if(H===s2)Y=!1}else if(W+=M,W===J&&!K.done)$.push(""),W=0;X=K,K=z.next(),j+=H.length}if(G=$.at(-1),!W&&G!==void 0&&G.length&&$.length>1)$[$.length-2]+=$.pop()},e4=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(s(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},$8=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let z="",Y,Q,G=$.split(" "),W=[""],X=0;for(let H=0;H<G.length;H++){let M=G[H];if(J.trim!==!1){let q=W.at(-1)??"",B=q.trimStart();if(q.length!==B.length)W[W.length-1]=B,X=s(B)}if(H!==0){if(X>=Z&&(J.wordWrap===!1||J.trim===!1))W.push(""),X=0;if(X||J.trim===!1)W[W.length-1]+=" ",X++}let D=s(M);if(J.hard&&D>Z){let q=Z-X,B=1+Math.floor((D-q-1)/Z);if(Math.floor((D-1)/Z)<B)W.push("");a3(W,M,Z),X=s(W.at(-1)??"");continue}if(X+D>Z&&X&&D){if(J.wordWrap===!1&&X<Z){a3(W,M,Z),X=s(W.at(-1)??"");continue}W.push(""),X=0}if(X+D>Z&&J.wordWrap===!1){a3(W,M,Z),X=s(W.at(-1)??"");continue}W[W.length-1]+=M,X+=D}if(J.trim!==!1)W=W.map((H)=>e4(H));let K=W.join(`
|
|
21
|
+
`),j=!1;for(let H=0;H<K.length;H++){let M=K[H];if(z+=M,!j){if(j=M>="\uD800"&&M<="\uDBFF",j)continue}else j=!1;if(M===h1||M===a2){d2.lastIndex=H+1;let q=d2.exec(K)?.groups;if(q?.code!==void 0){let B=Number.parseFloat(q.code);Y=B===r4?void 0:B}else if(q?.uri!==void 0)Q=q.uri.length===0?void 0:q.uri}if(K[H+1]===`
|
|
22
|
+
`){if(Q)z+=i2("");let D=Y?u2(Y):void 0;if(Y&&D)z+=l2(D)}else if(M===`
|
|
23
|
+
`){if(Y&&u2(Y))z+=l2(Y);if(Q)z+=i2(Q)}}return z},Z8=/\r?\n/;function K0($,Z,J){return String($).normalize().split(Z8).map((z)=>$8(z,Z,J)).join(`
|
|
24
|
+
`)}var a=$9(r3(),1);import{ReadStream as r2}from"node:tty";function n0($,Z,J){if(!J.some((G)=>!G.disabled))return $;let z=$+Z,Y=Math.max(J.length-1,0),Q=z<0?Y:z>Y?0:z;return J[Q]?.disabled?n0(Q,Z<0?-1:1,J):Q}function y1($,Z,J,z){let Y=z.split(`
|
|
25
|
+
`),Q=0,G=$;for(let X of Y){if(G<=X.length)break;G-=X.length+1,Q++}for(Q=Math.max(0,Math.min(Y.length-1,Q+J)),G=Math.min(G,Y[Q].length)+Z;G<0&&Q>0;)Q--,G+=Y[Q].length+1;for(;G>Y[Q].length&&Q<Y.length-1;)G-=Y[Q].length+1,Q++;G=Math.max(0,Math.min(Y[Q].length,G));let W=0;for(let X=0;X<Q;X++)W+=Y[X].length+1;return W+G}var G8=["up","down","left","right","space","enter","cancel"],W8=["January","February","March","April","May","June","July","August","September","October","November","December"],d={actions:new Set(G8),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...W8],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:($,Z)=>`There are only ${$} days in ${Z}`,afterMin:($)=>`Date must be on or after ${$.toISOString().slice(0,10)}`,beforeMax:($)=>`Date must be on or before ${$.toISOString().slice(0,10)}`}}};function X8($){if($!==void 0)return $;if(d.accessible!==void 0)return d.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function Z$($,Z){if(typeof $=="string")return d.aliases.get($)===Z;for(let J of $)if(J!==void 0&&Z$(J,Z))return!0;return!1}function K8($,Z){if($===Z)return;let J=$.split(`
|
|
26
|
+
`),z=Z.split(`
|
|
27
|
+
`),Y=Math.max(J.length,z.length),Q=[];for(let G=0;G<Y;G++)J[G]!==z[G]&&Q.push(G);return{lines:Q,numLinesBefore:J.length,numLinesAfter:z.length,numLines:Y}}var H8=globalThis.process.platform.startsWith("win"),p1=Symbol("clack:cancel");function I0($){return $===p1}function m1($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}function J9({input:$=Z9,output:Z=$$,overwrite:J=!0,hideCursor:z=!0}={}){let Y=O0.createInterface({input:$,output:Z,prompt:"",tabSize:1});O0.emitKeypressEvents($,Y),$ instanceof r2&&$.isTTY&&$.setRawMode(!0);let Q=(G,{name:W,sequence:X})=>{let K=String(G);if(Z$([K,W,X],"cancel")){z&&Z.write(a.cursor.show),process.exit(0);return}if(!J)return;O0.moveCursor(Z,W==="return"?0:-1,W==="return"?-1:0,()=>{O0.clearLine(Z,1,()=>{$.once("keypress",Q)})})};return z&&Z.write(a.cursor.hide),$.once("keypress",Q),()=>{$.off("keypress",Q),z&&Z.write(a.cursor.show),$ instanceof r2&&$.isTTY&&!H8&&$.setRawMode(!1),Y.terminal=!1,Y.close()}}var G1=($)=>("columns"in $)&&typeof $.columns=="number"?$.columns:80,J$=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function W1($,Z,J,z=J,Y=J,Q){let G=G1($??$$);return K0(Z,G-J.length,{hard:!0,trim:!1}).split(`
|
|
28
|
+
`).map((W,X,K)=>{let j=Q?Q(W,X):W;return X===0?`${z}${j}`:X===K.length-1?`${Y}${j}`:`${J}${j}`}).join(`
|
|
29
|
+
`)}function z9($,Z){if("~standard"in $){let J=$["~standard"].validate(Z);return J instanceof Promise?J.then((z)=>z.issues?.at(0)?.message):J.issues?.at(0)?.message}return $(Z)}class P0{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return X8(this.opts.accessible)}constructor($,Z=!0){let{input:J=Z9,output:z=$$,render:Y,signal:Q,...G}=$;this.opts=G,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=Y.bind(this),this._track=Z,this._abortSignal=Q,this.input=J,this.output=z}unsubscribe(){this._subscribers.clear()}setSubscriber($,Z){let J=this._subscribers.get($)??[];J.push(Z),this._subscribers.set($,J)}on($,Z){this.setSubscriber($,{cb:Z})}once($,Z){this.setSubscriber($,{cb:Z,once:!0})}emit($,...Z){let J=this._subscribers.get($)??[],z=[];for(let Y of J)Y.cb(...Z),Y.once&&z.push(()=>J.splice(J.indexOf(Y),1));for(let Y of z)Y()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(p1);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Q8.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),m1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(a.cursor.show),this.output.off("resize",this.render),m1(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(a.cursor.show),this.output.off("resize",this.render),m1(this.input,!1),$(p1)})})}_isActionKey($,Z){return $==="\t"}_shouldSubmit($,Z){return!0}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,Z){this.userInput=$??"",this.emit("userInput",this.userInput),Z&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress($,Z){if(this.state!=="validating"){if(this._track&&Z.name!=="return"&&(Z.name&&this._isActionKey($,Z)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),Z?.name&&(!this._track&&d.aliases.has(Z.name)&&this.emit("cursor",d.aliases.get(Z.name)),d.actions.has(Z.name)&&this.emit("cursor",Z.name)),$&&($.toLowerCase()==="y"||$.toLowerCase()==="n")&&this.emit("confirm",$.toLowerCase()==="y"),this.emit("key",$,Z),Z?.name==="return"&&this._shouldSubmit($,Z)){if(this.opts.validate){let J=z9(this.opts.validate,this.value),z;J instanceof Promise?(this.state="validating",this.render(),z=await J):z=J,z&&(this.error=z instanceof Error?z.message:z,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Z$([$,Z?.name,Z?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
30
|
+
`),m1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=K0(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
31
|
+
`).length-1;this.output.write(a.cursor.move(-999,$*-1))}render(){let $=K0(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write(a.cursor.hide);else{let Z=K8(this._prevFrame,$),J=J$(this.output);if(this.restoreCursor(),Z){let z=Math.max(0,Z.numLinesAfter-J),Y=Math.max(0,Z.numLinesBefore-J),Q=Z.lines.find((G)=>G>=z);if(Q===void 0){this._prevFrame=$;return}if(Z.lines.length===1){this.output.write(a.cursor.move(0,Q-Y)),this.output.write(a.erase.lines(1));let G=$.split(`
|
|
32
|
+
`);this.output.write(G[Q]),this._prevFrame=$,this.output.write(a.cursor.move(0,G.length-Q-1));return}else if(Z.lines.length>1){if(z<Y)Q=z;else{let W=Q-Y;W>0&&this.output.write(a.cursor.move(0,W))}this.output.write(a.erase.down());let G=$.split(`
|
|
33
|
+
`).slice(Q);this.output.write(G.join(`
|
|
34
|
+
`)),this._prevFrame=$;return}}this.output.write(a.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function j8($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function U8($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function q8($,Z){if(Z)return $?Z:Z[0]}var V8=class extends P0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Z="";#J;#Q;#K;#Y;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return c1(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let Z=this.userInput.slice(0,this.cursor),J=this.userInput.slice(this.cursor,this.cursor+1),z=this.userInput.slice(this.cursor+1);return`${Z}${c1("inverse",J)}${z}`}get options(){return typeof this.#Q=="function"?this.#Q():this.#Q}constructor(Z){super(Z),this.#Q=Z.options,this.#K=Z.placeholder,this.#Y=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#J=typeof Z.options=="function"?Z.filter:Z.filter??U8;let z;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?z=Z.initialValue:z=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(z=[this.options[0]?.value]),z)for(let Y of z){let Q=J.findIndex((G)=>G.value===Y);Q!==-1&&(this.toggleSelected(Y),this.#$=Q)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Y,Q)=>this.#z(Y,Q)),this.on("userInput",(Y)=>this.#W(Y))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#z(Z,J){let z=J.name==="up",Y=J.name==="down",Q=J.name==="return",G=this.userInput===""||this.userInput==="\t",W=this.#K,X=this.options,K=W!==void 0&&W!==""&&X.some((j)=>!j.disabled&&(this.#J?this.#J(W,j):!0));if(J.name==="tab"&&G&&K){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#Y&&!this.multiple&&this.focusedValue!==void 0){let j=String(this.focusedValue);this._clearUserInput(),this._setUserInput(j,!0),this.isNavigating=!1;return}z||Y?(this.#$=n0(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):Q?this.value=q8(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((J)=>J!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#W(Z){if(Z!==this.#Z){this.#Z=Z;let J=this.options;Z&&this.#J?this.filteredOptions=J.filter((Q)=>this.#J?.(Z,Q)):this.filteredOptions=[...J];let z=j8(this.focusedValue,this.filteredOptions);this.#$=n0(z,0,this.filteredOptions);let Y=this.filteredOptions[this.#$];Y&&!Y.disabled?this.focusedValue=Y.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class z$ extends P0{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor($){super($,!1),this.value=!!$.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(Z)=>{this.output.write(a.cursor.move(0,-1)),this.value=Z,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var M8={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function t2($){return[...$].map((Z)=>M8[Z])}function D8($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let Y of Z)Y.type==="literal"?z=Y.value.trim()||Y.value:(Y.type==="year"||Y.type==="month"||Y.type==="day")&&J.push({type:Y.type,len:Y.type==="year"?4:2});return{segments:J,separator:z}}function t3($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function v1($){return{year:t3($.year),month:t3($.month),day:t3($.day)}}function e3($,Z){return new Date($||2001,Z||1,0).getDate()}function Y9($){let{year:Z,month:J,day:z}=v1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let Y=new Date(Date.UTC(Z,J-1,z));if(!(Y.getUTCFullYear()!==Z||Y.getUTCMonth()!==J-1||Y.getUTCDate()!==z))return{year:Z,month:J,day:z}}function e2($){let Z=Y9($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function F8($,Z,J,z){let Y=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,Q=z?{year:z.getUTCFullYear(),month:z.getUTCMonth()+1,day:z.getUTCDate()}:null;return $==="year"?{min:Y?.year??1,max:Q?.year??9999}:$==="month"?{min:Y&&Z.year===Y.year?Y.month:1,max:Q&&Z.year===Q.year?Q.month:12}:{min:Y&&Z.year===Y.year&&Z.month===Y.month?Y.day:1,max:Q&&Z.year===Q.year&&Z.month===Q.month?Q.day:e3(Z.year,Z.month)}}class Q9 extends P0{#$;#Z;#J;#Q;#K;#Y={segmentIndex:0,positionInSegment:0};#z=!0;#W=null;inlineError="";get segmentCursor(){return{...this.#Y}}get segmentValues(){return{...this.#J}}get segments(){return this.#$}get separator(){return this.#Z}get formattedValue(){return this.#U(this.#J)}#U($){return this.#$.map((Z)=>$[Z.type]).join(this.#Z)}#X(){this._setUserInput(this.#U(this.#J)),this._setValue(e2(this.#J)??void 0)}constructor($){let Z=$.format?{segments:t2($.format),separator:$.separator??"/"}:D8($.locale),J=$.separator??Z.separator,z=$.format?t2($.format):Z.segments,Y=$.initialValue??$.defaultValue,Q=Y?{year:String(Y.getUTCFullYear()).padStart(4,"0"),month:String(Y.getUTCMonth()+1).padStart(2,"0"),day:String(Y.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},G=z.map((W)=>Q[W.type]).join(J);super({...$,initialUserInput:G},!1),this.#$=z,this.#Z=J,this.#J=Q,this.#Q=$.minDate,this.#K=$.maxDate,this.#X(),this.on("cursor",(W)=>this.#q(W)),this.on("key",(W,X)=>this.#V(W,X)),this.on("finalize",()=>this.#D($))}#G(){let $=Math.max(0,Math.min(this.#Y.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#Y.positionInSegment=Math.max(0,Math.min(this.#Y.positionInSegment,Z.len-1)),{segment:Z,index:$}}#H($){this.inlineError="",this.#W=null;let Z=this.#G();Z&&(this.#Y.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#Y.positionInSegment=0,this.#z=!0)}#j($){let Z=this.#G();if(!Z)return;let{segment:J}=Z,z=this.#J[J.type],Y=!z||z.replace(/_/g,"")==="",Q=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,G=F8(J.type,v1(this.#J),this.#Q,this.#K),W;Y?W=$===1?G.min:G.max:W=Math.max(Math.min(G.max,Q+$),G.min),this.#J={...this.#J,[J.type]:W.toString().padStart(J.len,"0")},this.#z=!0,this.#W=null,this.#X()}#q($){if($)switch($){case"right":return this.#H(1);case"left":return this.#H(-1);case"up":return this.#j(1);case"down":return this.#j(-1)}}#V($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#G();if(!J)return;if(!this.#J[J.segment.type].replace(/_/g,"")){this.#H(-1);return}this.#J[J.segment.type]="_".repeat(J.segment.len),this.#z=!0,this.#Y.positionInSegment=0,this.#X();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#G();if(!J)return;let z=Z.shift?-1:1,Y=J.index+z;Y>=0&&Y<this.#$.length&&(this.#Y.segmentIndex=Y,this.#Y.positionInSegment=0,this.#z=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#G();if(!J)return;let{segment:z}=J,Y=!this.#J[z.type].replace(/_/g,"");if(this.#z&&this.#W!==null&&!Y){let M=this.#W+$,D={...this.#J,[z.type]:M},q=this.#M(D,z);if(q){this.inlineError=q,this.#W=null,this.#z=!1;return}this.inlineError="",this.#J[z.type]=M,this.#W=null,this.#z=!1,this.#X(),J.index<this.#$.length-1&&(this.#Y.segmentIndex=J.index+1,this.#Y.positionInSegment=0,this.#z=!0);return}this.#z&&!Y&&(this.#J[z.type]="_".repeat(z.len),this.#Y.positionInSegment=0),this.#z=!1,this.#W=null;let Q=this.#J[z.type],G=Q.indexOf("_"),W=G>=0?G:Math.min(this.#Y.positionInSegment,z.len-1);if(W<0||W>=z.len)return;let X=Q.slice(0,W)+$+Q.slice(W+1),K=!1;if(W===0&&Q==="__"&&(z.type==="month"||z.type==="day")){let M=Number.parseInt($,10);X=`0${$}`,K=M<=(z.type==="month"?1:2)}if(z.type==="year"&&(X=(Q.replace(/_/g,"")+$).padStart(z.len,"_")),!X.includes("_")){let M={...this.#J,[z.type]:X},D=this.#M(M,z);if(D){this.inlineError=D;return}}this.inlineError="",this.#J[z.type]=X;let j=X.includes("_")?void 0:Y9(this.#J);if(j){let{year:M,month:D}=j,q=e3(M,D);this.#J={year:String(Math.max(0,Math.min(9999,M))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,D))).padStart(2,"0"),day:String(Math.max(1,Math.min(q,j.day))).padStart(2,"0")}}this.#X();let H=X.indexOf("_");K?(this.#z=!0,this.#W=$):H>=0?this.#Y.positionInSegment=H:G>=0&&J.index<this.#$.length-1?(this.#Y.segmentIndex=J.index+1,this.#Y.positionInSegment=0,this.#z=!0):this.#Y.positionInSegment=Math.min(W+1,z.len-1)}}#M($,Z){let{month:J,day:z}=v1($);if(Z.type==="month"&&(J<0||J>12))return d.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return d.date.messages.invalidDay(31,"any month")}#D($){let{year:Z,month:J,day:z}=v1(this.#J);if(Z&&J&&z){let Y=e3(Z,J);this.#J={...this.#J,day:String(Math.min(z,Y)).padStart(2,"0")}}this.value=e2(this.#J)??$.defaultValue??void 0}}var L8=class extends P0{options;cursor=0;#$;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),z=this.value;return z===void 0?!1:J.every((Y)=>z.includes(Y.value))}toggleValue(){let Z=this.options[this.cursor];if(Z!==void 0)if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,z=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter((Y)=>z.findIndex((Q)=>Q.value===Y)===-1):this.value=[...this.value,...z.map((Y)=>Y.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((z)=>z!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#$=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([z,Y])=>[{value:z,group:!0,label:z},...Y.map((Q)=>({...Q,group:z}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:z})=>z===Z.cursorAt),this.#$?0:1),this.on("cursor",(z)=>{switch(z){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Y=this.options[this.cursor]?.group===!0;!this.#$&&Y&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Y=this.options[this.cursor]?.group===!0;!this.#$&&Y&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},B8=new Set(["up","down","left","right"]);class G9 extends P0{#$=!1;#Z;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${$}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),z=$.slice(this.cursor+1);return J===`
|
|
35
35
|
`?`${Z}█
|
|
36
|
-
${
|
|
36
|
+
${z}`:`${Z}${c1("inverse",J)}${z}`}get cursor(){return this._cursor}#J($){if(this.userInput.length===0){this._setUserInput($);return}this._setUserInput(this.userInput.slice(0,this.cursor)+$+this.userInput.slice(this.cursor))}#Q($){let Z=this.value??"";switch($){case"up":this._cursor=y1(this._cursor,0,-1,Z);return;case"down":this._cursor=y1(this._cursor,0,1,Z);return;case"left":this._cursor=y1(this._cursor,-1,0,Z);return;case"right":this._cursor=y1(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#Z)return this.focused==="submit"?!0:(this.#J(`
|
|
37
37
|
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
38
|
-
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#
|
|
39
|
-
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#
|
|
40
|
-
`);
|
|
38
|
+
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#J(`
|
|
39
|
+
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#Z=$.showSubmit??!1,this.on("key",(J,z)=>{if(z?.name&&B8.has(z.name)){this.#$=!1,this.#Q(z.name);return}if(J==="\t"&&this.#Z){this.focused=this.focused==="editor"?"submit":"editor";return}if(z?.name!=="return"){if(this.#$=!1,z?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(z?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}J&&(this.#Z&&this.focused==="submit"&&(this.focused="editor"),this.#J(J??""),this._cursor++)}}),this.on("userInput",(J)=>{this._setValue(J)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}class Y$ extends P0{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(($)=>$.disabled!==!0)}toggleAll(){let $=this._enabledOptions,Z=this.value!==void 0&&this.value.length===$.length;this.value=Z?[]:$.map((J)=>J.value)}toggleInvert(){let $=this.value;if(!$)return;let Z=this._enabledOptions.filter((J)=>!$.includes(J.value));this.value=Z.map((J)=>J.value)}toggleValue(){this.value===void 0&&(this.value=[]);let $=this.value.includes(this._value);this.value=$?this.value.filter((Z)=>Z!==this._value):[...this.value,this._value]}constructor($){super($,!1),this.options=$.options,this.value=[...$.initialValues??[]];let Z=Math.max(this.options.findIndex(({value:J})=>J===$.cursorAt),0);this.cursor=this.options[Z]?.disabled?n0(Z,1,this.options):Z,this.on("key",(J,z)=>{z.name==="a"&&this.toggleAll(),z.name==="i"&&this.toggleInvert()}),this.on("cursor",(J)=>{switch(J){case"left":case"up":this.cursor=n0(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=n0(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Q$ extends P0{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${this.userInput}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),z=$.slice(this.cursor+1);return`${Z}${c1("inverse",J)}${z}`}get cursor(){return this._cursor}constructor($){super({...$,initialUserInput:$.initialUserInput??$.initialValue}),this.on("userInput",(Z)=>{this._setValue(Z)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as V,stripVTControlCharacters as vJ}from"node:util";import J0 from"node:process";var K1=$9(r3(),1);function N8(){if(J0.platform!=="win32")return J0.env.TERM!=="linux";return Boolean(J0.env.CI)||Boolean(J0.env.WT_SESSION)||Boolean(J0.env.TERMINUS_SUBLIME)||J0.env.ConEmuTask==="{cmd::Cmder}"||J0.env.TERM_PROGRAM==="Terminus-Sublime"||J0.env.TERM_PROGRAM==="vscode"||J0.env.TERM==="xterm-256color"||J0.env.TERM==="alacritty"||J0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var G$=N8(),O8=()=>process.env.CI==="true";var g=($,Z)=>G$?$:Z,W9=g("◆","*"),M9=g("■","x"),D9=g("▲","x"),d1=g("◇","o"),I8=g("┌","T"),f=g("│","|"),C0=g("└","—"),uJ=g("┐","T"),lJ=g("┘","—"),X9=g("●",">"),K9=g("○"," "),P8=g("◻","[•]"),H9=g("◼","[+]"),j9=g("◻","[ ]"),iJ=g("▪","•"),U9=g("─","-"),C8=g("╮","+"),R8=g("├","+"),b8=g("╯","+"),A8=g("╰","+"),aJ=g("╭","+"),k8=g("●","•"),_8=g("◆","*"),f8=g("▲","!"),E8=g("■","x"),W$=($)=>{switch($){case"initial":case"active":return V("cyan",W9);case"cancel":return V("red",M9);case"error":return V("yellow",D9);case"submit":return V("green",d1);case"validating":return V("dim",W9)}},S8=($)=>{switch($){case"initial":case"active":return V("cyan",f);case"cancel":return V("red",f);case"error":return V("yellow",f);case"submit":return V("green",f)}};function x8($,Z){let J=[`${Z?`${V("cyan",f)} `:""}${$.join(" • ")}`];return Z&&J.push(V("cyan",C0)),J}var q9=($,Z,J,z,Y,Q=!1)=>{let G=Z,W=0;if(Q)for(let X=z-1;X>=J;X--){let K=$[X];if(K&&(G-=K.length),W++,G<=Y)break}else for(let X=J;X<z;X++){let K=$[X];if(K&&(G-=K.length),W++,G<=Y)break}return{lineCount:G,removals:W}},V9=({cursor:$,options:Z,style:J,output:z=process.stdout,maxItems:Y=Number.POSITIVE_INFINITY,columnPadding:Q=0,rowPadding:G=4})=>{let W=G1(z)-Q,X=J$(z),K=V("dim","..."),j=Math.max(X-G,0),H=Math.max(Math.min(Y,j),5),M=0;$>=H-3&&(M=Math.max(Math.min($-H+3,Z.length-H),0));let D=H<Z.length&&M>0,q=H<Z.length&&M+H<Z.length,B=Math.min(M+H,Z.length),N=[],x=0;D&&x++,q&&x++;let m=M+(D?1:0),p=B-(q?1:0);for(let U=m;U<p;U++){let P=Z[U],I=P?J(P,U===$):"",E=K0(I,W,{hard:!0,trim:!1}).split(`
|
|
40
|
+
`);N.push(E),x+=E.length}if(x>j){let U=0,P=0,I=x,E=$-m,S=j,h=()=>q9(N,I,0,E,S),T=()=>q9(N,I,E+1,N.length,S,!0);D?({lineCount:I,removals:U}=h(),I>S&&(q||(S-=1),{lineCount:I,removals:P}=T())):(q||(S-=1),{lineCount:I,removals:P}=T(),I>S&&(S-=1,{lineCount:I,removals:U}=h())),U>0&&(D=!0,N.splice(0,U)),P>0&&(q=!0,N.splice(N.length-P,P))}let F=[];D&&F.push(K);for(let U of N)for(let P of U)F.push(P);return q&&F.push(K),F};var X$=($)=>{let Z=$.active??"Yes",J=$.inactive??"No";return new z$({active:Z,inactive:J,signal:$.signal,input:$.input,output:$.output,initialValue:$.initialValue??!0,render(){let z=$.withGuide??d.withGuide,Y=`${W$(this.state)} `,Q=z?`${V("gray",f)} `:"",G=W1($.output,$.message,Q,Y),W=`${z?`${V("gray",f)}
|
|
41
41
|
`:""}${G}
|
|
42
|
-
`,X=this.value?Z:J;switch(this.state){case"submit":{let K=
|
|
43
|
-
${V("gray",f)}`:""}`}default:{let K=
|
|
42
|
+
`,X=this.value?Z:J;switch(this.state){case"submit":{let K=z?`${V("gray",f)} `:"";return`${W}${K}${V("dim",X)}`}case"cancel":{let K=z?`${V("gray",f)} `:"";return`${W}${K}${V(["strikethrough","dim"],X)}${z?`
|
|
43
|
+
${V("gray",f)}`:""}`}default:{let K=z?`${V("cyan",f)} `:"",j=z?V("cyan",C0):"";return`${W}${K}${this.value?`${V("green",X9)} ${Z}`:`${V("dim",K9)} ${V("dim",Z)}`}${$.vertical?z?`
|
|
44
44
|
${V("cyan",f)} `:`
|
|
45
|
-
`:` ${V("dim","/")} `}${this.value?`${V("dim",
|
|
46
|
-
${
|
|
47
|
-
`}}}}).prompt()};var
|
|
45
|
+
`:` ${V("dim","/")} `}${this.value?`${V("dim",K9)} ${V("dim",J)}`:`${V("green",X9)} ${J}`}
|
|
46
|
+
${j}
|
|
47
|
+
`}}}}).prompt()};var w8=[`${V("dim","↑/↓")} to navigate`,`${V("dim","Space:")} select`,`${V("dim","Enter:")} confirm`],X1=($,Z)=>$.split(`
|
|
48
48
|
`).map((J)=>Z(J)).join(`
|
|
49
|
-
`),
|
|
50
|
-
${V("reset",V("dim",`Press ${V(["gray","bgWhite","inverse"]," space ")} to select, ${V("gray",V("bgWhite",V("inverse"," enter ")))} to submit`))}`},render(){let
|
|
51
|
-
`:""}${
|
|
52
|
-
`,W=this.value??[],X=(K,
|
|
53
|
-
${V("gray",f)}`:""}`}case"error":{let K=
|
|
54
|
-
`).map((
|
|
55
|
-
`),
|
|
56
|
-
`).length,
|
|
57
|
-
`).length+1;return`${G}${K}${
|
|
49
|
+
`),F9=($)=>{let Z=(Y,Q)=>{let G=Y.label??String(Y.value);return Q==="disabled"?`${V("gray",j9)} ${X1(G,(W)=>V(["strikethrough","gray"],W))}${Y.hint?` ${V("dim",`(${Y.hint??"disabled"})`)}`:""}`:Q==="active"?`${V("cyan",P8)} ${G}${Y.hint?` ${V("dim",`(${Y.hint})`)}`:""}`:Q==="selected"?`${V("green",H9)} ${X1(G,(W)=>V("dim",W))}${Y.hint?` ${V("dim",`(${Y.hint})`)}`:""}`:Q==="cancelled"?`${X1(G,(W)=>V(["strikethrough","dim"],W))}`:Q==="active-selected"?`${V("green",H9)} ${G}${Y.hint?` ${V("dim",`(${Y.hint})`)}`:""}`:Q==="submitted"?`${X1(G,(W)=>V("dim",W))}`:`${V("dim",j9)} ${X1(G,(W)=>V("dim",W))}`},J=$.required??!0,z=$.showInstructions??!0;return new Y$({options:$.options,signal:$.signal,input:$.input,output:$.output,initialValues:$.initialValues,required:J,cursorAt:$.cursorAt,validate(Y){if(J&&(Y===void 0||Y.length===0))return`Please select at least one option.
|
|
50
|
+
${V("reset",V("dim",`Press ${V(["gray","bgWhite","inverse"]," space ")} to select, ${V("gray",V("bgWhite",V("inverse"," enter ")))} to submit`))}`},render(){let Y=$.withGuide??d.withGuide,Q=W1($.output,$.message,Y?`${S8(this.state)} `:"",`${W$(this.state)} `),G=`${Y?`${V("gray",f)}
|
|
51
|
+
`:""}${Q}
|
|
52
|
+
`,W=this.value??[],X=(K,j)=>{if(K.disabled)return Z(K,"disabled");let H=W.includes(K.value);return j&&H?Z(K,"active-selected"):H?Z(K,"selected"):Z(K,j?"active":"inactive")};switch(this.state){case"submit":{let K=this.options.filter(({value:H})=>W.includes(H)).map((H)=>Z(H,"submitted")).join(V("dim",", "))||V("dim","none"),j=W1($.output,K,Y?`${V("gray",f)} `:"");return`${G}${j}`}case"cancel":{let K=this.options.filter(({value:H})=>W.includes(H)).map((H)=>Z(H,"cancelled")).join(V("dim",", "));if(K.trim()==="")return`${G}${V("gray",f)}`;let j=W1($.output,K,Y?`${V("gray",f)} `:"");return`${G}${j}${Y?`
|
|
53
|
+
${V("gray",f)}`:""}`}case"error":{let K=Y?`${V("yellow",f)} `:"",j=this.error.split(`
|
|
54
|
+
`).map((D,q)=>q===0?`${Y?`${V("yellow",C0)} `:""}${V("yellow",D)}`:` ${D}`).join(`
|
|
55
|
+
`),H=G.split(`
|
|
56
|
+
`).length,M=j.split(`
|
|
57
|
+
`).length+1;return`${G}${K}${V9({output:$.output,options:this.options,cursor:this.cursor,maxItems:$.maxItems,columnPadding:K.length,rowPadding:H+M,style:X}).join(`
|
|
58
58
|
${K}`)}
|
|
59
|
-
${
|
|
60
|
-
`}default:{let K=
|
|
61
|
-
`).length,
|
|
62
|
-
`),
|
|
59
|
+
${j}
|
|
60
|
+
`}default:{let K=Y?`${V("cyan",f)} `:"",j=G.split(`
|
|
61
|
+
`).length,H=z?x8(w8,Y):Y?[V("cyan",C0)]:[],M=H.join(`
|
|
62
|
+
`),D=H.length+1;return`${G}${K}${V9({output:$.output,options:this.options,cursor:this.cursor,maxItems:$.maxItems,columnPadding:K.length,rowPadding:j+D,style:X}).join(`
|
|
63
63
|
${K}`)}
|
|
64
|
-
${
|
|
65
|
-
`}}}}).prompt()};var y={message:($=[],{symbol:Z=V("gray",f),secondarySymbol:J=V("gray",f),output:
|
|
66
|
-
`);if(
|
|
64
|
+
${M}
|
|
65
|
+
`}}}}).prompt()};var y={message:($=[],{symbol:Z=V("gray",f),secondarySymbol:J=V("gray",f),output:z=process.stdout,spacing:Y=1,withGuide:Q}={})=>{let G=[],W=Q??d.withGuide,X=W?J:"",K=W?`${Z} `:"",j=W?`${J} `:"";for(let M=0;M<Y;M++)G.push(X);let H=Array.isArray($)?$:$.split(`
|
|
66
|
+
`);if(H.length>0){let[M,...D]=H;M.length>0?G.push(`${K}${M}`):G.push(W?Z:"");for(let q of D)q.length>0?G.push(`${j}${q}`):G.push(W?J:"")}z.write(`${G.join(`
|
|
67
67
|
`)}
|
|
68
|
-
`)},info:($,Z)=>{y.message($,{...Z,symbol:V("blue",
|
|
69
|
-
`)},
|
|
70
|
-
${V("gray",C0)} `:"";J.write(`${
|
|
68
|
+
`)},info:($,Z)=>{y.message($,{...Z,symbol:V("blue",k8)})},success:($,Z)=>{y.message($,{...Z,symbol:V("green",_8)})},step:($,Z)=>{y.message($,{...Z,symbol:V("green",d1)})},warn:($,Z)=>{y.message($,{...Z,symbol:V("yellow",f8)})},warning:($,Z)=>{y.warn($,Z)},error:($,Z)=>{y.message($,{...Z,symbol:V("red",E8)})}};var L9=($="",Z)=>{let J=Z?.output??process.stdout,z=Z?.withGuide??d.withGuide?`${V("gray",I8)} `:"";J.write(`${z}${$}
|
|
69
|
+
`)},H0=($="",Z)=>{let J=Z?.output??process.stdout,z=Z?.withGuide??d.withGuide?`${V("gray",f)}
|
|
70
|
+
${V("gray",C0)} `:"";J.write(`${z}${$}
|
|
71
71
|
|
|
72
|
-
`)};var
|
|
73
|
-
`),Y
|
|
74
|
-
`).map(
|
|
75
|
-
`),
|
|
76
|
-
`:"",
|
|
72
|
+
`)};var T8=($)=>$,g8=($,Z,J)=>{let z={hard:!0,trim:!1},Y=K0($,Z,z).split(`
|
|
73
|
+
`),Q=Y.reduce((X,K)=>Math.max(s(K),X),0),G=Y.map(J).reduce((X,K)=>Math.max(s(K),X),0),W=Z-(G-Q);return K0($,W,z)},u1=($="",Z="",J)=>{let z=J?.output??J0.stdout,Y=J?.withGuide??d.withGuide,Q=J?.format??T8,G=["",...g8($,G1(z)-6,Q).split(`
|
|
74
|
+
`).map(Q),""],W=s(Z),X=Math.max(G.reduce((M,D)=>{let q=s(D);return q>M?q:M},0),W)+2,K=G.map((M)=>`${V("gray",f)} ${M}${" ".repeat(X-s(M))}${V("gray",f)}`).join(`
|
|
75
|
+
`),j=Y?`${V("gray",f)}
|
|
76
|
+
`:"",H=Y?R8:A8;z.write(`${j}${V("green",d1)} ${V("reset",Z)} ${V("gray",U9.repeat(Math.max(X-W-1,1))+C8)}
|
|
77
77
|
${K}
|
|
78
|
-
${V("gray",
|
|
79
|
-
`)};var
|
|
80
|
-
`);let b=
|
|
81
|
-
`);b.length>1&&J.write(
|
|
82
|
-
`);let c=0,o=0;P(),
|
|
83
|
-
`):J.write(`${i} ${
|
|
84
|
-
`)),
|
|
85
|
-
`:""}${
|
|
86
|
-
`,
|
|
78
|
+
${V("gray",H+U9.repeat(X+2)+b8)}
|
|
79
|
+
`)};var h8=($)=>V("magenta",$),B9=({indicator:$="dots",onCancel:Z,output:J=process.stdout,cancelMessage:z,errorMessage:Y,frames:Q=G$?["◒","◐","◓","◑"]:["•","o","O","0"],delay:G=G$?80:120,signal:W,...X}={})=>{let K=O8(),j,H,M=!1,D=!1,q="",B,N=performance.now(),x=G1(J),m=X?.styleFrame??h8,p=(b)=>{let c=b>1?Y??d.messages.error:z??d.messages.cancel;D=b===1,M&&(_(c,b),D&&typeof Z=="function"&&Z())},F=()=>p(2),U=()=>p(1),P=()=>{process.on("uncaughtExceptionMonitor",F),process.on("unhandledRejection",F),process.on("SIGINT",U),process.on("SIGTERM",U),process.on("exit",p),W&&W.addEventListener("abort",U)},I=()=>{process.removeListener("uncaughtExceptionMonitor",F),process.removeListener("unhandledRejection",F),process.removeListener("SIGINT",U),process.removeListener("SIGTERM",U),process.removeListener("exit",p),W&&W.removeEventListener("abort",U)},E=()=>{if(B===void 0)return;K&&J.write(`
|
|
80
|
+
`);let b=K0(B,x,{hard:!0,trim:!1}).split(`
|
|
81
|
+
`);b.length>1&&J.write(K1.cursor.up(b.length-1)),J.write(K1.cursor.to(0)),J.write(K1.erase.down())},S=(b)=>b.replace(/\.+$/,""),h=(b)=>{let c=(performance.now()-b)/1000,o=Math.floor(c/60),i=Math.floor(c%60);return o>0?`[${o}m ${i}s]`:`[${i}s]`},T=X.withGuide??d.withGuide,k=(b="")=>{M=!0,j=J9({output:J}),q=S(b),N=performance.now(),T&&J.write(`${V("gray",f)}
|
|
82
|
+
`);let c=0,o=0;P(),H=setInterval(()=>{if(K&&q===B)return;E(),B=q;let i=m(Q[c]),j0;if(K)j0=`${i} ${q}...`;else if($==="timer")j0=`${i} ${q} ${h(N)}`;else{let z0=".".repeat(Math.floor(o)).slice(0,3);j0=`${i} ${q}${z0}`}let w=K0(j0,x,{hard:!0,trim:!1});J.write(w),c=c+1<Q.length?c+1:0,o=o<4?o+0.125:0},G)},_=(b="",c=0,o=!1)=>{if(!M)return;M=!1,clearInterval(H),E();let i=c===0?V("green",d1):c===1?V("red",M9):V("red",D9);q=b??q,o||($==="timer"?J.write(`${i} ${q} ${h(N)}
|
|
83
|
+
`):J.write(`${i} ${q}
|
|
84
|
+
`)),I(),j()};return{start:k,stop:(b="")=>_(b,0),message:(b="")=>{q=S(b??q)},cancel:(b="")=>_(b,1),error:(b="")=>_(b,2),clear:()=>_("",0,!0),get isCancelled(){return D}}},nJ={light:g("─","-"),heavy:g("━","="),block:g("█","#")};var sJ=[`${V("dim","↑/↓")} to navigate`,`${V("dim","Enter:")} confirm`];var oJ=`${V("gray",f)} `;var N9=($)=>new Q$({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??d.withGuide,J=`${`${Z?`${V("gray",f)}
|
|
85
|
+
`:""}${W$(this.state)} `}${$.message}
|
|
86
|
+
`,z=$.placeholder&&$.placeholder.length>0?V("inverse",$.placeholder[0])+V("dim",$.placeholder.slice(1)):V(["inverse","hidden"],"_"),Y=this.userInput?this.userInputWithCursor:z,Q=this.value??"";switch(this.state){case"validating":{let G=Z?`${V("cyan",f)} `:"",W=Z?V("cyan",C0):"",X=V("dim",Y),K=V("dim","Validating...");return`${J}${G}${X}
|
|
87
87
|
${W} ${K}
|
|
88
88
|
`}case"error":{let G=this.error?` ${V("yellow",this.error)}`:"",W=Z?`${V("yellow",f)} `:"",X=Z?V("yellow",C0):"";return`${J.trim()}
|
|
89
|
-
${W}${
|
|
89
|
+
${W}${Y}
|
|
90
90
|
${X}${G}
|
|
91
|
-
`}case"submit":{let G=
|
|
92
|
-
${W}`:""}`}default:{let G=Z?`${V("cyan",f)} `:"",W=Z?V("cyan",C0):"";return`${J}${G}${
|
|
91
|
+
`}case"submit":{let G=Q?`${Z?" ":""}${V("dim",Q)}`:"",W=Z?V("gray",f):"";return`${J}${W}${G}`}case"cancel":{let G=Q?` ${V(["strikethrough","dim"],Q)}`:"",W=Z?V("gray",f):"";return`${J}${W}${G}${Q.trim()?`
|
|
92
|
+
${W}`:""}`}default:{let G=Z?`${V("cyan",f)} `:"",W=Z?V("cyan",C0):"";return`${J}${G}${Y}
|
|
93
93
|
${W}
|
|
94
|
-
`}}}}).prompt();import{existsSync as
|
|
94
|
+
`}}}}).prompt();import{existsSync as s1}from"node:fs";import{join as o0}from"node:path";import{accessSync as y8,constants as O9,statSync as m8}from"node:fs";import{delimiter as v8,extname as c8,resolve as p8}from"node:path";function H1($,Z,J){let z=J==="win32",Y=z?[`${$}.exe`,`${$}.cmd`,`${$}.bat`,$]:[$];for(let Q of(Z.PATH??"").split(z?";":v8)){if(!Q)continue;for(let G of Y){let W=p8(Q,G);try{if(y8(W,z?O9.F_OK:O9.X_OK),m8(W).isFile())return W}catch{}}}return null}async function l1($,Z,J,z){if(!$)return null;let Y=c8($).toLowerCase(),Q=z==="win32"&&(Y===".cmd"||Y===".bat");try{return await J.run(Q?Z.ComSpec||Z.COMSPEC||"cmd.exe":$,Q?["/d","/s","/c",$,"--version"]:["--version"],{env:Z})}catch{return null}}import{existsSync as d8,readFileSync as u8}from"node:fs";import{applyEdits as I9,format as l8,modify as K$,parse as P9}from"jsonc-parser";function j1($){if(!d8($))return{value:null,text:"",exists:!1};let Z=u8($,"utf8"),J=[],z=P9(Z,J,{allowTrailingComma:!0});return{value:J.length===0?z:null,text:Z,exists:!0}}function H$($,Z,J,z){let Q=P9($,[],{allowTrailingComma:!0})??{};for(let H of Z)if(typeof Q==="object"&&Q!==null)Q=Q[H];else{Q=void 0;break}let G=Array.isArray(Q)?Q:[],W=G.findIndex((H)=>typeof H==="string"&&z(H));if(W!==-1&&G[W]===J)return{text:$,changed:!1};let X;if(W!==-1)X=K$($,[...Z,W],J,{formattingOptions:{insertSpaces:!0,tabSize:2}});else if(!Array.isArray(Q))X=K$($,Z,[J],{formattingOptions:{insertSpaces:!0,tabSize:2}});else X=K$($,[...Z,G.length],J,{formattingOptions:{insertSpaces:!0,tabSize:2}});let K=I9($,X);return{text:I9(K,l8(K,void 0,{insertSpaces:!0,tabSize:2})),changed:!0}}import{existsSync as i1}from"node:fs";import{mkdir as b9,writeFile as a1}from"node:fs/promises";import{join as n1}from"node:path";function A9($){return $===s0||$.startsWith(`${s0}@`)}function j$($){let Z=n1($,"opencode.jsonc");if(i1(Z))return{path:Z,exists:!0};let J=n1($,"opencode.json");if(i1(J))return{path:J,exists:!0};return{path:Z,exists:!1}}function i8($){let Z=n1($,"tui.jsonc");if(i1(Z))return{path:Z,exists:!0};let J=n1($,"tui.json");if(i1(J))return{path:J,exists:!0};return{path:Z,exists:!1}}async function k9($,Z=process.env){let J=x0(Z);await b9(J,{recursive:!0});let{path:z,exists:Y}=j$(J),Q=C9($);if(!Y){let K=`{
|
|
95
95
|
"$schema": "https://opencode.ai/config.json",
|
|
96
96
|
"plugin": [
|
|
97
|
-
"${
|
|
97
|
+
"${Q}"
|
|
98
98
|
]
|
|
99
99
|
}
|
|
100
|
-
`;return await
|
|
100
|
+
`;return await a1(z,K,"utf8"),{configPath:z,changed:!0,created:!0}}let{text:G}=j1(z),{text:W,changed:X}=H$(G,["plugin"],Q,A9);if(X)await a1(z,W,"utf8");return{configPath:z,changed:X,created:!1}}async function _9($,Z=process.env){let J=x0(Z);await b9(J,{recursive:!0});let{path:z,exists:Y}=i8(J),Q=R9($);if(!Y){let K=`{
|
|
101
101
|
"plugin": [
|
|
102
|
-
"${
|
|
102
|
+
"${Q}"
|
|
103
103
|
]
|
|
104
104
|
}
|
|
105
|
-
`;return await d1(Q,K,"utf8"),{configPath:Q,changed:!0,created:!0}}let{text:G}=W1(Q),{text:W,changed:X}=Q$(G,["plugin"],Y,M9);if(X)await d1(Q,W,"utf8");return{configPath:Q,changed:X,created:!1}}import{existsSync as N9}from"node:fs";import{readFile as x8,writeFile as dJ}from"node:fs/promises";import{join as w8}from"node:path";function B9($=process.env,Z=v0($)){let J=w8(Z,"settings.json");if(!N9(J))return!1;try{let z=JSON.parse(T8(J))?.packages;if(!Array.isArray(z))return!1;return z.some((Y)=>{let G=typeof Y==="string"?Y:typeof Y==="object"&&Y!==null?Y.source:"";if(typeof G!=="string")return!1;return G===X1||G.startsWith(`${X1}@`)||G===`npm:${X1}`||G.startsWith(`npm:${X1}@`)})}catch{return!1}}function T8($){return j1("node:fs").readFileSync($,"utf8")}async function I9($=process.env){let Z=k1($);if(!N9(Z))return!1;try{let J=await x8(Z,"utf8"),Q=JSON.parse(J);return Boolean(Q?.anthropic&&typeof Q.anthropic==="object")}catch{return!1}}async function O9($,Z=e,J=process.env){let Q=L9($),z=await Z.run("pi",["install",Q],{env:J});if(z.exitCode!==0)return{ok:!1,exitCode:z.exitCode,stderr:z.stderr};return{ok:!0,message:`Installed ${Q}`}}function g8($,Z){let J=C9($,Z),Q;switch(Z){case"darwin":Q=["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",i0(J,"Applications","OpenCode.app"),i0(J,"Applications","OpenCode Beta.app")];break;case"win32":{let z=$.LOCALAPPDATA??i0(J,"AppData","Local");Q=[i0(z,"Programs","opencode"),i0(z,"opencode")];break}case"linux":Q=["/opt/OpenCode","/usr/lib/opencode",i0(J,".local","share","applications","opencode.desktop")];break;default:Q=[]}return Q.some((z)=>l1(z))}async function h8($=process.env,Z=e,J={}){let Q=J.platform??process.platform,z=E0($,Q),Y=l1(z)||g8($,Q),G=G1("opencode",$,Q)??G1("opencode2",$,Q),W=Y||G!==null,X=await c1(G,$,Z,Q),K=X?.exitCode===0?X.stdout.trim()||null:null,{path:H,exists:j}=z$(z),U=!1;if(j){let{value:M}=W1(H);if(Array.isArray(M?.plugin))U=M.plugin.some((D)=>typeof D==="string"&&(D===l0||D.startsWith(`${l0}@`)))}return{kind:"opencode",installed:W,version:K,configPath:H,pluginInstalled:U}}async function y8($=process.env,Z=e,J={}){let Q=J.platform??process.platform,z=v0($,Q),Y=l1(z),G=G1("pi",$,Q),W=Y||G!==null,X=await c1(G,$,Z,Q),K=null;if(X?.exitCode===0){let U=X.stdout.trim()||X.stderr.trim();K=U.split(/\r?\n/).find((D)=>/^\d+\.\d+\.\d+/.test(D.trim()))?.trim()||U||null}let H=B9($,z),j=await I9($);return{kind:"pi",installed:W,version:K,configPath:z,pluginInstalled:H,hasLocalAuth:j}}async function m8($=process.env,Z=e,J={}){let Q=J.platform??process.platform,z=G1("ck",$,Q),Y=z!==null,G=await c1(z,$,Z,Q),W=G?.exitCode===0?G.stdout.trim()||null:null,X=null,K=!1;try{if(X=R1(void 0,$),X&&l1(X)){let H=await P9({connectionFile:X,handshakeTimeoutMs:2000});K=!0,H.close()}}catch{K=!1}return{ckInstalled:Y,ckVersion:W,daemonRunning:K,connectionPath:X}}async function R9($=process.env,Z=e,J={}){let[Q,z,Y]=await Promise.all([h8($,Z,J),y8($,Z,J),m8($,Z,J)]);return{opencode:Q,pi:z,claustrum:Y}}async function A9($,Z){let J={...Z.env},Q=async()=>{if(f1(J),await p0(Z.fence),await N0($,J)!=="local")throw Error("Disconnect from the vault first.")};await Q();let z=Z.paths??await c0($,J),Y=await Z.login?.($);if(Y&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(Y.accountIdentity))throw Error("Claude sign-in did not establish an account UUID");if(await Q(),await b9({paths:z.paths,legacyConfigPath:z.legacyConfigPath,legacyStatePath:z.legacyStatePath,host:$,hostAuthPath:z.hostAuthPath,routingSourcePath:z.routingSourcePath,routingDestinationPath:z.routingDestinationPath,env:J,processFence:Q,removePiAnthropicAuth:Z.removePiAnthropicAuth}),Y){let G=d0({paths:z.paths,host:$,vault:{env:J},beforePoolWrite:Q});try{if((await G.read()).mode!=="local")throw Error("Disconnect from the vault first.");await Q(),await G.loginOAuth({routeId:"main",replace:!0,...Y})}finally{G.close()}}}async function _9($){let Z=await i1("max");v1(Z.url,`Claude sign-in for ${$==="pi"?"Pi":"OpenCode"}`);let J=await X9({message:"Paste the Claude callback URL or authorization code:"});if(O0(J))throw Error("Claude sign-in cancelled");let Q=await a1(J,Z.verifier,Z.redirectUri,Z.state);if(Q.type!=="success")throw Error("Claude sign-in failed");let z=await k9(Q.access,void 0,void 0);if(!z.accountUuid)throw Error("Claude sign-in did not establish an account UUID");return{accountIdentity:z.accountUuid,credential:{type:"oauth",access:Q.access,refresh:Q.refresh,expires:Q.expires}}}async function E9($=[],Z={}){let J=Z.env??process.env,Q=Z.runner??e,z=Z.fence??w3,Y=Z.activate??H2,G=Z.migrateLocal??A9,W={output:Z.output},X=$.includes("--yes")||$.includes("-y"),K=$.includes("--dry-run"),H=$.includes("--no-claustrum"),j=$.includes("--claustrum"),U=$.includes("--remove-pi-auth"),M=$.includes("--login"),D=M?Z.localLogin??_9:void 0;if(M&&j)return y.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",W),1;G9("CortexKit Anthropic Auth Setup",W);let B=W9(W);B.start("Detecting installed environments…");let I=await(Z.detect??R9)(J,Q);B.stop("Environment detection complete.");let T=I.opencode.installed?`detected (${I.opencode.version??"version unknown"}, ${I.opencode.pluginInstalled?"plugin already configured":"plugin not configured"})`:"not found",m=I.pi.installed?`detected (${I.pi.version??"version unknown"}, ${I.pi.pluginInstalled?"extension already installed":"extension not installed"})`:"not found",p=I.claustrum.daemonRunning?`daemon running (${I.claustrum.ckVersion??"ck ready"})`:I.claustrum.ckInstalled?"ck installed, daemon not running":"not installed";if(y.info(`OpenCode: ${T}`,W),y.info(`Pi: ${m}`,W),y.info(`Claustrum: ${p}`,W),!I.opencode.installed&&!I.pi.installed)return y.error("Neither OpenCode nor Pi was detected on this system.",W),K0("Install OpenCode (https://opencode.ai) or Pi (https://github.com/badlogic/pi-mono) first.",W),1;let F=[];if(X){if(I.opencode.installed)F.push("opencode");if(I.pi.installed)F.push("pi")}else{let k=[];if(I.opencode.installed)k.push({value:"opencode",label:"OpenCode",hint:I.opencode.pluginInstalled?"already configured":"configure plugin + TUI sidebar"});if(I.pi.installed)k.push({value:"pi",label:"Pi",hint:I.pi.pluginInstalled?"already installed":"install provider extension"});let _=await Y9({message:"Select integrations to configure:",options:k,initialValues:k.map((b)=>b.value),required:!0,...W});if(O0(_))return K0("Setup cancelled.",W),0;F=_}if(F.length===0)return K0("No integrations selected.",W),0;let q=!1;if(I.claustrum.daemonRunning&&I.claustrum.ckInstalled&&!H){if(j)q=!0;else if(!X){let k=await Z$({message:"Use Claude accounts from the Claustrum vault? Local account files stay unchanged and are not used while connected.",initialValue:!1,...W});if(O0(k))return K0("Setup cancelled.",W),0;q=k}}if(D&&q)return y.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",W),1;if(D||!q){for(let k of F)if(await N0(k,J)!=="local")return y.error("Disconnect from the vault first.",W),1}let O=!1;if(F.includes("pi")&&I.pi.hasLocalAuth)if(X){if(!U)return y.error(q?"Pi has stored Anthropic authentication. Rerun with --remove-pi-auth to preserve it privately during vault use and restore it on disconnect.":"Pi has a stored Anthropic login. Rerun with --remove-pi-auth to move it into the native account pool.",W),K0("Setup aborted.",W),1;O=!0}else{y.warn(q?"Pi has stored Anthropic authentication. Vault setup must preserve it privately and restore it on disconnect.":"Pi has a stored Anthropic OAuth token. Native account-pool setup moves credentials out of the host auth store.",W);let k=await Z$({message:q?"Move Pi authentication aside privately for vault use, then restore it on disconnect?":"Move the Pi Anthropic OAuth login into the native account pool and remove its stored copy?",initialValue:!1,...W});if(O0(k)||!k)return y.error("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.",W),K0("Setup aborted.",W),1;O=!0}try{await p0(z)}catch(k){return y.error(await B0("setup-process-check",k,J),W),K0("Setup aborted — quit active hosts and rerun setup.",W),1}let E=[];for(let k of F)E.push(await c0(k,J));if(await W2(E),K){if(y.info("[dry-run] Planned actions:",W),y.info(` - Target integrations: ${F.join(", ")}`,W),y.info(` - Claustrum custody: ${q?"enabled":"disabled"}`,W),O)y.info(" - Pi local OAuth token will be removed",W);return K0("Dry run complete. No changes were made.",W),0}let S=await f9(),h=async(k,_)=>{B.start(`Switching ${_} to Claustrum vault custody…`);try{let b=await Y(k,{env:J,runner:Q,fence:z,removePiAnthropicAuth:k==="pi"&&O});return B.stop(b==="already-vault"?`${_} already uses Claustrum vault custody.`:`${_} now uses Claustrum vault custody.`),!0}catch(b){return B.stop(`${_} vault custody setup failed.`),y.error(await B0("setup-activation",b,J),W),!1}};if(F.includes("opencode")){B.start("Configuring OpenCode plugin and TUI sidebar…");try{await D9(S,J),await F9(S,J),B.stop("OpenCode configuration updated.")}catch(k){return B.stop("OpenCode setup failed."),y.error(await B0("setup-opencode-config",k,J),W),1}if(D||!q)await G("opencode",{env:J,fence:z,removePiAnthropicAuth:!1,login:D});if(q&&!await h("opencode","OpenCode"))return 1}if(F.includes("pi")){B.start("Installing Pi Anthropic extension…");try{let k=await O9(S,Q,J);if(!k.ok)return B.stop("Pi extension installation failed."),y.error(await P2("setup-pi-install",k,J),W),1;B.stop("Pi Anthropic extension installed.")}catch(k){return B.stop("Pi setup failed."),y.error(await B0("setup-pi",k,J),W),1}if(D||!q)await G("pi",{env:J,fence:z,removePiAnthropicAuth:O,login:D});if(q&&!await h("pi","Pi"))return 1}let w=[];if(F.includes("opencode"))w.push("• Start OpenCode normally (opencode).");if(F.includes("pi"))w.push("• Start Pi normally (pi).");if(q)w.push("• Manage accounts in Claustrum with: ck auth login --provider anthropic"),w.push(" Newly added accounts will be discovered automatically without restarting.");return v1(w.join(`
|
|
106
|
-
`),"Next Steps",W),
|
|
105
|
+
`;return await a1(z,K,"utf8"),{configPath:z,changed:!0,created:!0}}let{text:G}=j1(z),{text:W,changed:X}=H$(G,["plugin"],Q,A9);if(X)await a1(z,W,"utf8");return{configPath:z,changed:X,created:!1}}import{existsSync as E9}from"node:fs";import{readFile as a8,writeFile as qz}from"node:fs/promises";import{join as n8}from"node:path";function S9($=process.env,Z=u0($)){let J=n8(Z,"settings.json");if(!E9(J))return!1;try{let Y=JSON.parse(s8(J))?.packages;if(!Array.isArray(Y))return!1;return Y.some((Q)=>{let G=typeof Q==="string"?Q:typeof Q==="object"&&Q!==null?Q.source:"";if(typeof G!=="string")return!1;return G===U1||G.startsWith(`${U1}@`)||G===`npm:${U1}`||G.startsWith(`npm:${U1}@`)})}catch{return!1}}function s8($){return M1("node:fs").readFileSync($,"utf8")}async function x9($=process.env){let Z=S1($);if(!E9(Z))return!1;try{let J=await a8(Z,"utf8"),z=JSON.parse(J);return Boolean(z?.anthropic&&typeof z.anthropic==="object")}catch{return!1}}async function w9($,Z=$0,J=process.env){let z=f9($),Y=await Z.run("pi",["install",z],{env:J});if(Y.exitCode!==0)return{ok:!1,exitCode:Y.exitCode,stderr:Y.stderr};return{ok:!0,message:`Installed ${z}`}}function o8($,Z){let J=g9($,Z),z;switch(Z){case"darwin":z=["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",o0(J,"Applications","OpenCode.app"),o0(J,"Applications","OpenCode Beta.app")];break;case"win32":{let Y=$.LOCALAPPDATA??o0(J,"AppData","Local");z=[o0(Y,"Programs","opencode"),o0(Y,"opencode")];break}case"linux":z=["/opt/OpenCode","/usr/lib/opencode",o0(J,".local","share","applications","opencode.desktop")];break;default:z=[]}return z.some((Y)=>s1(Y))}async function r8($=process.env,Z=$0,J={}){let z=J.platform??process.platform,Y=x0($,z),Q=s1(Y)||o8($,z),G=H1("opencode",$,z)??H1("opencode2",$,z),W=Q||G!==null,X=await l1(G,$,Z,z),K=X?.exitCode===0?X.stdout.trim()||null:null,{path:j,exists:H}=j$(Y),M=!1;if(H){let{value:D}=j1(j);if(Array.isArray(D?.plugin))M=D.plugin.some((q)=>typeof q==="string"&&(q===s0||q.startsWith(`${s0}@`)))}return{kind:"opencode",installed:W,version:K,configPath:j,pluginInstalled:M}}async function t8($=process.env,Z=$0,J={}){let z=J.platform??process.platform,Y=u0($,z),Q=s1(Y),G=H1("pi",$,z),W=Q||G!==null,X=await l1(G,$,Z,z),K=null;if(X?.exitCode===0){let M=X.stdout.trim()||X.stderr.trim();K=M.split(/\r?\n/).find((q)=>/^\d+\.\d+\.\d+/.test(q.trim()))?.trim()||M||null}let j=S9($,Y),H=await x9($);return{kind:"pi",installed:W,version:K,configPath:Y,pluginInstalled:j,hasLocalAuth:H}}async function e8($=process.env,Z=$0,J={}){let z=J.platform??process.platform,Y=H1("ck",$,z),Q=Y!==null,G=await l1(Y,$,Z,z),W=G?.exitCode===0?G.stdout.trim()||null:null,X=null,K=!1;try{if(X=_1(void 0,$),X&&s1(X)){let j=await T9({connectionFile:X,handshakeTimeoutMs:2000});K=!0,j.close()}}catch{K=!1}return{ckInstalled:Q,ckVersion:W,daemonRunning:K,connectionPath:X}}async function h9($=process.env,Z=$0,J={}){let[z,Y,Q]=await Promise.all([r8($,Z,J),t8($,Z,J),e8($,Z,J)]);return{opencode:z,pi:Y,claustrum:Q}}async function m9($,Z){let J={...Z.env},z=async()=>{if(w1(J),await i0(Z.fence),await B0($,J)!=="local")throw Error("Disconnect from the vault first.")};await z();let Y=Z.paths??await l0($,J),Q=await Z.login?.($);if(Q&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(Q.accountIdentity))throw Error("Claude sign-in did not establish an account UUID");if(await z(),await y9({paths:Y.paths,legacyConfigPath:Y.legacyConfigPath,legacyStatePath:Y.legacyStatePath,host:$,hostAuthPath:Y.hostAuthPath,routingSourcePath:Y.routingSourcePath,routingDestinationPath:Y.routingDestinationPath,env:J,processFence:z,removePiAnthropicAuth:Z.removePiAnthropicAuth}),Q){let G=a0({paths:Y.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await G.read()).mode!=="local")throw Error("Disconnect from the vault first.");await z(),await G.loginOAuth({routeId:"main",replace:!0,...Q})}finally{G.close()}}}async function c9($){let Z=await o1("max");u1(Z.url,`Claude sign-in for ${$==="pi"?"Pi":"OpenCode"}`);let J=await N9({message:"Paste the Claude callback URL or authorization code:"});if(I0(J))throw Error("Claude sign-in cancelled");let z=await r1(J,Z.verifier,Z.redirectUri,Z.state);if(z.type!=="success")throw Error("Claude sign-in failed");let Y=await v9(z.access,void 0,void 0);if(!Y.accountUuid)throw Error("Claude sign-in did not establish an account UUID");return{accountIdentity:Y.accountUuid,credential:{type:"oauth",access:z.access,refresh:z.refresh,expires:z.expires}}}async function d9($=[],Z={}){let J=Z.env??process.env,z=Z.runner??$0,Y=Z.fence??c3,Q=Z.activate??P2,G=Z.migrateLocal??m9,W={output:Z.output},X=$.includes("--yes")||$.includes("-y"),K=$.includes("--dry-run"),j=$.includes("--no-claustrum"),H=$.includes("--claustrum"),M=$.includes("--remove-pi-auth"),D=$.includes("--login"),q=D?Z.localLogin??c9:void 0;if(D&&H)return y.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",W),1;L9("CortexKit Anthropic Auth Setup",W);let B=B9(W);B.start("Detecting installed environments…");let N=await(Z.detect??h9)(J,z);B.stop("Environment detection complete.");let x=N.opencode.installed?`detected (${N.opencode.version??"version unknown"}, ${N.opencode.pluginInstalled?"plugin already configured":"plugin not configured"})`:"not found",m=N.pi.installed?`detected (${N.pi.version??"version unknown"}, ${N.pi.pluginInstalled?"extension already installed":"extension not installed"})`:"not found",p=N.claustrum.daemonRunning?`daemon running (${N.claustrum.ckVersion??"ck ready"})`:N.claustrum.ckInstalled?"ck installed, daemon not running":"not installed";if(y.info(`OpenCode: ${x}`,W),y.info(`Pi: ${m}`,W),y.info(`Claustrum: ${p}`,W),!N.opencode.installed&&!N.pi.installed)return y.error("Neither OpenCode nor Pi was detected on this system.",W),H0("Install OpenCode (https://opencode.ai) or Pi (https://github.com/badlogic/pi-mono) first.",W),1;let F=[];if(X){if(N.opencode.installed)F.push("opencode");if(N.pi.installed)F.push("pi")}else{let k=[];if(N.opencode.installed)k.push({value:"opencode",label:"OpenCode",hint:N.opencode.pluginInstalled?"already configured":"configure plugin + TUI sidebar"});if(N.pi.installed)k.push({value:"pi",label:"Pi",hint:N.pi.pluginInstalled?"already installed":"install provider extension"});let _=await F9({message:"Select integrations to configure:",options:k,initialValues:k.map((b)=>b.value),required:!0,...W});if(I0(_))return H0("Setup cancelled.",W),0;F=_}if(F.length===0)return H0("No integrations selected.",W),0;let U=!1;if(N.claustrum.daemonRunning&&N.claustrum.ckInstalled&&!j){if(H)U=!0;else if(!X){let k=await X$({message:"Use Claude accounts from the Claustrum vault? Local account files stay unchanged and are not used while connected.",initialValue:!1,...W});if(I0(k))return H0("Setup cancelled.",W),0;U=k}}if(q&&U)return y.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",W),1;if(q||!U){for(let k of F)if(await B0(k,J)!=="local")return y.error("Disconnect from the vault first.",W),1}let I=!1;if(F.includes("pi")&&N.pi.hasLocalAuth)if(X){if(!M)return y.error(U?"Pi has stored Anthropic authentication. Rerun with --remove-pi-auth to preserve it privately during vault use and restore it on disconnect.":"Pi has a stored Anthropic login. Rerun with --remove-pi-auth to move it into the native account pool.",W),H0("Setup aborted.",W),1;I=!0}else{y.warn(U?"Pi has stored Anthropic authentication. Vault setup must preserve it privately and restore it on disconnect.":"Pi has a stored Anthropic OAuth token. Native account-pool setup moves credentials out of the host auth store.",W);let k=await X$({message:U?"Move Pi authentication aside privately for vault use, then restore it on disconnect?":"Move the Pi Anthropic OAuth login into the native account pool and remove its stored copy?",initialValue:!1,...W});if(I0(k)||!k)return y.error("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.",W),H0("Setup aborted.",W),1;I=!0}try{await i0(Y)}catch(k){return y.error(await N0("setup-process-check",k,J),W),H0("Setup aborted — quit active hosts and rerun setup.",W),1}let E=[];for(let k of F)E.push(await l0(k,J));if(await B2(E),K){if(y.info("[dry-run] Planned actions:",W),y.info(` - Target integrations: ${F.join(", ")}`,W),y.info(` - Claustrum custody: ${U?"enabled":"disabled"}`,W),I)y.info(" - Pi local OAuth token will be removed",W);return H0("Dry run complete. No changes were made.",W),0}let S=await p9(),h=async(k,_)=>{B.start(`Switching ${_} to Claustrum vault custody…`);try{let b=await Q(k,{env:J,runner:z,fence:Y,removePiAnthropicAuth:k==="pi"&&I});return B.stop(b==="already-vault"?`${_} already uses Claustrum vault custody.`:`${_} now uses Claustrum vault custody.`),!0}catch(b){return B.stop(`${_} vault custody setup failed.`),y.error(await N0("setup-activation",b,J),W),!1}};if(F.includes("opencode")){B.start("Configuring OpenCode plugin and TUI sidebar…");try{await k9(S,J),await _9(S,J),B.stop("OpenCode configuration updated.")}catch(k){return B.stop("OpenCode setup failed."),y.error(await N0("setup-opencode-config",k,J),W),1}if(q||!U)await G("opencode",{env:J,fence:Y,removePiAnthropicAuth:!1,login:q});if(U&&!await h("opencode","OpenCode"))return 1}if(F.includes("pi")){B.start("Installing Pi Anthropic extension…");try{let k=await w9(S,z,J);if(!k.ok)return B.stop("Pi extension installation failed."),y.error(await T2("setup-pi-install",k,J),W),1;B.stop("Pi Anthropic extension installed.")}catch(k){return B.stop("Pi setup failed."),y.error(await N0("setup-pi",k,J),W),1}if(q||!U)await G("pi",{env:J,fence:Y,removePiAnthropicAuth:I,login:q});if(U&&!await h("pi","Pi"))return 1}let T=[];if(F.includes("opencode"))T.push("• Start OpenCode normally (opencode).");if(F.includes("pi"))T.push("• Start Pi normally (pi).");if(U)T.push("• Manage accounts in Claustrum with: ck auth login --provider anthropic"),T.push(" Newly added accounts will be discovered automatically without restarting.");return u1(T.join(`
|
|
106
|
+
`),"Next Steps",W),H0("Setup complete!",W),0}async function r0($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await E1(),J=a0({paths:Z,host:"opencode"});try{return await J.read(),await $(J)}finally{J.close()}}async function t1(){if(await B0("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function u9(){console.log(`Usage:
|
|
107
107
|
opencode-anthropic-auth setup [--yes] [--dry-run]
|
|
108
108
|
opencode-anthropic-auth login [label]
|
|
109
109
|
opencode-anthropic-auth api add [label]
|
|
@@ -112,9 +112,9 @@ ${W}
|
|
|
112
112
|
|
|
113
113
|
Native credentials are managed by the offline setup migration.
|
|
114
114
|
Legacy import source:
|
|
115
|
-
${
|
|
115
|
+
${i9()}`)}function U$($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function Z3($){let J=await($.fetchImpl??fetch)(`https://api.cloudflare.com/client/v4${$.path}`,{method:$.method,headers:{authorization:`Bearer ${$.token}`,...$.body instanceof FormData?{}:{"content-type":"application/json"},...$.headers},body:$.body}),z=await J.text(),Y;try{Y=JSON.parse(z)}catch{throw Error(`Cloudflare API returned ${J.status}: ${z}`)}if(!J.ok||Y.success===!1){let Q=Y.errors?.map((G)=>G.message).filter(Boolean).join("; ");throw Error(Q||`Cloudflare API returned ${J.status}`)}return Y.result}async function z6($,Z,J,z){return Z3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function Y6($){let Z={main_module:"worker.js",compatibility_date:"2026-04-28",bindings:[{type:"kv_namespace",name:"RELAY_STATE",namespace_id:$.kvNamespaceId},{type:"secret_text",name:"RELAY_TOKEN",text:$.relayToken}]},J=new FormData;return J.set("metadata",JSON.stringify(Z)),J.set("worker.js",new Blob([s9],{type:"application/javascript+module"}),"worker.js"),Z3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function Q6($,Z,J,z){await Z3({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:z})}async function G6($,Z,J){return Z3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function W6($={}){await r0((D)=>D.read());let Z=$.fetchImpl??fetch,J=$.prompt??$3,z=$.warn??((D)=>console.warn(D)),Y=U$(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(Y);let Q=U$(process.env.CLOUDFLARE_ACCOUNT_ID||await J("Cloudflare account ID: "),"Cloudflare account ID"),G=await J("Worker name [opencode-anthropic-relay]: ")||"opencode-anthropic-relay",W=`${G}-state`,X=n9();$.secrets?.push(X),console.log("Creating Cloudflare KV namespace...");let K=await z6(Y,Q,W,Z);console.log("Uploading relay Worker..."),await Y6({token:Y,accountId:Q,scriptName:G,kvNamespaceId:K.id,relayToken:X,fetchImpl:Z}),await Q6(Y,Q,G,Z).catch(async(D)=>{z(await N0("cli-relay-workers-dev",D,process.env,[Y,X]))});let j=await G6(Y,Q,Z),M=(j?.subdomain?`https://${G}.${j.subdomain}.workers.dev`:"")||U$(await $3("Relay Worker URL: "),"Relay Worker URL");await r0((D)=>D.updateRelay({enabled:!0,url:M,token:X,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${M}`),console.log("Relay settings saved to the native account store.")}var e1=null;async function $3($){return e1??=J6({input:$6,output:Z6}),(await e1.question($)).trim()}function X6(){e1?.close(),e1=null}async function K6($,Z={}){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");let J=Z.prompt??$3,z=Z.authorize??o1,Y=Z.exchange??r1;await t1(),await r0(async(Q)=>{let G=await Q.read(),W=$?.trim()||await J("Fallback account label (optional): "),X=await z("max");console.log(`
|
|
116
116
|
Open this URL in your browser and complete Claude sign-in:
|
|
117
117
|
`),console.log(`${X.url}
|
|
118
|
-
`);let K=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(K);let
|
|
119
|
-
Saved native fallback account${W?` "${W}"`:""}.`)})}async function
|
|
120
|
-
Saved API fallback route${
|
|
118
|
+
`);let K=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(K);let j=await Y(K,X.verifier,X.redirectUri,X.state);if(j.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(j.access,j.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await t1();let H=W&&W!=="main"?W:crypto.randomUUID(),M=G.accounts.some((D)=>D.id===H&&D.source==="local");await Q.loginOAuth({routeId:H,replace:M,label:W||void 0,credential:{access:j.access,refresh:j.refresh,expires:j.expires}}),console.log(`
|
|
119
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function H6($,Z={}){await t1(),await r0((X)=>X.read());let J=Z.prompt??$3,z=$?.trim()||await J("API fallback label (optional): "),Y=process.env.OPENCODE_ANTHROPIC_AUTH_API_BASE_URL?.trim()||(await J("Anthropic-compatible base URL [https://api.kie.ai/claude]: ")).trim()||"https://api.kie.ai/claude";if(!l9(Y))throw Error("API fallback base URL must be an http(s) URL without embedded credentials");let Q=process.env.OPENCODE_ANTHROPIC_AUTH_API_KEY?.trim()||await J("API key: ");if(!Q.trim())throw Error("API key is required");Z.secrets?.push(Q.trim());let W=(process.env.OPENCODE_ANTHROPIC_AUTH_API_AUTH_HEADER?.trim()||await J("Auth header [authorization-bearer|x-api-key] (default authorization-bearer): ")).trim().toLowerCase()==="x-api-key"?"x-api-key":"authorization-bearer";await r0(async(X)=>{await t1();let K=await X.read(),j=z&&z!=="main"?z:crypto.randomUUID(),H=K.accounts.find((M)=>M.id===j);if(H?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await X.addApi({routeId:j,replace:Boolean(H),label:z||void 0,apiKey:Q.trim(),baseURL:Y,authHeader:W})}),console.log(`
|
|
120
|
+
Saved API fallback route${z?` "${z}"`:""} (${Y}).`)}async function j6(){await r0(async($)=>{let Z=(await $.read()).accounts.filter((J)=>J.id!=="main");if(!Z.length){console.log("No native fallback accounts found.");return}for(let[J,z]of Z.entries()){let Y=z.label||z.id,Q=z.enabled?"enabled":"disabled";if(z.type==="api"){console.log(`${J+1}. ${Y} (${Q}) — API route ${z.baseURL}`);continue}let G=z.quota?.five_hour?.remainingPercent,W=z.quota?.seven_day?.remainingPercent,X=G===void 0&&W===void 0?"quota unknown":`5h ${G??"?"}%, 1w ${W??"?"}% remaining`;console.log(`${J+1}. ${Y} (${Q}) — ${X}${z.state?` — ${a9(z)}`:""}`)}})}async function U6($){let[Z,J,z]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){u9();return}if(Z==="setup"){$.stage="cli-setup";let Y=await d9(process.argv.slice(3));if(Y!==0)process.exitCode=Y;return}if(Z==="login"){$.stage="cli-login",await K6(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await H6(z,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await j6();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await W6({secrets:$.secrets});return}u9(),process.exitCode=1}if(M1.main==M1.module){let $={stage:"cli-command",secrets:[]};try{await U6($)}catch(Z){console.error(await N0($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{X6()}}export{d9 as runSetupCommand,W6 as relaySetup,K6 as login,H6 as addApiRoute};
|