@cortexkit/opencode-anthropic-auth 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +85 -84
- package/dist/{index-fds0s2j4.js → index-04syas8a.js} +2 -2
- package/dist/{index-aaajxwzd.js → index-3xqv3rw3.js} +1 -1
- package/dist/{index-4ya27n12.js → index-52r2e1h9.js} +1 -1
- package/dist/index-b3mxpp4w.js +2 -0
- package/dist/index-p4wvcwhh.js +3 -0
- package/dist/index-ynq181e8.js +42 -0
- package/dist/index-yxtdke11.js +449 -0
- package/dist/index-zdgceztz.js +1 -0
- 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/setup/detect.d.ts +7 -4
- package/dist/setup/host-executable.d.ts +3 -0
- package/dist/setup/paths.d.ts +3 -2
- package/dist/setup/pi.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +3 -3
- package/dist/v2/tui.js +1 -1
- package/package.json +2 -2
- package/dist/index-ae3fq4n6.js +0 -42
- package/dist/index-nngmvczq.js +0 -450
- package/dist/index-pn597b6f.js +0 -2
- package/dist/setup/claustrum.d.ts +0 -26
package/dist/cli.js
CHANGED
|
@@ -1,108 +1,109 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as C2,B as R2,C as S2,D as u2,u as k0,v as p0,w as q0,x as W1,y as P0,z as Y1}from"./index-pn597b6f.js";import{$ as v1,Ad as f0,Bd as O$,Ca as a2,Cd as z1,Dd as x$,Ed as v2,Fa as n2,Jb as S$,Ld as j1,Md as K3,Wb as y2,Xb as L$,Z as n0,_ as E0,be as o2,de as r2,hd as X1,id as b$,jd as s2,la as w$,ld as z0,ma as _$,pa as J1,pd as k$,ua as O1,va as I1,vd as X3,wb as c2,xa as G3,ya as P$}from"./index-nngmvczq.js";import{re as z2,se as Z4,te as x3}from"./index-aaajxwzd.js";var B3=Z4((e5,$2)=>{var L3={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"},J4={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},Q4={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?L3.up():"");if($)Z+=L3.left;return Z}};$2.exports={cursor:L3,scroll:J4,erase:Q4,beep:"\x07"}});import{stdin as a4,stdout as n4}from"node:process";import{createInterface as s4}from"node:readline/promises";import{randomUUID as U7}from"node:crypto";import{constants as K1}from"node:fs";import{lstat as q7,mkdir as V7,open as M7}from"node:fs/promises";import{homedir as D7}from"node:os";import{isAbsolute as R$,join as F3}from"node:path";import{types as U3}from"node:util";import{readFile as H7}from"node:fs/promises";import{appendFileSync as z9,chmodSync as W9,existsSync as R1,renameSync as y3,statSync as Y9}from"node:fs";var e2=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,$9=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function Z9($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function M0($={}){let Z=[$9,...$.extraValuePatterns??[]].map((W)=>new RegExp(W.source,W.flags.includes("g")?W.flags:`${W.flags}g`));function J(W){let G=W.toLowerCase().replace(/[-_]/g,"");return e2.test(W)||G.includes("apikey")||G.endsWith("secret")||G.endsWith("password")||G.endsWith("token")&&!G.endsWith("tokens")||!!$.extraSecretKeys?.(G)}function Q(W){let G=W,Y=[["name",W.name],["message",W.message],["stack",W.stack]];for(let j of["code","status","cause"])if(G[j]!==void 0)Y.push([j,G[j]]);let X=new Set(Y.map(([j])=>j));for(let j of Object.entries(W))if(!X.has(j[0]))Y.push(j);return Y}function z(W,G,Y,X=0){if(typeof W==="string")return Z.reduce((j,H)=>j.replace(H,"***REDACTED***"),W);if(!W||typeof W!=="object")return W;if(Y.has(W))return"[Circular]";Y.add(W);try{if(Array.isArray(W))return W.map((K)=>z(K,G,Y,X));let j=Z9(W);if(j&&X>=8)return"[Truncated]";let H=j?X+1:X;return Object.fromEntries((j?Q(W):Object.entries(W)).map(([K,U])=>[K,G&&J(K)?"***REDACTED***":z(U,G,Y,H)]))}finally{Y.delete(W)}}return{redact:(W)=>z(W,!0,new WeakSet),redactStrings:(W)=>z(W,!1,new WeakSet)}}var h3=M0(),J9=h3.redact,Q9=h3.redactStrings;var d0={error:0,warn:1,info:2,debug:3,trace:4},G9=5242880,X9=3;function A1($){try{W9($,384)}catch{}}function j9($){try{if(!(R1($)&&Y9($).size>=G9))return;for(let J=X9-1;J>=1;J--)if(R1(`${$}.${J}`)){let Q=`${$}.${J+1}`;y3(`${$}.${J}`,Q),A1(Q)}let Z=`${$}.1`;y3($,Z),A1(Z)}catch{}}function K9($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function H9($){let Z,J,Q,z=M0(),W,G=[],Y;function X(N){Z=N.file,J=N.level,z=M0(N),W=N.captureSink}function j(N){if(N===void 0||N in d0)Q=N}function H(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function K(){if(Q)return Q;let N=typeof J==="function"?J():J;if(N&&N in d0)return N;return"info"}function U(){if(Y)clearTimeout(Y),Y=void 0;if(!G.length)return;let N;try{N=H()}catch{G=[];return}let A=G.join("");if(G=[],!N)return;try{if(j9(N),R1(N))A1(N);z9(N,A,{encoding:"utf8",mode:384})}catch{}}function V(){if(!Y)Y=setTimeout(()=>{Y=void 0,U()},500)}function q(N,A,w,M){if(Z===void 0&&W===void 0)return;try{if(d0[A]>d0[K()])return;let D=z.redactStrings(w),R;try{R=z.redact(M)}catch{R="[unserializable]"}let k=`[${new Date().toISOString()}] ${A.toUpperCase()} [${N}] ${D}`+(M===void 0?"":K9(R))+`
|
|
3
|
-
`;try{
|
|
4
|
-
`,
|
|
5
|
-
`,"utf8"),await
|
|
6
|
-
`,{
|
|
7
|
-
`,
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`;if(Buffer.byteLength(z)>y1)throw new f("invalid-state","Claustrum enrollment state is too large");let W=w9(Q,`.${E9($)}.${process.pid}.${b9()}.tmp`),G,Y=!1;try{G=await s3(W,"wx",384),Y=!0,await G.writeFile(z,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await A9(W,$),Y=!1}finally{if(await G?.close().catch(()=>{}),Y)await r3(W).catch(()=>{})}}async function s0($,Z){let J=await H0($.tokenPath),Q=J===void 0?void 0:u1(J),z=await H0($.statePath),W=z===void 0?void 0:d1(z);if(Q)return{state:"approved",proposedName:W?.proposedName??Z,...W?.phase==="approved"&&W.approvedName!==void 0&&{approvedName:W.approvedName},tokenGeneration:Q.token_generation};if(!W)return{state:"idle"};if(W.phase==="approved")return{state:"blocked",proposedName:W.proposedName,code:"missing_token"};return $0(W)}async function l1($){let Z=await H0($);if(Z===void 0)throw new f("not-enrolled","Claustrum enrollment is not configured");return u1(Z)}function $0($){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 z$(){return new f("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class o0{#$;#J;#Z;#W;#X;#z;#Q;constructor($){this.#Q=$.ancestorOptions??{},this.#$=$.client,this.#J=$.paths,this.#Z=$.proposedName,this.#W=$.now??Date.now,this.#X=$.mintSecret??(()=>f9(32).toString("hex")),this.#z=$.writeTokenFile??n0}async status(){return s0(this.#J,this.#Z)}async resetTerminal(){return W$(this.#J,this.#Z)}async#Y($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#W()};return await K0(this.#J.statePath,J,this.#Q),$0(J)}async reconcile(){await a0(L0(this.#J.statePath));let $=await e({name:"ceremony",path:this.#J.statePath,ttlMs:t3,renew:!0});if(!$)return{state:"busy"};try{let Z=await H0(this.#J.tokenPath),J=Z===void 0?void 0:u1(Z),Q=await H0(this.#J.statePath),z=Q===void 0?void 0:d1(Q);if(z&&z.proposedName!==this.#Z)throw z$();if(J){if(!z||z.phase==="pending"){let G={version:1,phase:"approved",proposedName:z?.proposedName??this.#Z,tokenGeneration:J.token_generation,updatedAt:this.#W()};await K0(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.#W()};return await K0(this.#J.statePath,G,this.#Q),$0(G)}if(z&&z.phase!=="pending")return $0(z);if(!z){let G=this.#W();if(z={version:1,phase:"pending",proposedName:this.#Z,requestSecret:this.#X(),createdAt:G,updatedAt:G},!p1.test(z.requestSecret))throw new f("invalid-state","invalid minted Claustrum enrollment secret");await K0(this.#J.statePath,z,this.#Q)}if(!z.requestId)try{let G=I9("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),Y=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:G});z={...z,requestId:Y.requestId,updatedAt:this.#W()},await K0(this.#J.statePath,z,this.#Q)}catch(G){let Y=m1(G);if(!Y)throw G;if(Y.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:Y.code};return this.#Y(z,Y.code)}let W=z.requestId;if(!W)return $0(z);try{let G=await this.#$.enrollPoll({requestId:W,requestSecret:z.requestSecret});if(G.status==="pending")return $0(z);if(G.status==="denied"){let X={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#W()};return await K0(this.#J.statePath,X,this.#Q),$0(X)}await a0(L0(this.#J.tokenPath)),await Q$(L0(this.#J.tokenPath),this.#Q),await this.#z(this.#J.tokenPath,{token:G.token,token_generation:G.tokenGeneration});let Y={version:1,phase:"approved",proposedName:z.proposedName,approvedName:G.name,tokenGeneration:G.tokenGeneration,updatedAt:this.#W()};return await K0(this.#J.statePath,Y,this.#Q),$0(Y)}catch(G){let Y=m1(G);if(!Y)throw G;if(Y.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:W,retryCode:Y.code};return this.#Y(z,Y.code)}}finally{await $.release()}}}async function W$($,Z){await a0(L0($.statePath));let J=await e({name:"ceremony",path:$.statePath,ttlMs:t3,renew:!0});if(!J)return"busy";try{if(await H0($.tokenPath)!==void 0)return"refused-approved";let Q=await H0($.statePath);if(Q===void 0)return"idle";let z=d1(Q);if(z.proposedName!==Z)throw z$();if(z.phase==="pending")return"refused-pending";return await J.assertOwned(),await r3($.statePath),"reset"}finally{await J.release()}}var i1="claustrum-tombstone:v1:";function Y$($,Z){return Z!==void 0&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function T9($,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 G$=R0("claustrum");function s1($,Z,J,Q=G$){let z=Y$(Z,J);return Q.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:z,reason:T9(Z,J)}),z}var n1=300000;function a1(){return new f("invalid-material","Claustrum returned invalid credential material")}function h9($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw a1()}if(!J||typeof J!=="object")throw a1();let Q=J,z=Q.access_token??Q.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(i1))throw a1();return Z}function y9($,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 r0{#$;#J;#Z;#W;#X;#z;#Q;#Y=new WeakMap;#H=new WeakMap;#G=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#J=$.readToken;else if(Z)this.#J=()=>l1(Z);else throw new f("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#W=$.family,this.#X=$.parseIdentity,this.#z=$.requireAssertion??!1,this.#Z=$.now??Date.now,this.#Q=$.logger??G$}#j($){if(this.#G)throw new f("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#K($){this.#j($);let Z=await this.#J();if(this.#j($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new f("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#F($,Z){this.#j(Z);let J,Q;try{let z=$();J=Z?await Promise.race([z,new Promise((W,G)=>{let Y=()=>G(Z.reason);if(Z.addEventListener("abort",Y,{once:!0}),Q=()=>Z.removeEventListener("abort",Y),Z.aborted)Y()})]):await z}catch(z){if(this.#j(Z),z instanceof E0)throw z;throw new f("unavailable","Claustrum scoped operation unavailable")}finally{Q?.()}return this.#j(Z),J}async discover($){let Z=await this.#K($),J=await this.#F(()=>this.#$.listScoped(Z),$),Q=[],z=[],W=new Map;for(let Y of J.rows){let X=y9(Y,this.#W);if(!X)continue;z.push({row:Y,type:X}),W.set(Y.id,(W.get(Y.id)??0)+1)}let G=[];for(let{row:Y,type:X}of z){let j;if(!Y.id.trim())j="empty credential id";else if((W.get(Y.id)??0)>1)j="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())j="blank account identity";else if(!Y.state.trim())j="empty state";if(j){Q.push({...Y.id.trim()&&{credentialId:Y.id},reason:j});continue}G.push(Object.freeze({credentialId:Y.id,credentialType:X,...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of Q)this.#Q.warn("skipped malformed vault record",Y);return{view:J.view,credentials:Object.freeze(G),skipped:Object.freeze(Q)}}async authorize($,Z){if(!$.credentialId)throw new f("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:J,credentialType:Q,accountIdentity:z}=$;if(this.#z&&z===void 0)throw new f("identity-unasserted","Claustrum dispatch requires a known account identity");let W=await this.#K(Z),G=await this.#F(()=>this.#$.getScoped({credentialId:J,enrollmentToken:W,...Q==="oauth"&&{minTtlMs:n1}}),Z);if(G.credentialId!==void 0&&G.credentialId!==J)throw new f("identity-changed","Claustrum served credential identity changed");let Y=G.expiresAtMs;if(!Number.isSafeInteger(G.recordVersion)||G.recordVersion<0||Y===null&&Q==="oauth"||Y!==null&&(!Number.isFinite(Y)||Y-this.#Z()<n1))throw new f("insufficient-validity","Claustrum served credential has insufficient validity");let X=h9(G.material),j=G.accountId?.trim()?G.accountId:void 0;if(this.#z&&(G.credentialId===void 0||j===void 0))throw new f("identity-unasserted","Claustrum served credential did not assert its identity");let H=j===void 0?this.#X?.(X):void 0,K=j??H;if(z!==void 0&&K!==void 0&&K!==z)throw new f("identity-changed","Claustrum served credential identity changed");let U=K??z,q=Object.freeze(Object.defineProperty({credentialId:J,credentialType:Q,...U!==void 0&&{accountIdentity:U},accountIdentitySource:j!==void 0?"asserted":H!==void 0?"parsed":z!==void 0?"expected":"none",...z!==void 0&&{expectedAccountIdentity:z},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...j!==void 0&&{assertedAccountIdentity:j},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:Y},"accessToken",{value:X,enumerable:!1}));return this.#Y.set(q,W),q}async reportFailure($,Z,J){if(Z!==401)return;this.#j();let Q=this.#Y.get($);if(!Q)throw new f("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#H.get($);if(z)return z;let W=this.#F(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:Q,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#H.set($,W);try{await W,this.#Q.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(G){throw this.#H.delete($),G}}close(){if(this.#G)return;this.#G=!0,this.#$.close()}}import{createHash as s9}from"node:crypto";import{readFile as o9}from"node:fs/promises";var F0="all",m9=Object.freeze(["primary"]);function j$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function B0($,Z){return JSON.stringify([$,Z])}function r1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function n($){return typeof $==="number"&&Number.isFinite($)}function X$($){return typeof $==="string"&&$.length>0}function s($,Z,J){return $[Z]===void 0||J($[Z])}function v9($){return n($)&&$>0}function o1($){return typeof $==="string"}function p9($){if(!r1($)||!X$($.scope)||!X$($.label))return!1;switch($.kind){case"reading":return n($.checkedAt)&&n($.usedPercent)&&s($,"resetsAt",o1)&&s($,"windowMinutes",v9);case"retired":return n($.retiredAt);case"absent":return n($.checkedAt);default:return!1}}function c9($){if(!r1($)||!n($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&s($,"remainingPercent",n)&&s($,"usedPercent",n)&&s($,"resetsAt",o1)&&s($,"limit",n)&&s($,"used",n)&&s($,"remaining",n)&&s($,"unit",o1)}function U0($){if(!r1($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!p9(J))return!1;let Q=B0(J.scope,J.label);if(Z.has(Q))return!1;Z.add(Q)}return s($,"budget",c9)}class t0 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function $1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function e0($){return typeof $==="number"&&Number.isFinite($)}function K$($){return $===void 0||typeof $==="string"&&$!==""}function H$($){return typeof $==="string"&&$!==""}function w0($,Z){return $[Z]===void 0||e0($[Z])}function t1($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function d9($){return $1($)&&K$($.scope)&&H$($.label)&&e0($.usedPercent)&&t1($,"resetsAt")&&($.windowMinutes===void 0||e0($.windowMinutes)&&$.windowMinutes>0)}function u9($){return $1($)&&K$($.scope)&&H$($.label)}function l9($){if(!$1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&w0($,"remainingPercent")&&w0($,"usedPercent")&&t1($,"resetsAt")&&w0($,"limit")&&w0($,"used")&&w0($,"remaining")&&t1($,"unit")}function F$($){if(!$1($)||!e0($.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(!d9(z))return!1;let W=B0(z.scope??F0,z.label);if(Q.has(W))return!1;Q.add(W)}if(!J.every(u9))return!1;return $.budget===void 0||l9($.budget)}function i9($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function a9($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function _0($,Z){if($!==void 0&&!U0($))throw new t0("stored quota map is malformed");if(!F$(Z))throw new t0("quota observation is malformed");let J=$??{limits:[]},Q=Z.checkedAt,z=new Map;for(let K of J.limits)z.set(B0(K.scope,K.label),K);let W=(K)=>{let U=z.get(K);return U===void 0||Q>=j$(U)},G=new Set;for(let K of Z.readings??[]){let U=K.scope??F0,V=B0(U,K.label);if(G.add(V),!W(V))continue;z.set(V,{scope:U,label:K.label,kind:"reading",checkedAt:Q,usedPercent:K.usedPercent,...K.resetsAt===void 0?{}:{resetsAt:K.resetsAt},...K.windowMinutes===void 0?{}:{windowMinutes:K.windowMinutes}})}for(let K of Z.coverage??[]){let U=K.scope??F0,V=B0(U,K.label);if(G.has(V)||!W(V))continue;let q=z.get(V);z.set(V,q===void 0||q.kind==="absent"?{scope:U,label:K.label,kind:"absent",checkedAt:Q}:{scope:U,label:K.label,kind:"retired",retiredAt:Q})}let{limits:Y,budget:X,...j}=J,H=a9(J.budget,Z.budget,Q);return{...j,limits:[...z.values()].sort(i9),...H===void 0?{}:{budget:H}}}var n9=Object.freeze({validate:U0,merge:_0});function U$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function e1($,Z,J){return $.some((Q)=>U$(Q,Z,J))}function $3($,Z,J){let Q={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==J),Q]}function Z3($,Z,J){return $.filter((Q)=>!Z.some((z)=>U$(Q,z,J)))}var V$="vault:";function r9($){return s9("sha256").update($).digest("hex")}function t9($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function e9($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function Z0($){return[$.credentialId,...$.aliases??[]]}function M$($,Z,J={}){let Q=J.now??Date.now(),z=J.routePrefix??V$,W=J.reservedRouteIds??new Set,G=$?.rows??[],Y=[...$?.declined??[]],X=Z.skipped.length===0,j=new Set(Z.credentials.map((M)=>M.credentialId)),H=new Set(Z.skipped.flatMap((M)=>M.credentialId===void 0?[]:[M.credentialId])),K=Z.skipped.some((M)=>M.credentialId===void 0),U=(M)=>!j.has(M)&&(H.has(M)||K),V=new Map;for(let M of G){if(M.accountIdentity===void 0)continue;for(let D of Z0(M))if(!V.has(D))V.set(D,M.accountIdentity)}let q=new Map;for(let M of Z.credentials){let D=M.accountIdentity!==void 0?{credential:M,identity:M.accountIdentity,claimed:!0}:{credential:M,identity:V.get(M.credentialId),claimed:!1},R=e9(D),k=q.get(R)??[];k.push(D),q.set(R,k)}let B=new Set,I=new Set(W),N=[],A=(M,D)=>M.credential.credentialId.localeCompare(D.credential.credentialId),w=[...q.values()].map((M)=>M.toSorted(A)).sort((M,D)=>M[0]&&D[0]?A(M[0],D[0]):0);for(let M of w){let D=M[0]?.identity,R=M.filter((O)=>O.credential.state==="active"),k=R.length?R:M,E=k.filter((O)=>O.claimed),S=E.length?E:k,m=new Set(M.map((O)=>O.credential.credentialId)),T=G.find((O)=>!B.has(O)&&Z0(O).some((c)=>m.has(c))&&(O.accountIdentity===void 0||O.accountIdentity===D)),C=S.find((O)=>O.credential.credentialId===T?.credentialId)??S[0];if(!C)continue;let x=C.credential,b=T??(D===void 0?void 0:G.find((O)=>!B.has(O)&&O.accountIdentity===D));if(b)B.add(b);let y=b?.routeId;if(!y||W.has(y)){let O=`${z}${x.credentialId}${D===void 0?"":`~${r9(D).slice(0,10)}`}`;y=O;for(let c=2;I.has(y);c++)y=`${O}~${c}`}I.add(y);let p=b?Z0(b).filter(U):[],L=[...new Set([...M.map((O)=>O.credential.credentialId),...p])].filter((O)=>O!==x.credentialId).sort((O,c)=>O.localeCompare(c)),P=J.mapAccount?.(x)??{};N.push({previousIndex:b?G.indexOf(b):1/0,row:{routeId:y,credentialId:x.credentialId,credentialType:x.credentialType,...D!==void 0&&{accountIdentity:D},...L.length&&{aliases:L},state:x.state,label:P.label?.trim()||t9(x),...x.email!==void 0&&{email:x.email},...x.orgName!==void 0&&{orgName:x.orgName},enabled:![x.credentialId,...L].some((O)=>e1(Y,O,D)),addedAt:b?.addedAt??Q,...b?.quota!==void 0&&{quota:b.quota},...!C.claimed&&D!==void 0&&{unclaimed:!0}}})}return G.forEach((M,D)=>{if(B.has(M)||!Z0(M).some(U))return;if(I.has(M.routeId))return;let[R,...k]=Z0(M).filter((m)=>!j.has(m));if(R===void 0)return;I.add(M.routeId);let{aliases:E,...S}=M;N.push({previousIndex:D,row:{...S,credentialId:R,...k.length&&{aliases:k},stale:!0}})}),N.sort((M,D)=>M.previousIndex===D.previousIndex?M.row.credentialId.localeCompare(D.row.credentialId):M.previousIndex-D.previousIndex),{version:1,view:Z.view,complete:X,...!X&&{rejected:Z.skipped.map((M)=>({...M.credentialId!==void 0&&{credentialId:M.credentialId},reason:M.reason}))},rows:N.map((M)=>M.row),declined:Y}}function J3($){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 N0($){return $===void 0||typeof $==="string"}function $7($){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"||!N0($.accountIdentity)||!N0($.email)||!N0($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((Z)=>typeof Z==="string"))||$.quota!==void 0&&!U0($.quota)||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return $}var Z7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function q$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!Z1(J)||!N0(J.credentialId)||typeof J.reason!=="string"||!Z7.has(J.reason))return;Z.push(J)}return Z}function J7($){if(!Z1($)||$.version!==1||!N0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!q$($.rejected))throw new f("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let W=$7(z);if(!W)throw new f("invalid-state","Claustrum roster file is not valid");Z.push(W)}let J=[];for(let z of $.declined){if(!Z1(z)||typeof z.credentialId!=="string"||!N0(z.accountIdentity))throw new f("invalid-state","Claustrum roster file is not valid");J.push(z)}let Q=q$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...Q&&{rejected:Q},rows:Z,declined:J}}async function J0($){let Z;try{Z=await o9($,"utf8")}catch(Q){if(Q.code==="ENOENT")return;throw Q}let J;try{J=JSON.parse(Z)}catch{throw new f("invalid-state","Claustrum roster file is not valid")}return J7(J)}var Q7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},z7={name:"claustrum-roster",ttlMs:30000};async function S0($,Z,J={}){return g1($,Q7,async(Q)=>{let z=await J0($),{next:W,result:G}=await Z(z,{assertOwned:()=>Q.assertOwned()});if(W)await Q.assertOwned(),await _1($,W,{beforeRename:async()=>{await J.beforePublish?.(),await Q.assertOwned()}});return G})}function Q3($,Z){return S0($,(J)=>{let Q=J?.rows.find((W)=>W.routeId===Z);if(!J||!Q)throw new f("route-unavailable","Claustrum route is not in the roster");let z=$3(J.declined,Q.credentialId,Q.accountIdentity);return{next:{...J,declined:z,rows:J.rows.map((W)=>W===Q?{...W,enabled:!1}:W)},result:void 0}})}function z3($,Z){return S0($,(J)=>{let Q=J?.rows.find((z)=>z.routeId===Z);if(!J||!Q)throw new f("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:Z3(J.declined,Z0(Q),Q.accountIdentity),rows:J.rows.map((z)=>z===Q?{...z,enabled:!0}:z)},result:void 0}})}function W7($,Z){if(!Z0($).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")&&Z0($).length===1)return"bind";return"refuse"}function W3($,Z){return S0($,(J)=>{let Q=J?.rows.find((Y)=>Y.routeId===Z.routeId),z=!J||!Q?"refuse":W7(Q,Z);if(!J||!Q||z==="refuse")return{result:!1};let W=_0(Q.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...J,rows:J.rows.map((Y)=>Y===Q?{...Y,...G,quota:W}:Y)},result:!0}})}async function Y3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let J=await e({...z7,path:$.path,renew:!0});if(!J){let Q=await J0($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new f("roster-busy","Claustrum account discovery is already in progress");return Q}try{let Q=await $.custody.discover($.signal);return $.signal?.throwIfAborted(),await S0($.path,async(z)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let W=typeof $.projection==="function"?$.projection():$.projection,G=M$(z,Q,W);return{...JSON.stringify(z)!==JSON.stringify(G)&&{next:G},result:G}})}finally{await J.release()}}class D${#$;#J=new AbortController;#Z;#W;#X;#z;#Q;#Y;#H=!1;constructor($){this.#$=$,this.#Z=$.logger??R0("claustrum")}#G($){this.#J.signal.throwIfAborted(),$?.throwIfAborted()}async#j(){return await this.#$.isCustodyActive?.()??!0}#K($,Z){let J=E1([this.#J.signal,...Z?[Z]:[]]);return new Promise((Q,z)=>{let W=()=>{J.signal.removeEventListener("abort",G),J.dispose()},G=()=>{W(),z(J.signal.reason)};if(J.signal.addEventListener("abort",G,{once:!0}),$.then((Y)=>{if(W(),J.signal.aborted)z(J.signal.reason);else Q(Y)},(Y)=>{W(),z(Y)}),J.signal.aborted)G()})}async#F(){if(this.#G(),this.#W)return this.#W;if(!this.#X)this.#X=this.#$.connect().then(($)=>{if(this.#J.signal.aborted)$.close(),this.#G();return this.#W=new r0({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z}),this.#W}).finally(()=>{this.#X=void 0});return this.#K(this.#X)}snapshot(){return this.#Q}routingRows(){return J3(this.#Q)}refresh(){if(this.#G(),this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#j()){this.#Q=void 0,this.#W?.close(),this.#W=void 0;return}let $=await this.#F(),Z=await Y3({path:this.#$.rosterPath,custody:$,isActive:()=>this.#j(),signal:this.#J.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.#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.#G(),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.#Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#Y=void 0,$()},Z),this.#Y.unref?.()};$()}async authorize($,Z){this.#G(Z);let J=this.#Q??await this.#K(this.refresh(),Z);if(!J||!await this.#j())throw new f("not-active","Claustrum scoped custody is not active");let Q=await J0(this.#$.rosterPath);this.#G(Z);let z=J.rows.find((X)=>X.routeId===$),W=Q?.rows.find((X)=>X.routeId===$);if(W&&!W.enabled)throw new f("route-declined","Claustrum route is disabled");if(!z||!W||W.state!=="active"||W.credentialId!==z.credentialId||W.accountIdentity!==z.accountIdentity)throw new f("route-unavailable","Claustrum route is disabled, removed or changed");let G=await this.#K(this.#F(),Z),Y=E1([this.#J.signal,...Z?[Z]:[]]);try{return await G.authorize({credentialId:W.credentialId,credentialType:W.credentialType,...W.accountIdentity!==void 0&&{accountIdentity:W.accountIdentity}},Y.signal)}finally{Y.dispose()}}async reportFailure($,Z,J){if(this.#G(),!this.#W)throw new f("no-receipt","Claustrum dispatch receipt has no active owner");await this.#W.reportFailure($,Z,J)}async send($,Z,J){let Q=J.signal,z=await this.authorize($,Q),W=await Z(z,Q);if(W.status===401&&!Q?.aborted){let G;try{G=await this.authorize($,Q)}catch{}if(s1(J.site,z,G,this.#Z))await W.body?.cancel().catch(()=>{}),z=G,W=await Z(G,Q)}if(W.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 W}async decline($){this.#G(),await Q3(this.#$.rosterPath,$),this.#Q=await J0(this.#$.rosterPath)}async accept($){this.#G(),await z3(this.#$.rosterPath,$),this.#Q=await J0(this.#$.rosterPath)}async recordQuota($,Z,J){this.#G();let Q=await W3(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 J0(this.#$.rosterPath);return Q}close(){if(this.#J.signal.aborted)return;if(this.#J.abort(new f("closed","Claustrum consumer is closed")),this.#Y)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Y);this.#Y=void 0,this.#W?.close(),this.#Q=void 0}}class o extends Error{code;constructor($){super(`Native vault setup: ${$}`);this.code=$;this.name="NativeVaultEnrollmentError"}}async function B$($,Z){let J={...Z.env},Q=Z.paths??L$($,J),z=`anthropic-auth-${$}`,W=Z.processFence,G=Z.runner,Y=Z.ckBinary??"ck",X,j=Z.client;try{await W();let H=await s0(Q,z),K=new Set(["superseded","not_found","already_consumed"]);if(H.state==="idle"||H.state==="pending"||H.state==="blocked"&&K.has(H.code)){if(!j)X=await c1({connectionFile:J1(Z.connectionFile??($==="pi"?J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0),$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:J)}),j=X;let V=j,q=new o0({paths:Q,proposedName:z,client:{enrollPropose:async(B)=>{return await W(),V.enrollPropose(B)},enrollPoll:async(B)=>{return await W(),V.enrollPoll(B)}},writeTokenFile:async(B,I)=>{await W(),await n0(B,I)}});if(H.state==="blocked"){if(await W(),await q.resetTerminal()!=="reset")throw new o("enrollment-refused");throw new o("enrollment-reset")}if(await W(),H=await q.reconcile(),H.state==="pending"&&H.requestId){if(await W(),(await G.run(Y,["auth","enroll","approve","--request-id",H.requestId,"--name",z],{env:J})).exitCode!==0)throw new o("approval-refused");await W(),H=await q.reconcile()}}if(H.state!=="approved")throw new o("enrollment-refused");if(await W(),(await G.run(Y,["auth","grant","--principal",`enrolled:${z}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"],{env:J})).exitCode!==0)throw new o("permission-refused")}catch(H){if(H instanceof o)throw H;throw new o("enrollment-refused")}finally{X?.close()}}import{dirname as Y7,join as N$,resolve as Q1}from"node:path";async function O0($,Z){let J=$==="pi"?P0(Z):q0(Z),Q=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),z=Q1(Q||N$(J,G3)),W=Q1(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(z.endsWith(G3)?N$(Y7(z),P$):`${z}.state.json`)),G=await z1(z,W),Y=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:G,legacyConfigPath:z,legacyStatePath:W,hostAuthPath:$==="pi"?Y1(Z):W1(Z),routingSourcePath:Q1(Y||X3(z)),routingDestinationPath:Q1(Y||X3(G.config))}}async function I$($){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 O$(Q),W=Z.get(z);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(z,J.host)}}import{execFile as G7}from"node:child_process";import{promisify as X7}from"node:util";var j7=X7(G7),l={async run($,Z,J={}){try{let Q=J.env?{...process.env,...J.env}:process.env,{stdout:z,stderr:W}=await j7($,Z,{env:Q,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof z==="string"?z:String(z),stderr:typeof W==="string"?W:String(W)}}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 f$=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class Q0 extends Error{code="process-inspection-failed";constructor(){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError"}}class G1 extends Error{activeHosts;constructor($){let Z=$.map((Q)=>({pid:Q.pid,command:f$.exec(Q.command)?.[1]??"host"})),J=Z.map((Q)=>` - PID ${Q.pid}: ${Q.command}`).join(`
|
|
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{Y?.({channel:q,level:P,message:S,data:h})}catch{}if(Z===void 0)return;if(G.push(w),G.length>=50){let k=I(!1);if(k instanceof Promise)k.catch(()=>{})}else T()}catch{}}function p(q){return{error:(P,O)=>m(q,"error",P,O),warn:(P,O)=>m(q,"warn",P,O),info:(P,O)=>m(q,"info",P,O),debug:(P,O)=>m(q,"debug",P,O),trace:(P,O)=>m(q,"trace",P,O)}}function F(){if(A)j(()=>U0(H)).catch(()=>{});if(K=void 0,G=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,Q=void 0,z=g0(),Y=void 0}if($)U($);return{configure:U,createLogger:p,setLogLevel:M,flushLogs:I,reset:F}}var Q7=J7();function n0($){return Q7.createLogger($)}function J3($){let Z=new AbortController,J=[],Q=!1,z=()=>{if(Q)return;Q=!0;for(let{source:W,listener:X}of J)W.removeEventListener("abort",X);J.length=0},Y=(W)=>{if(Q||Z.signal.aborted)return;Z.abort(W),z()},G=$.find((W)=>W.aborted);if(G)return Z.abort(G.reason),{signal:Z.signal,dispose:z};for(let W of $){if(Z.signal.aborted)break;let X=()=>Y(W.reason);if(J.push({source:W,listener:X}),W.addEventListener("abort",X,{once:!0}),W.aborted)Y(W.reason)}return{signal:Z.signal,dispose:z}}import{createHash as U7,randomBytes as q7,randomUUID as V7}from"node:crypto";import{constants as k$}from"node:fs";import{chmod as M7,mkdir as D7,open as E$,readFile as K3,realpath as F7,rename as L7,stat as S$,unlink as x$}from"node:fs/promises";import{basename as N7,dirname as A0,extname as n6,isAbsolute as s6,join as B7,resolve as o6}from"node:path";import{randomUUID as L$}from"node:crypto";import{mkdir as z7,open as N$,rename as Y7,rm as G7}from"node:fs/promises";import{dirname as B$}from"node:path";class Q3 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function z3($,Z,J={}){await W7($,Z,J)}async function W7($,Z,J,Q){if(A)return T0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??L$)()}.tmp`,onRenamed:Q,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await z7(B$($),{recursive:!0});let z=`${$}.${(J.stageName??L$)()}.tmp`,Y,G=!1;try{if(Y=await N$(z,"wx",384),G=!0,await Y.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
5
|
+
`,"utf8"),await Y.chmod(384),J.durable)try{await Y.sync()}catch(W){throw new Q3(W)}if(await Y.close(),Y=void 0,await J.beforeRename?.(),await Y7(z,$),G=!1,Q?.(),J.durable){let W=await N$(B$($),"r");try{await W.sync()}catch(X){throw new Q3(X)}finally{await W.close()}}}finally{if(await Y?.close().catch(()=>{}),G)await G7(z,{force:!0}).catch(()=>{})}}var X7=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 U1}from"node:crypto";import{mkdir as I$,open as K7,readFile as O$,rename as P$,rm as q1,stat as C$,writeFile as R$}from"node:fs/promises";import{dirname as X3,join as b$}from"node:path";function Y3($,Z){return`${$}.${Z}.lock`}class G3 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class h0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function W3($,Z,J){let Q=performance.now();for(;;){let z=await V0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(z)try{return await J(z)}finally{await z.release()}let Y=Z.timeoutMs-(performance.now()-Q);if(Y<=0)throw new G3({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((G)=>setTimeout(G,Math.min(25,Math.ceil(Y))))}}var j7=globalThis.setTimeout.bind(globalThis),H7=globalThis.clearTimeout.bind(globalThis);function A$($){let Z=$?.code;return Z==="ENOENT"||!A&&(Z==="EINVAL"||Z==="ENOTDIR")}async function V0($){let Z=Y3($.path,$.name),J=b$(Z,"owner.json"),Q=U1(),z=$.now??Date.now,Y=null,G=!1,W=!1,X,K,H=new Promise((L)=>{K=L});function j(L){try{let N=$.onRenewalTimer?.(L);if(N&&(typeof N==="object"||typeof N==="function")&&"then"in N&&typeof N.then==="function")Promise.resolve(N).catch(()=>{})}catch{}}function U(){if(!Y)return;H7(Y),Y=null,j("cancelled")}function M(L,N){if(X||G)return;X=Object.freeze({reason:L,expectedOwnerId:Q,...typeof N?.ownerId==="string"?{observedOwnerId:N.ownerId}:{},...typeof N?.expiresAt==="number"?{observedExpiresAt:N.expiresAt}:{}}),U(),K(X)}let D,B=null,I=`${Z}.evicting`,T=b$(I,"owner.json"),m=U1(),p=5000,F=8;async function q(){if(A)try{return JSON.parse(await Y0(Z,!0))}catch(L){if(L.code!=="EISDIR"&&L.reason!=="wrong-kind")throw L;return await n(Z,"directory",!0),JSON.parse(await Y0(J,!0))}try{return JSON.parse(await O$(Z,"utf8"))}catch(L){if(L.code!=="EISDIR")throw L;return JSON.parse(await O$(J,"utf8"))}}async function P(){if(A){let v=await q(),u=Number(v?.expiresAt)-z();await T0(Z,`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,u),beforeRename:async()=>{let K1=await q();if(K1?.ownerId!==Q||!(Number(K1?.expiresAt)>z())||!await _())throw new h0({target:$.path,name:$.name})}});return}let L=`${Z}.${U1()}.tmp`,N,C=!1;try{N=await K7(L,"wx",384),C=!0,await N.writeFile(`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
7
|
+
`,"utf8"),await N.chmod(384),await N.close(),N=void 0;let v=await q();if(v?.ownerId!==Q||!(Number(v?.expiresAt)>z())||!await _())throw new h0({target:$.path,name:$.name});await P$(L,Z),C=!1}finally{if(await N?.close().catch(()=>{}),C)await q1(L,{force:!0}).catch(()=>{})}}async function O(){let L=`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
8
|
+
`;if(A)await w0(Z,L);else await R$(Z,L,{encoding:"utf8",mode:384,flag:"wx"})}async function E(L){let N=L.code;if(N==="EEXIST"){if(A)await q();return!0}if(N==="EISDIR"){if(A)await n(Z,"directory",!0),await Y0(J,!0);return!0}return!1}async function S(){if(A)await z0(X3(Z));try{return await O(),!0}catch(L){let N=L.code;if(await E(L))return!1;if(N==="ENOENT"){if(A)await z0(X3(Z));else await I$(X3(Z),{recursive:!0});try{return await O(),!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 w(L=!0){if(L&&$.onStep)await $.onStep("lock-read-ready");let N;try{N=await q()}catch(v){if(A&&v.code!=="ENOENT")throw v}let C=Number(N?.expiresAt);if(Number.isFinite(C)&&C>z())return{status:"live"};if(typeof N?.ownerId==="string"&&Number.isFinite(C))return{status:"stale",identity:{kind:"owner",ownerId:N.ownerId,expiresAt:C}};try{let v=await C$(Z),u=Number.isFinite(C)?C:v.mtimeMs+$.ttlMs;if(u>z())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,N){if(N.status!=="stale")return!1;let C=N.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 Y0(T,A))?.ownerId===m}catch(L){if(A&&L.code!=="ENOENT")throw L;return!1}}async function b(L){if(A)await r(L,"remove",()=>q1(L,{recursive:!0,force:!0}));else await q1(L,{recursive:!0,force:!0}).catch(()=>{})}async function c(){if(await _())await b(I)}async function o(){if(A)await U$(I);else await I$(I);try{let L=`${JSON.stringify({ownerId:m,createdAt:z()})}
|
|
9
|
+
`;if(A)await w0(T,L);else await R$(T,L,{encoding:"utf8",mode:384,flag:"wx"})}catch(L){if(A$(L))return!1;throw await c(),L}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function i(){let L;try{L=await C$(I)}catch(C){if(C.code==="ENOENT")return"missing";throw C}if(A)await n(I,"directory",!0);if(L.mtimeMs+p>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let N=`${I}.${U1()}`;try{await P$(I,N)}catch(C){if(C.code==="ENOENT")return"missing";throw C}if($.onStep)await $.onStep("stale-marker-claimed");return await b(N),"recovered"}async function j0(L){try{if(!await o())return!1}catch(N){if(N.code==="EEXIST"){if(A){await n(I,"directory",!0);try{await Y0(T,!0)}catch(C){if(C.code!=="ENOENT")throw C}}return!1}throw N}try{await L()}finally{await c()}return!0}async function x(){for(let L=0;L<F;L++){if($.onStep)await $.onStep("relinquish-read");let N;try{N=await q()}catch(C){if(A)throw C;return}if(N?.ownerId!==Q)return;try{await q1(Z,{recursive:!0,force:!0});return}catch(C){if(A)throw C;await h()}}}function J0(){if(!$.renew||G||X)return;let L=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(Y=j7(()=>{Y=null;let N=(async()=>{let C=!G;try{if(!await j0(async()=>{let u=await q(),K1=z();if(G||X){C=!1;return}if(u?.ownerId!==Q){M("taken-over",u),C=!1;return}if(!(Number(u?.expiresAt)>K1)){M("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 _()){M("marker-lost"),C=!1,await x();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(v){if(A&&v instanceof l)D=v,M("renewal-failed"),C=!1;try{let u=await q();if(u?.ownerId!==Q)M("taken-over",u);else if(!(Number(u?.expiresAt)>z()))M("expired",u)}catch{M("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(C&&!G&&!X)J0()}})();B=N,N.finally(()=>{if(B===N)B=null})},L),"unref"in Y)Y.unref();j("scheduled")}function G$(){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 N=await w();if(N.status==="live")return G$();if(N.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 w();if(C.status==="live")return G$();if(!k(N.identity,C))continue;if(!await _())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await _())return null;let v=await w(!1);if(!k(N.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 x(),R0=!1,null;break}finally{await c()}}if(!R0)return null;return J0(),{ownerId:Q,whenLost:()=>H,hasLost:()=>X!==void 0,assertOwned:async()=>{if(D)throw D;let L;try{let N=await q();if(L=N,!G&&!X&&N?.ownerId===Q&&Number(N?.expiresAt)>z())return;M(N?.ownerId!==Q?"taken-over":"expired",N)}catch(N){if(M("unreadable"),A&&N instanceof l)throw N}throw new h0({target:$.path,name:$.name,expectedOwnerId:Q,...typeof L?.ownerId==="string"?{observedOwnerId:L.ownerId}:{},...typeof L?.expiresAt==="number"?{observedExpiresAt:L.expiresAt}:{}})},release:async()=>{if(A&&W)return;G=!0,U(),await B;for(let L=0;L<F;L++){try{let N=!1;if(await j0(async()=>{let v;try{v=await q()}catch(u){if(A&&u.code==="ENOENT"){N=!0;return}throw u}if(v?.ownerId!==Q){N=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await _())return;await b(Z),N=!0})){if(A&&!N)throw new l(Z,"release-not-confirmed",{code:"EIO"});W=N;return}await i()}catch(N){if(A)throw N;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 I7=1,M1=16384,w$=30000,U3=/^[0-9a-f]{64}$/,T$=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),g$=new Set(["pending_queue_full"]);function j3($){if(!($ instanceof o0))return;if(T$.has($.code))return{code:$.code,disposition:"terminal"};if(g$.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function q3($){return H3.connect($)}function h$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function y$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function s0(){return new R("invalid-state","invalid Claustrum enrollment state")}function V3($){if(!h$($)||$.version!==I7||typeof $.proposedName!=="string"||$.proposedName.length===0)throw s0();if($.phase==="pending"){if(!U3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!V1($.createdAt)||!V1($.updatedAt))throw s0();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)||!y$($.tokenGeneration)||!V1($.updatedAt))throw s0();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"||!V1($.updatedAt))throw s0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw s0()}function M3($){if(!h$($)||!U3.test(String($.token??""))||!y$($.token_generation))throw new R("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function O7($){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 _$($){try{return JSON.parse($)}catch{throw new R("invalid-state","Claustrum enrollment file is not valid JSON")}}async function k0($){if(A)try{await z0(A0($));let J=await Y0($,!0);if(Buffer.byteLength(J)>M1)throw new R("unsafe-file","Claustrum enrollment file is too large");return _$(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await E$($,k$.O_RDONLY|k$.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new R("unsafe-file","Claustrum enrollment file could not be opened safely")}try{O7(await Z.stat());let J=Buffer.alloc(M1+1),{bytesRead:Q}=await Z.read(J,0,J.byteLength,0);if(Q>M1)throw new R("unsafe-file","Claustrum enrollment file is too large");return _$(J.subarray(0,Q).toString("utf8"))}finally{await Z.close()}}function f$($,Z){let J=[];for(let Q of $.split(`
|
|
10
|
+
`)){if(Q.trim()===""||Q.startsWith("#"))continue;let z=Q.split(":");if(z.length!==Z||!/^[^\s:,]+$/.test(z[0]??"")||!/^\d+$/.test(z[2]??"")||!Number.isSafeInteger(Number(z[2]))||Z===7&&(!/^\d+$/.test(z[3]??"")||!Number.isSafeInteger(Number(z[3])))||Z===4&&z[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(z[3]??""))return;J.push(z)}return J}async function P7($,Z,J){try{let[Q,z]=await Promise.all([K3(J.passwdPath??"/etc/passwd","utf8"),K3(J.groupPath??"/etc/group","utf8")]),Y=f$(Q,7),G=f$(z,4);if(!Y||!G)return!1;let W=Y.filter((j)=>Number(j[2])===$),X=G.filter((j)=>Number(j[2])===Z);if(W.length!==1||X.length!==1)return!1;let K=W[0]?.[0],H=X[0]?.[3]??"";return(H===""||H.split(",").every((j)=>j===K))&&!Y.some((j)=>Number(j[2])!==$&&Number(j[3])===Z)}catch{return!1}}function m$($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>K3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function v$($,Z={}){if(!A){let J=process.geteuid?.();if(J===void 0)return;let Q=process.getegid?.(),z;try{z=await F7($)}catch{return}let Y;for(;;){let G=await S$(z).catch(()=>{return});if(G&&(G.mode&18)!==0&&(G.mode&512)===0){if(Y===void 0)Y=Q!==void 0&&await P7(J,Q,Z);if((G.mode&2)!==0||G.uid!==J||G.gid!==Q||!Y)throw new R("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${z}. Another user could replace it. Run: chmod g-w,o-w ${z}`)}let W=A0(z);if(W===z)return;z=W}}try{await H0($,m$(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 D1($,Z={}){if(A){await z0($,!1,m$(Z));return}await D7($,{recursive:!0,mode:448});let J=await S$($),Q=process.geteuid?.();if(Q!==void 0&&J.uid!==Q)throw new R("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((J.mode&63)!==0)await M7($,448)}async function b0($,Z,J={}){let Q=A0($);await D1(Q,J),await v$(Q,J);let z=`${JSON.stringify(Z)}
|
|
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(`
|
|
11
12
|
`);super(`OpenCode or Pi processes are currently running:
|
|
12
13
|
${J}
|
|
13
14
|
|
|
14
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}function
|
|
15
|
-
`,$.length-
|
|
16
|
-
`,
|
|
15
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}function r7($=e,Z={}){let J=(Z.platform??process.platform)==="win32";return{async listRunningHosts(Q){let z=J?"tasklist":"ps",Y=J?["/fo","csv","/nh"]:["-eo","pid,command"],G;try{G=await $.run(z,Y,{env:Q})}catch{throw new L0}if(G.exitCode!==0)throw new L0;let W=G.stdout.split(/\r?\n/),X=[],K=process.pid;for(let H of W){let j=H.trim();if(!j)continue;let U,M;if(J){let D=j.split(",").map((B)=>B.replace(/^"|"$/g,""));if(D.length<2)throw new L0;M=D[0]??"",U=Number(D[1])}else{let D=/^(\d+)\s+(.+)$/.exec(j);if(!D){if(/^PID\s+COMMAND$/i.test(j))continue;throw new L0}U=Number(D[1]),M=D[2]??""}if(!Number.isInteger(U)||U<0)throw new L0;if(U===K)continue;if(X2.test(M))X.push({pid:U,command:M})}return X}}}var w3=r7(e);async function p0($=w3){let Z=await $.listRunningHosts();if(Z.length>0)throw new _1(Z)}class S0 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 e7($){try{return JSON.parse(await t7($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new S0("host-auth-invalid")}}async function H2($,Z){let J={...Z.env},Q=async()=>{try{f1(J)}catch{throw new S0("auth-content-refused")}await p0(Z.fence)};await Q();let z=Z.paths??await c0($,J);if($==="pi"){let X=K2("pi",await e7(z.hostAuthPath)),K=await T3({env:J,authPath:z.hostAuthPath}).inspect();if(K.slot==="placeholder"&&K.stash==="missing")throw new E1("missing-stash");if(X.kind!=="absent"&&K.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new S0("consent-required")}let Y=await N0($,J);await J2($,{env:J,runner:Z.runner,processFence:Q,...Z.enrollment});let G=Z.discover??(()=>j2({paths:z.paths,host:$,env:$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:J})),W=d0({paths:z.paths,host:$,vault:{env:J,discover:G}});try{await Q(),await W.vault.refresh();let X=await W.read(),K=X.accounts.find((H)=>H.id==="main");if(X.mode!=="claustrum"||!K?.accountIdentity||K.source!=="vault")throw new S0("primary-unverified");if(await Q(),$==="pi")await T3({env:J,authPath:z.hostAuthPath}).enterVault();return Y==="claustrum"?"already-vault":"committed"}finally{W.close()}}var Y4={"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 $1(){return($)=>$}var G4=$1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified"]),W4=$1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),X4=$1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused"]),K4=$1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),j4=$1()(["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"]),H4=new Set([new L0().message,...G4.map(($)=>new S0($).message),...W4.map(($)=>new W0($).message),...X4.map(($)=>new L2($).message),...K4.map(($)=>new E1($).message),...j4.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"]),U4=new Set(["opencode","litecode","opencode2","pi","host"]),q4=64,V4=256,M4=4096,g3=65536,D4=4096,F4=3,q2="[output beyond the diagnostic limit omitted]",L4="[output withheld: no line break within the inspected window]",N4="[detail withheld: the known credentials could not be read safely]",m3=new TextEncoder,N2=new TextDecoder;function $0($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function Z1($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!y3.isProxy($)}function B2($,Z){if(!Z1($)||!Array.isArray($))return;let J=$0($,"length");if(typeof J!=="number"||J>Z)return;let Q=[];for(let z=0;z<J;z+=1){let Y=Object.getOwnPropertyDescriptor($,String(z));if(Y===void 0||!("value"in Y))return;Q.push(Y.value)}return Q}function B4($){let Z=B2($,q4);if(Z===void 0||Z.length===0)return;let J=[];for(let Q of Z){if(!Z1(Q))return;let z=$0(Q,"pid"),Y=$0(Q,"command");if(typeof z!=="number"||!Number.isSafeInteger(z)||z<0)return;if(typeof Y!=="string"||!U4.has(Y.toLowerCase()))return;J.push({pid:z,command:Y})}return J}function I4($){try{if(!Z1($))return;let Z=$0($,"message");if(typeof Z!=="string")return;if(H4.has(Z))return Z;let J=$0($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let Q=B4($0($,"activeHosts"));if(Q&&Z===new _1(Q).message)return Z}catch{}return}function O4($,Z=[]){try{let J=new Set,Q=B2(Z,V4);if(Q===void 0)return;for(let Y of Q){if(typeof Y!=="string")return;if(Y!=="")J.add(Y)}if(!Z1($))return;let z=Reflect.ownKeys($);if(z.length>M4)return;for(let Y of z){if(typeof Y!=="string"||!M2(Y))continue;let G=Object.getOwnPropertyDescriptor($,Y);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 P4($,Z){let J=m3.encode($);if(J.length<=Z)return $;let Q=Math.max(0,Z);while(Q>0&&((J[Q]??0)&192)===128)Q-=1;return N2.decode(J.subarray(0,Q))}function C4($,Z){let J=m3.encode($);if(J.length<=Z)return $;let Q=J.length-Math.max(0,Z);while(Q<J.length&&((J[Q]??0)&192)===128)Q+=1;return N2.decode(J.subarray(Q))}function R4($,Z,J){let Q=$,z=!1;if($.length>g3){if(z=!0,J==="tail"){let X=$.indexOf(`
|
|
16
|
+
`,$.length-g3);Q=X===-1?"":$.slice(X+1)}else{let X=$.lastIndexOf(`
|
|
17
|
+
`,g3);Q=X===-1?"":$.slice(0,X)}if(Q==="")return[L4]}let Y=Z.redactText(Q).split(/\r?\n/);if(Y.length>1&&Y[Y.length-1]==="")Y.pop();if(J==="tail")Y.reverse();let G=[],W=D4;for(let X of Y){let K=m3.encode(X).length+1;if(K<=W){G.push(X),W-=K;continue}if(G.length===0)G.push(J==="tail"?C4(X,W-1):P4(X,W-1));z=!0;break}if(J==="tail")G.reverse();if(z)if(J==="tail")G.unshift(q2);else G.push(q2);return G}function b4($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(y3.isProxy(Z))break;let Q=$0(Z,"name");if(typeof Q==="string")return Q;Z=Object.getPrototypeOf(Z)}return"object"}function I2($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(y3.isProxy($))return["thrown proxy (not inspected)"];let J=[],Q=b4($),z=$0($,"message");J.push(typeof z==="string"?`${Q}: ${z}`:`${Q} (no message)`);let Y=$0($,"code");if(typeof Y==="string"||typeof Y==="number")J.push(`code: ${Y}`);let G=$0($,"stack");if(typeof G==="string")J.push(G);let W=$0($,"cause");if(W!==void 0)if(Z>=F4)J.push("caused by: [not described]");else J.push("caused by:",...I2(W,Z+1));return J}function V2($,Z){let J=$0($,Z);return typeof J==="string"&&J!==""?J:void 0}function A4($){if(!Z1($))return;let Z=V2($,"XDG_STATE_HOME"),J=V2($,"HOME"),Q=Z&&U2(Z)?Z:h3(J&&U2(J)?J:z4(),".local","state");return h3(Q,"cortexkit","anthropic-auth","diagnostics")}async function k4($,Z,J){try{let Q=A4($);if(Q===void 0)return;await J4(Q,{recursive:!0,mode:448});let z=await Z4(Q);if(!z.isDirectory())return;if(process.platform!=="win32"){if((z.mode&63)!==0)return;if(z.uid!==process.getuid?.())return}let Y=h3(Q,`${Z}-${Date.now()}-${process.pid}-${$4()}.log`),G=await Q4(Y,S1.O_WRONLY|S1.O_CREAT|S1.O_EXCL|(S1.O_NOFOLLOW??0),384);try{await G.writeFile(J,"utf8")}finally{await G.close()}return Y}catch{return}}async function O2($,Z,J,Q,z,Y){let G,W=O4(J,Q);if(W===void 0)G=[N4];else try{let j=F2(W);try{let{text:U,keep:M}=Y();G=R4(U,j,M)}finally{j.dispose()}}catch{G=["[failure detail could not be recorded]"]}let X=Y4[$],K=D2("error","cli",`${X} failed`,{stage:$,code:Z,...z}),H=await k4(J,$,`${[K,...G].join(`
|
|
17
18
|
`)}
|
|
18
|
-
`);return H===void 0?`${X} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${X} failed (${Z}). Details were written to ${H}`}async function
|
|
19
|
-
`),keep:"head"}))}async function
|
|
20
|
-
`),H=!1;for(let
|
|
21
|
-
`){if(
|
|
22
|
-
`){if(z&&
|
|
23
|
-
`)}var
|
|
24
|
-
`),
|
|
19
|
+
`);return H===void 0?`${X} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${X} failed (${Z}). Details were written to ${H}`}async function B0($,Z,J,Q=[]){let z=I4(Z);if(z!==void 0)return z;return O2($,`${$}/unexpected-error`,J,Q,{},()=>({text:I2(Z,0).join(`
|
|
20
|
+
`),keep:"head"}))}async function P2($,Z,J){return O2($,`${$}/installer-exit`,J,[],{exitCode:Number.isInteger(Z.exitCode)?Z.exitCode:null},()=>({text:typeof Z.stderr==="string"?Z.stderr:"",keep:"tail"}))}import{styleText as h1}from"node:util";import{stdout as a3,stdin as d2}from"node:process";import*as I0 from"node:readline";import l4 from"node:readline";var C2=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),R2=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},b2=($)=>{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 _4=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,f4=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,A2=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,E4=/\t{1,1000}/y,k2=/[\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,S4=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,x4=/\p{M}+/gu,w4={limit:1/0,ellipsis:""},_2=($,Z={},J={})=>{let Q=Z.limit??1/0,z=Z.ellipsis??"",Y=Z?.ellipsisWidth??(z?_2(z,w4,J).width:0),G=0,W=J.controlWidth??0,X=J.tabWidth??8,K=J.emojiWidth??2,H=2,j=J.regularWidth??1,U=J.wideWidth??2,M=[[S4,j],[_4,0],[f4,W],[E4,X],[k2,K],[A2,U]],D=0,B=0,I=$.length,T=0,m=!1,p=I,F=Math.max(0,Q-Y),q=0,P=0,O=0,E=0;$:while(!0){if(P>q||B>=I&&B>D){let S=$.slice(q,P)||$.slice(D,B);T=0;for(let h of S.replaceAll(x4,"")){let w=h.codePointAt(0)||0;if(R2(w))E=2;else if(b2(w))E=U;else E=j;if(O+E>F)p=Math.min(p,Math.max(q,D)+T);if(O+E>Q){m=!0;break $}T+=h.length,O+=E}q=P=0}if(B>=I)break $;for(let S=0,h=M.length;S<h;S++){let[w,k]=M[S];if(w.lastIndex=B,w.test($)){if(T=w===A2?C2($.slice(B,w.lastIndex)):w===k2?1:w.lastIndex-B,E=T*k,O+E>F)p=Math.min(p,B+Math.floor((F-O)/k));if(O+E>Q){m=!0;break $}O+=E,q=D,P=B,B=D=w.lastIndex;continue $}}B+=1}return{width:m?F:O,index:m?p:I,truncated:m,ellipsed:m&&Q>=Y}},f2=_2;var T4={limit:1/0,ellipsis:"",ellipsisWidth:0},g4=($,Z={})=>{return f2($,T4,Z).width},s=g4;var x1="\x1B",T2="",h4=39,c3="\x07",g2="[",y4="]",h2="m",p3=`${y4}8;;`,E2=new RegExp(`(?:\\${g2}(?<code>\\d+)m|\\${p3}(?<uri>.*)${c3})`,"y"),S2=($)=>{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},x2=($)=>`${x1}${g2}${$}${h2}`,w2=($)=>`${x1}${p3}${$}${c3}`,v3=($,Z,J)=>{let Q=Z[Symbol.iterator](),z=!1,Y=!1,G=$.at(-1),W=G===void 0?0:s(G),X=Q.next(),K=Q.next(),H=0;while(!X.done){let j=X.value,U=s(j);if(W+U<=J)$[$.length-1]+=j;else $.push(j),W=0;if(j===x1||j===T2)z=!0,Y=Z.startsWith(p3,H+1);if(z){if(Y){if(j===c3)z=!1,Y=!1}else if(j===h2)z=!1}else if(W+=U,W===J&&!K.done)$.push(""),W=0;X=K,K=Q.next(),H+=j.length}if(G=$.at(-1),!W&&G!==void 0&&G.length&&$.length>1)$[$.length-2]+=$.pop()},m4=($)=>{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("")},v4=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let Q="",z,Y,G=$.split(" "),W=[""],X=0;for(let j=0;j<G.length;j++){let U=G[j];if(J.trim!==!1){let D=W.at(-1)??"",B=D.trimStart();if(D.length!==B.length)W[W.length-1]=B,X=s(B)}if(j!==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 M=s(U);if(J.hard&&M>Z){let D=Z-X,B=1+Math.floor((M-D-1)/Z);if(Math.floor((M-1)/Z)<B)W.push("");v3(W,U,Z),X=s(W.at(-1)??"");continue}if(X+M>Z&&X&&M){if(J.wordWrap===!1&&X<Z){v3(W,U,Z),X=s(W.at(-1)??"");continue}W.push(""),X=0}if(X+M>Z&&J.wordWrap===!1){v3(W,U,Z),X=s(W.at(-1)??"");continue}W[W.length-1]+=U,X+=M}if(J.trim!==!1)W=W.map((j)=>m4(j));let K=W.join(`
|
|
21
|
+
`),H=!1;for(let j=0;j<K.length;j++){let U=K[j];if(Q+=U,!H){if(H=U>="\uD800"&&U<="\uDBFF",H)continue}else H=!1;if(U===x1||U===T2){E2.lastIndex=j+1;let D=E2.exec(K)?.groups;if(D?.code!==void 0){let B=Number.parseFloat(D.code);z=B===h4?void 0:B}else if(D?.uri!==void 0)Y=D.uri.length===0?void 0:D.uri}if(K[j+1]===`
|
|
22
|
+
`){if(Y)Q+=w2("");let M=z?S2(z):void 0;if(z&&M)Q+=x2(M)}else if(U===`
|
|
23
|
+
`){if(z&&S2(z))Q+=x2(z);if(Y)Q+=w2(Y)}}return Q},c4=/\r?\n/;function X0($,Z,J){return String($).normalize().split(c4).map((Q)=>v4(Q,Z,J)).join(`
|
|
24
|
+
`)}var a=p2(u3(),1);import{ReadStream as m2}from"node:tty";function u0($,Z,J){if(!J.some((G)=>!G.disabled))return $;let Q=$+Z,z=Math.max(J.length-1,0),Y=Q<0?z:Q>z?0:Q;return J[Y]?.disabled?u0(Y,Z<0?-1:1,J):Y}function w1($,Z,J,Q){let z=Q.split(`
|
|
25
|
+
`),Y=0,G=$;for(let X of z){if(G<=X.length)break;G-=X.length+1,Y++}for(Y=Math.max(0,Math.min(z.length-1,Y+J)),G=Math.min(G,z[Y].length)+Z;G<0&&Y>0;)Y--,G+=z[Y].length+1;for(;G>z[Y].length&&Y<z.length-1;)G-=z[Y].length+1,Y++;G=Math.max(0,Math.min(z[Y].length,G));let W=0;for(let X=0;X<Y;X++)W+=z[X].length+1;return W+G}var i4=["up","down","left","right","space","enter","cancel"],a4=["January","February","March","April","May","June","July","August","September","October","November","December"],d={actions:new Set(i4),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:[...a4],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 n4($){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 n3($,Z){if(typeof $=="string")return d.aliases.get($)===Z;for(let J of $)if(J!==void 0&&n3(J,Z))return!0;return!1}function s4($,Z){if($===Z)return;let J=$.split(`
|
|
25
26
|
`),Q=Z.split(`
|
|
26
|
-
`),z=Math.max(J.length,Q.length),
|
|
27
|
-
`).map((
|
|
28
|
-
`)}function
|
|
29
|
-
`),
|
|
30
|
-
`).length-1;this.output.write(
|
|
31
|
-
`);this.output.write(G[
|
|
32
|
-
`).slice(
|
|
33
|
-
`)),this._prevFrame=$;return}}this.output.write(d.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function K4($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((Q)=>Q.value===$);return J!==-1?J:0}function H4($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function F4($,Z){if(Z)return $?Z:Z[0]}var U4=class extends X0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#J="";#Z;#W;#X;#z;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return V1(["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}${V1("inverse",J)}${Q}`}get options(){return typeof this.#W=="function"?this.#W():this.#W}constructor(Z){super(Z),this.#W=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??H4;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 W=J.findIndex((G)=>G.value===z);W!==-1&&(this.toggleSelected(z),this.#$=W)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(z,W)=>this.#Q(z,W)),this.on("userInput",(z)=>this.#Y(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",W=J.name==="return",G=this.userInput===""||this.userInput==="\t",Y=this.#X,X=this.options,j=Y!==void 0&&Y!==""&&X.some((H)=>!H.disabled&&(this.#Z?this.#Z(Y,H):!0));if(J.name==="tab"&&G&&j){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(Y,!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.#$=b0(this.#$,Q?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):W?this.value=F4(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])}#Y(Z){if(Z!==this.#J){this.#J=Z;let J=this.options;Z&&this.#Z?this.filteredOptions=J.filter((W)=>this.#Z?.(Z,W)):this.filteredOptions=[...J];let Q=K4(this.focusedValue,this.filteredOptions);this.#$=b0(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 b3 extends X0{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(d.cursor.move(0,-1)),this.value=Z,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var q4={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function J2($){return[...$].map((Z)=>q4[Z])}function V4($){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 N3($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function q1($){return{year:N3($.year),month:N3($.month),day:N3($.day)}}function P3($,Z){return new Date($||2001,Z||1,0).getDate()}function X2($){let{year:Z,month:J,day:Q}=q1($);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 Q2($){let Z=X2($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function M4($,Z,J,Q){let z=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,W=Q?{year:Q.getUTCFullYear(),month:Q.getUTCMonth()+1,day:Q.getUTCDate()}:null;return $==="year"?{min:z?.year??1,max:W?.year??9999}:$==="month"?{min:z&&Z.year===z.year?z.month:1,max:W&&Z.year===W.year?W.month:12}:{min:z&&Z.year===z.year&&Z.month===z.month?z.day:1,max:W&&Z.year===W.year&&Z.month===W.month?W.day:P3(Z.year,Z.month)}}class j2 extends X0{#$;#J;#Z;#W;#X;#z={segmentIndex:0,positionInSegment:0};#Q=!0;#Y=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)}#G(){this._setUserInput(this.#H(this.#Z)),this._setValue(Q2(this.#Z)??void 0)}constructor($){let Z=$.format?{segments:J2($.format),separator:$.separator??"/"}:V4($.locale),J=$.separator??Z.separator,Q=$.format?J2($.format):Z.segments,z=$.initialValue??$.defaultValue,W=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((Y)=>W[Y.type]).join(J);super({...$,initialUserInput:G},!1),this.#$=Q,this.#J=J,this.#Z=W,this.#W=$.minDate,this.#X=$.maxDate,this.#G(),this.on("cursor",(Y)=>this.#q(Y)),this.on("key",(Y,X)=>this.#V(Y,X)),this.on("finalize",()=>this.#M($))}#j(){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:$}}#K($){this.inlineError="",this.#Y=null;let Z=this.#j();Z&&(this.#z.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#z.positionInSegment=0,this.#Q=!0)}#F($){let Z=this.#j();if(!Z)return;let{segment:J}=Z,Q=this.#Z[J.type],z=!Q||Q.replace(/_/g,"")==="",W=Number.parseInt((Q||"0").replace(/_/g,"0"),10)||0,G=M4(J.type,q1(this.#Z),this.#W,this.#X),Y;z?Y=$===1?G.min:G.max:Y=Math.max(Math.min(G.max,W+$),G.min),this.#Z={...this.#Z,[J.type]:Y.toString().padStart(J.len,"0")},this.#Q=!0,this.#Y=null,this.#G()}#q($){if($)switch($){case"right":return this.#K(1);case"left":return this.#K(-1);case"up":return this.#F(1);case"down":return this.#F(-1)}}#V($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#j();if(!J)return;if(!this.#Z[J.segment.type].replace(/_/g,"")){this.#K(-1);return}this.#Z[J.segment.type]="_".repeat(J.segment.len),this.#Q=!0,this.#z.positionInSegment=0,this.#G();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#j();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.#j();if(!J)return;let{segment:Q}=J,z=!this.#Z[Q.type].replace(/_/g,"");if(this.#Q&&this.#Y!==null&&!z){let U=this.#Y+$,V={...this.#Z,[Q.type]:U},q=this.#U(V,Q);if(q){this.inlineError=q,this.#Y=null,this.#Q=!1;return}this.inlineError="",this.#Z[Q.type]=U,this.#Y=null,this.#Q=!1,this.#G(),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.#Y=null;let W=this.#Z[Q.type],G=W.indexOf("_"),Y=G>=0?G:Math.min(this.#z.positionInSegment,Q.len-1);if(Y<0||Y>=Q.len)return;let X=W.slice(0,Y)+$+W.slice(Y+1),j=!1;if(Y===0&&W==="__"&&(Q.type==="month"||Q.type==="day")){let U=Number.parseInt($,10);X=`0${$}`,j=U<=(Q.type==="month"?1:2)}if(Q.type==="year"&&(X=(W.replace(/_/g,"")+$).padStart(Q.len,"_")),!X.includes("_")){let U={...this.#Z,[Q.type]:X},V=this.#U(U,Q);if(V){this.inlineError=V;return}}this.inlineError="",this.#Z[Q.type]=X;let H=X.includes("_")?void 0:X2(this.#Z);if(H){let{year:U,month:V}=H,q=P3(U,V);this.#Z={year:String(Math.max(0,Math.min(9999,U))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,V))).padStart(2,"0"),day:String(Math.max(1,Math.min(q,H.day))).padStart(2,"0")}}this.#G();let K=X.indexOf("_");j?(this.#Q=!0,this.#Y=$):K>=0?this.#z.positionInSegment=K: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(Y+1,Q.len-1)}}#U($,Z){let{month:J,day:Q}=q1($);if(Z.type==="month"&&(J<0||J>12))return v.date.messages.invalidMonth;if(Z.type==="day"&&(Q<0||Q>31))return v.date.messages.invalidDay(31,"any month")}#M($){let{year:Z,month:J,day:Q}=q1(this.#Z);if(Z&&J&&Q){let z=P3(Z,J);this.#Z={...this.#Z,day:String(Math.min(Q,z)).padStart(2,"0")}}this.value=Q2(this.#Z)??$.defaultValue??void 0}}var D4=class extends X0{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((W)=>W.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((W)=>({...W,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}})}},L4=new Set(["up","down","left","right"]);class K2 extends X0{#$=!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===`
|
|
27
|
+
`),z=Math.max(J.length,Q.length),Y=[];for(let G=0;G<z;G++)J[G]!==Q[G]&&Y.push(G);return{lines:Y,numLinesBefore:J.length,numLinesAfter:Q.length,numLines:z}}var o4=globalThis.process.platform.startsWith("win"),y1=Symbol("clack:cancel");function O0($){return $===y1}function T1($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}function u2({input:$=d2,output:Z=a3,overwrite:J=!0,hideCursor:Q=!0}={}){let z=I0.createInterface({input:$,output:Z,prompt:"",tabSize:1});I0.emitKeypressEvents($,z),$ instanceof m2&&$.isTTY&&$.setRawMode(!0);let Y=(G,{name:W,sequence:X})=>{let K=String(G);if(n3([K,W,X],"cancel")){Q&&Z.write(a.cursor.show),process.exit(0);return}if(!J)return;I0.moveCursor(Z,W==="return"?0:-1,W==="return"?-1:0,()=>{I0.clearLine(Z,1,()=>{$.once("keypress",Y)})})};return Q&&Z.write(a.cursor.hide),$.once("keypress",Y),()=>{$.off("keypress",Y),Q&&Z.write(a.cursor.show),$ instanceof m2&&$.isTTY&&!o4&&$.setRawMode(!1),z.terminal=!1,z.close()}}var J1=($)=>("columns"in $)&&typeof $.columns=="number"?$.columns:80,s3=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function Q1($,Z,J,Q=J,z=J,Y){let G=J1($??a3);return X0(Z,G-J.length,{hard:!0,trim:!1}).split(`
|
|
28
|
+
`).map((W,X,K)=>{let H=Y?Y(W,X):W;return X===0?`${Q}${H}`:X===K.length-1?`${z}${H}`:`${J}${H}`}).join(`
|
|
29
|
+
`)}function l2($,Z){if("~standard"in $){let J=$["~standard"].validate(Z);return J instanceof Promise?J.then((Q)=>Q.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 n4(this.opts.accessible)}constructor($,Z=!0){let{input:J=d2,output:Q=a3,render:z,signal:Y,...G}=$;this.opts=G,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=z.bind(this),this._track=Z,this._abortSignal=Y,this.input=J,this.output=Q}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($)??[],Q=[];for(let z of J)z.cb(...Z),z.once&&Q.push(()=>J.splice(J.indexOf(z),1));for(let z of Q)z()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(y1);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=l4.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),T1(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),T1(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(a.cursor.show),this.output.off("resize",this.render),T1(this.input,!1),$(y1)})})}_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=l2(this.opts.validate,this.value),Q;J instanceof Promise?(this.state="validating",this.render(),Q=await J):Q=J,Q&&(this.error=Q instanceof Error?Q.message:Q,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}n3([$,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
|
+
`),T1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=X0(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
31
|
+
`).length-1;this.output.write(a.cursor.move(-999,$*-1))}render(){let $=X0(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=s4(this._prevFrame,$),J=s3(this.output);if(this.restoreCursor(),Z){let Q=Math.max(0,Z.numLinesAfter-J),z=Math.max(0,Z.numLinesBefore-J),Y=Z.lines.find((G)=>G>=Q);if(Y===void 0){this._prevFrame=$;return}if(Z.lines.length===1){this.output.write(a.cursor.move(0,Y-z)),this.output.write(a.erase.lines(1));let G=$.split(`
|
|
32
|
+
`);this.output.write(G[Y]),this._prevFrame=$,this.output.write(a.cursor.move(0,G.length-Y-1));return}else if(Z.lines.length>1){if(Q<z)Y=Q;else{let W=Y-z;W>0&&this.output.write(a.cursor.move(0,W))}this.output.write(a.erase.down());let G=$.split(`
|
|
33
|
+
`).slice(Y);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 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===`
|
|
34
35
|
`?`${Z}█
|
|
35
|
-
${Q}`:`${Z}${
|
|
36
|
+
${Q}`:`${Z}${h1("inverse",J)}${Q}`}get cursor(){return this._cursor}#Z($){if(this.userInput.length===0){this._setUserInput($);return}this._setUserInput(this.userInput.slice(0,this.cursor)+$+this.userInput.slice(this.cursor))}#Y($){let Z=this.value??"";switch($){case"up":this._cursor=w1(this._cursor,0,-1,Z);return;case"down":this._cursor=w1(this._cursor,0,1,Z);return;case"left":this._cursor=w1(this._cursor,-1,0,Z);return;case"right":this._cursor=w1(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#J)return this.focused==="submit"?!0:(this.#Z(`
|
|
36
37
|
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
37
38
|
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#Z(`
|
|
38
|
-
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#J=$.showSubmit??!1,this.on("key",(J,Q)=>{if(Q?.name&&
|
|
39
|
-
`);I.push(E),
|
|
39
|
+
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#J=$.showSubmit??!1,this.on("key",(J,Q)=>{if(Q?.name&&Y8.has(Q.name)){this.#$=!1,this.#Y(Q.name);return}if(J==="\t"&&this.#J){this.focused=this.focused==="editor"?"submit":"editor";return}if(Q?.name!=="return"){if(this.#$=!1,Q?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(Q?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}J&&(this.#J&&this.focused==="submit"&&(this.focused="editor"),this.#Z(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 r3 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?u0(Z,1,this.options):Z,this.on("key",(J,Q)=>{Q.name==="a"&&this.toggleAll(),Q.name==="i"&&this.toggleInvert()}),this.on("cursor",(J)=>{switch(J){case"left":case"up":this.cursor=u0(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=u0(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class t3 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),Q=$.slice(this.cursor+1);return`${Z}${h1("inverse",J)}${Q}`}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 DJ}from"node:util";import Z0 from"node:process";var Y1=p2(u3(),1);function G8(){if(Z0.platform!=="win32")return Z0.env.TERM!=="linux";return Boolean(Z0.env.CI)||Boolean(Z0.env.WT_SESSION)||Boolean(Z0.env.TERMINUS_SUBLIME)||Z0.env.ConEmuTask==="{cmd::Cmder}"||Z0.env.TERM_PROGRAM==="Terminus-Sublime"||Z0.env.TERM_PROGRAM==="vscode"||Z0.env.TERM==="xterm-256color"||Z0.env.TERM==="alacritty"||Z0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var e3=G8(),W8=()=>process.env.CI==="true";var g=($,Z)=>e3?$:Z,s2=g("◆","*"),Q9=g("■","x"),z9=g("▲","x"),m1=g("◇","o"),X8=g("┌","T"),f=g("│","|"),C0=g("└","—"),BJ=g("┐","T"),IJ=g("┘","—"),o2=g("●",">"),r2=g("○"," "),K8=g("◻","[•]"),t2=g("◼","[+]"),e2=g("◻","[ ]"),OJ=g("▪","•"),$9=g("─","-"),j8=g("╮","+"),H8=g("├","+"),U8=g("╯","+"),q8=g("╰","+"),PJ=g("╭","+"),V8=g("●","•"),M8=g("◆","*"),D8=g("▲","!"),F8=g("■","x"),$$=($)=>{switch($){case"initial":case"active":return V("cyan",s2);case"cancel":return V("red",Q9);case"error":return V("yellow",z9);case"submit":return V("green",m1);case"validating":return V("dim",s2)}},L8=($)=>{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 N8($,Z){let J=[`${Z?`${V("cyan",f)} `:""}${$.join(" • ")}`];return Z&&J.push(V("cyan",C0)),J}var Z9=($,Z,J,Q,z,Y=!1)=>{let G=Z,W=0;if(Y)for(let X=Q-1;X>=J;X--){let K=$[X];if(K&&(G-=K.length),W++,G<=z)break}else for(let X=J;X<Q;X++){let K=$[X];if(K&&(G-=K.length),W++,G<=z)break}return{lineCount:G,removals:W}},J9=({cursor:$,options:Z,style:J,output:Q=process.stdout,maxItems:z=Number.POSITIVE_INFINITY,columnPadding:Y=0,rowPadding:G=4})=>{let W=J1(Q)-Y,X=s3(Q),K=V("dim","..."),H=Math.max(X-G,0),j=Math.max(Math.min(z,H),5),U=0;$>=j-3&&(U=Math.max(Math.min($-j+3,Z.length-j),0));let M=j<Z.length&&U>0,D=j<Z.length&&U+j<Z.length,B=Math.min(U+j,Z.length),I=[],T=0;M&&T++,D&&T++;let m=U+(M?1:0),p=B-(D?1:0);for(let q=m;q<p;q++){let P=Z[q],O=P?J(P,q===$):"",E=X0(O,W,{hard:!0,trim:!1}).split(`
|
|
40
|
+
`);I.push(E),T+=E.length}if(T>H){let q=0,P=0,O=T,E=$-m,S=H,h=()=>Z9(I,O,0,E,S),w=()=>Z9(I,O,E+1,I.length,S,!0);M?({lineCount:O,removals:q}=h(),O>S&&(D||(S-=1),{lineCount:O,removals:P}=w())):(D||(S-=1),{lineCount:O,removals:P}=w(),O>S&&(S-=1,{lineCount:O,removals:q}=h())),q>0&&(M=!0,I.splice(0,q)),P>0&&(D=!0,I.splice(I.length-P,P))}let F=[];M&&F.push(K);for(let q of I)for(let P of q)F.push(P);return D&&F.push(K),F};var Z$=($)=>{let Z=$.active??"Yes",J=$.inactive??"No";return new o3({active:Z,inactive:J,signal:$.signal,input:$.input,output:$.output,initialValue:$.initialValue??!0,render(){let Q=$.withGuide??d.withGuide,z=`${$$(this.state)} `,Y=Q?`${V("gray",f)} `:"",G=Q1($.output,$.message,Y,z),W=`${Q?`${V("gray",f)}
|
|
40
41
|
`:""}${G}
|
|
41
|
-
`,X=this.value?Z:J;switch(this.state){case"submit":{let
|
|
42
|
-
${
|
|
43
|
-
${
|
|
44
|
-
`:` ${
|
|
42
|
+
`,X=this.value?Z:J;switch(this.state){case"submit":{let K=Q?`${V("gray",f)} `:"";return`${W}${K}${V("dim",X)}`}case"cancel":{let K=Q?`${V("gray",f)} `:"";return`${W}${K}${V(["strikethrough","dim"],X)}${Q?`
|
|
43
|
+
${V("gray",f)}`:""}`}default:{let K=Q?`${V("cyan",f)} `:"",H=Q?V("cyan",C0):"";return`${W}${K}${this.value?`${V("green",o2)} ${Z}`:`${V("dim",r2)} ${V("dim",Z)}`}${$.vertical?Q?`
|
|
44
|
+
${V("cyan",f)} `:`
|
|
45
|
+
`:` ${V("dim","/")} `}${this.value?`${V("dim",r2)} ${V("dim",J)}`:`${V("green",o2)} ${J}`}
|
|
45
46
|
${H}
|
|
46
|
-
`}}}}).prompt()};var
|
|
47
|
+
`}}}}).prompt()};var B8=[`${V("dim","↑/↓")} to navigate`,`${V("dim","Space:")} select`,`${V("dim","Enter:")} confirm`],z1=($,Z)=>$.split(`
|
|
47
48
|
`).map((J)=>Z(J)).join(`
|
|
48
|
-
`),
|
|
49
|
-
${
|
|
50
|
-
`:""}${
|
|
51
|
-
`,
|
|
52
|
-
${
|
|
53
|
-
`).map((
|
|
54
|
-
`),
|
|
49
|
+
`),Y9=($)=>{let Z=(z,Y)=>{let G=z.label??String(z.value);return Y==="disabled"?`${V("gray",e2)} ${z1(G,(W)=>V(["strikethrough","gray"],W))}${z.hint?` ${V("dim",`(${z.hint??"disabled"})`)}`:""}`:Y==="active"?`${V("cyan",K8)} ${G}${z.hint?` ${V("dim",`(${z.hint})`)}`:""}`:Y==="selected"?`${V("green",t2)} ${z1(G,(W)=>V("dim",W))}${z.hint?` ${V("dim",`(${z.hint})`)}`:""}`:Y==="cancelled"?`${z1(G,(W)=>V(["strikethrough","dim"],W))}`:Y==="active-selected"?`${V("green",t2)} ${G}${z.hint?` ${V("dim",`(${z.hint})`)}`:""}`:Y==="submitted"?`${z1(G,(W)=>V("dim",W))}`:`${V("dim",e2)} ${z1(G,(W)=>V("dim",W))}`},J=$.required??!0,Q=$.showInstructions??!0;return new r3({options:$.options,signal:$.signal,input:$.input,output:$.output,initialValues:$.initialValues,required:J,cursorAt:$.cursorAt,validate(z){if(J&&(z===void 0||z.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 z=$.withGuide??d.withGuide,Y=Q1($.output,$.message,z?`${L8(this.state)} `:"",`${$$(this.state)} `),G=`${z?`${V("gray",f)}
|
|
51
|
+
`:""}${Y}
|
|
52
|
+
`,W=this.value??[],X=(K,H)=>{if(K.disabled)return Z(K,"disabled");let j=W.includes(K.value);return H&&j?Z(K,"active-selected"):j?Z(K,"selected"):Z(K,H?"active":"inactive")};switch(this.state){case"submit":{let K=this.options.filter(({value:j})=>W.includes(j)).map((j)=>Z(j,"submitted")).join(V("dim",", "))||V("dim","none"),H=Q1($.output,K,z?`${V("gray",f)} `:"");return`${G}${H}`}case"cancel":{let K=this.options.filter(({value:j})=>W.includes(j)).map((j)=>Z(j,"cancelled")).join(V("dim",", "));if(K.trim()==="")return`${G}${V("gray",f)}`;let H=Q1($.output,K,z?`${V("gray",f)} `:"");return`${G}${H}${z?`
|
|
53
|
+
${V("gray",f)}`:""}`}case"error":{let K=z?`${V("yellow",f)} `:"",H=this.error.split(`
|
|
54
|
+
`).map((M,D)=>D===0?`${z?`${V("yellow",C0)} `:""}${V("yellow",M)}`:` ${M}`).join(`
|
|
55
|
+
`),j=G.split(`
|
|
55
56
|
`).length,U=H.split(`
|
|
56
|
-
`).length+1;return`${G}${
|
|
57
|
-
${
|
|
57
|
+
`).length+1;return`${G}${K}${J9({output:$.output,options:this.options,cursor:this.cursor,maxItems:$.maxItems,columnPadding:K.length,rowPadding:j+U,style:X}).join(`
|
|
58
|
+
${K}`)}
|
|
58
59
|
${H}
|
|
59
|
-
`}default:{let
|
|
60
|
-
`).length,
|
|
61
|
-
`),
|
|
62
|
-
${
|
|
60
|
+
`}default:{let K=z?`${V("cyan",f)} `:"",H=G.split(`
|
|
61
|
+
`).length,j=Q?N8(B8,z):z?[V("cyan",C0)]:[],U=j.join(`
|
|
62
|
+
`),M=j.length+1;return`${G}${K}${J9({output:$.output,options:this.options,cursor:this.cursor,maxItems:$.maxItems,columnPadding:K.length,rowPadding:H+M,style:X}).join(`
|
|
63
|
+
${K}`)}
|
|
63
64
|
${U}
|
|
64
|
-
`}}}}).prompt()};var
|
|
65
|
-
`);if(
|
|
65
|
+
`}}}}).prompt()};var y={message:($=[],{symbol:Z=V("gray",f),secondarySymbol:J=V("gray",f),output:Q=process.stdout,spacing:z=1,withGuide:Y}={})=>{let G=[],W=Y??d.withGuide,X=W?J:"",K=W?`${Z} `:"",H=W?`${J} `:"";for(let U=0;U<z;U++)G.push(X);let j=Array.isArray($)?$:$.split(`
|
|
66
|
+
`);if(j.length>0){let[U,...M]=j;U.length>0?G.push(`${K}${U}`):G.push(W?Z:"");for(let D of M)D.length>0?G.push(`${H}${D}`):G.push(W?J:"")}Q.write(`${G.join(`
|
|
66
67
|
`)}
|
|
67
|
-
`)},info:($,Z)=>{
|
|
68
|
-
`)},
|
|
69
|
-
${
|
|
68
|
+
`)},info:($,Z)=>{y.message($,{...Z,symbol:V("blue",V8)})},success:($,Z)=>{y.message($,{...Z,symbol:V("green",M8)})},step:($,Z)=>{y.message($,{...Z,symbol:V("green",m1)})},warn:($,Z)=>{y.message($,{...Z,symbol:V("yellow",D8)})},warning:($,Z)=>{y.warn($,Z)},error:($,Z)=>{y.message($,{...Z,symbol:V("red",F8)})}};var G9=($="",Z)=>{let J=Z?.output??process.stdout,Q=Z?.withGuide??d.withGuide?`${V("gray",X8)} `:"";J.write(`${Q}${$}
|
|
69
|
+
`)},K0=($="",Z)=>{let J=Z?.output??process.stdout,Q=Z?.withGuide??d.withGuide?`${V("gray",f)}
|
|
70
|
+
${V("gray",C0)} `:"";J.write(`${Q}${$}
|
|
70
71
|
|
|
71
|
-
`)};var
|
|
72
|
-
`),
|
|
73
|
-
`).map(
|
|
74
|
-
`),H=z?`${
|
|
75
|
-
`:"",
|
|
76
|
-
${
|
|
77
|
-
${
|
|
78
|
-
`)};var
|
|
79
|
-
`);let b=
|
|
80
|
-
`);b.length>1&&J.write(
|
|
81
|
-
`);let
|
|
82
|
-
`):J.write(`${
|
|
83
|
-
`)),
|
|
84
|
-
`:""}${
|
|
85
|
-
`,Q=$.placeholder&&$.placeholder.length>0?
|
|
86
|
-
${
|
|
87
|
-
`}case"error":{let G=this.error?` ${
|
|
88
|
-
${
|
|
72
|
+
`)};var I8=($)=>$,O8=($,Z,J)=>{let Q={hard:!0,trim:!1},z=X0($,Z,Q).split(`
|
|
73
|
+
`),Y=z.reduce((X,K)=>Math.max(s(K),X),0),G=z.map(J).reduce((X,K)=>Math.max(s(K),X),0),W=Z-(G-Y);return X0($,W,Q)},v1=($="",Z="",J)=>{let Q=J?.output??Z0.stdout,z=J?.withGuide??d.withGuide,Y=J?.format??I8,G=["",...O8($,J1(Q)-6,Y).split(`
|
|
74
|
+
`).map(Y),""],W=s(Z),X=Math.max(G.reduce((U,M)=>{let D=s(M);return D>U?D:U},0),W)+2,K=G.map((U)=>`${V("gray",f)} ${U}${" ".repeat(X-s(U))}${V("gray",f)}`).join(`
|
|
75
|
+
`),H=z?`${V("gray",f)}
|
|
76
|
+
`:"",j=z?H8:q8;Q.write(`${H}${V("green",m1)} ${V("reset",Z)} ${V("gray",$9.repeat(Math.max(X-W-1,1))+j8)}
|
|
77
|
+
${K}
|
|
78
|
+
${V("gray",j+$9.repeat(X+2)+U8)}
|
|
79
|
+
`)};var P8=($)=>V("magenta",$),W9=({indicator:$="dots",onCancel:Z,output:J=process.stdout,cancelMessage:Q,errorMessage:z,frames:Y=e3?["◒","◐","◓","◑"]:["•","o","O","0"],delay:G=e3?80:120,signal:W,...X}={})=>{let K=W8(),H,j,U=!1,M=!1,D="",B,I=performance.now(),T=J1(J),m=X?.styleFrame??P8,p=(b)=>{let c=b>1?z??d.messages.error:Q??d.messages.cancel;M=b===1,U&&(_(c,b),M&&typeof Z=="function"&&Z())},F=()=>p(2),q=()=>p(1),P=()=>{process.on("uncaughtExceptionMonitor",F),process.on("unhandledRejection",F),process.on("SIGINT",q),process.on("SIGTERM",q),process.on("exit",p),W&&W.addEventListener("abort",q)},O=()=>{process.removeListener("uncaughtExceptionMonitor",F),process.removeListener("unhandledRejection",F),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q),process.removeListener("exit",p),W&&W.removeEventListener("abort",q)},E=()=>{if(B===void 0)return;K&&J.write(`
|
|
80
|
+
`);let b=X0(B,T,{hard:!0,trim:!1}).split(`
|
|
81
|
+
`);b.length>1&&J.write(Y1.cursor.up(b.length-1)),J.write(Y1.cursor.to(0)),J.write(Y1.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]`},w=X.withGuide??d.withGuide,k=(b="")=>{U=!0,H=u2({output:J}),D=S(b),I=performance.now(),w&&J.write(`${V("gray",f)}
|
|
82
|
+
`);let c=0,o=0;P(),j=setInterval(()=>{if(K&&D===B)return;E(),B=D;let i=m(Y[c]),j0;if(K)j0=`${i} ${D}...`;else if($==="timer")j0=`${i} ${D} ${h(I)}`;else{let J0=".".repeat(Math.floor(o)).slice(0,3);j0=`${i} ${D}${J0}`}let x=X0(j0,T,{hard:!0,trim:!1});J.write(x),c=c+1<Y.length?c+1:0,o=o<4?o+0.125:0},G)},_=(b="",c=0,o=!1)=>{if(!U)return;U=!1,clearInterval(j),E();let i=c===0?V("green",m1):c===1?V("red",Q9):V("red",z9);D=b??D,o||($==="timer"?J.write(`${i} ${D} ${h(I)}
|
|
83
|
+
`):J.write(`${i} ${D}
|
|
84
|
+
`)),O(),H()};return{start:k,stop:(b="")=>_(b,0),message:(b="")=>{D=S(b??D)},cancel:(b="")=>_(b,1),error:(b="")=>_(b,2),clear:()=>_("",0,!0),get isCancelled(){return M}}},CJ={light:g("─","-"),heavy:g("━","="),block:g("█","#")};var RJ=[`${V("dim","↑/↓")} to navigate`,`${V("dim","Enter:")} confirm`];var bJ=`${V("gray",f)} `;var X9=($)=>new t3({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
|
+
`:""}${$$(this.state)} `}${$.message}
|
|
86
|
+
`,Q=$.placeholder&&$.placeholder.length>0?V("inverse",$.placeholder[0])+V("dim",$.placeholder.slice(1)):V(["inverse","hidden"],"_"),z=this.userInput?this.userInputWithCursor:Q,Y=this.value??"";switch(this.state){case"validating":{let G=Z?`${V("cyan",f)} `:"",W=Z?V("cyan",C0):"",X=V("dim",z),K=V("dim","Validating...");return`${J}${G}${X}
|
|
87
|
+
${W} ${K}
|
|
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}${z}
|
|
89
90
|
${X}${G}
|
|
90
|
-
`}case"submit":{let G=
|
|
91
|
-
${
|
|
92
|
-
${
|
|
93
|
-
`}}}}).prompt();import{existsSync as
|
|
91
|
+
`}case"submit":{let G=Y?`${Z?" ":""}${V("dim",Y)}`:"",W=Z?V("gray",f):"";return`${J}${W}${G}`}case"cancel":{let G=Y?` ${V(["strikethrough","dim"],Y)}`:"",W=Z?V("gray",f):"";return`${J}${W}${G}${Y.trim()?`
|
|
92
|
+
${W}`:""}`}default:{let G=Z?`${V("cyan",f)} `:"",W=Z?V("cyan",C0):"";return`${J}${G}${z}
|
|
93
|
+
${W}
|
|
94
|
+
`}}}}).prompt();import{existsSync as l1}from"node:fs";import{join as i0}from"node:path";import{accessSync as C8,constants as K9,statSync as R8}from"node:fs";import{delimiter as b8,extname as A8,resolve as k8}from"node:path";function G1($,Z,J){let Q=J==="win32",z=Q?[`${$}.exe`,`${$}.cmd`,`${$}.bat`,$]:[$];for(let Y of(Z.PATH??"").split(Q?";":b8)){if(!Y)continue;for(let G of z){let W=k8(Y,G);try{if(C8(W,Q?K9.F_OK:K9.X_OK),R8(W).isFile())return W}catch{}}}return null}async function c1($,Z,J,Q){if(!$)return null;let z=A8($).toLowerCase(),Y=Q==="win32"&&(z===".cmd"||z===".bat");try{return await J.run(Y?Z.ComSpec||Z.COMSPEC||"cmd.exe":$,Y?["/d","/s","/c",$,"--version"]:["--version"],{env:Z})}catch{return null}}import{existsSync as _8,readFileSync as f8}from"node:fs";import{applyEdits as j9,format as E8,modify as J$,parse as H9}from"jsonc-parser";function W1($){if(!_8($))return{value:null,text:"",exists:!1};let Z=f8($,"utf8"),J=[],Q=H9(Z,J,{allowTrailingComma:!0});return{value:J.length===0?Q:null,text:Z,exists:!0}}function Q$($,Z,J,Q){let Y=H9($,[],{allowTrailingComma:!0})??{};for(let j of Z)if(typeof Y==="object"&&Y!==null)Y=Y[j];else{Y=void 0;break}let G=Array.isArray(Y)?Y:[],W=G.findIndex((j)=>typeof j==="string"&&Q(j));if(W!==-1&&G[W]===J)return{text:$,changed:!1};let X;if(W!==-1)X=J$($,[...Z,W],J,{formattingOptions:{insertSpaces:!0,tabSize:2}});else if(!Array.isArray(Y))X=J$($,Z,[J],{formattingOptions:{insertSpaces:!0,tabSize:2}});else X=J$($,[...Z,G.length],J,{formattingOptions:{insertSpaces:!0,tabSize:2}});let K=j9($,X);return{text:j9(K,E8(K,void 0,{insertSpaces:!0,tabSize:2})),changed:!0}}import{existsSync as p1}from"node:fs";import{mkdir as V9,writeFile as d1}from"node:fs/promises";import{join as u1}from"node:path";function M9($){return $===l0||$.startsWith(`${l0}@`)}function z$($){let Z=u1($,"opencode.jsonc");if(p1(Z))return{path:Z,exists:!0};let J=u1($,"opencode.json");if(p1(J))return{path:J,exists:!0};return{path:Z,exists:!1}}function S8($){let Z=u1($,"tui.jsonc");if(p1(Z))return{path:Z,exists:!0};let J=u1($,"tui.json");if(p1(J))return{path:J,exists:!0};return{path:Z,exists:!1}}async function D9($,Z=process.env){let J=E0(Z);await V9(J,{recursive:!0});let{path:Q,exists:z}=z$(J),Y=U9($);if(!z){let K=`{
|
|
94
95
|
"$schema": "https://opencode.ai/config.json",
|
|
95
96
|
"plugin": [
|
|
96
|
-
"${
|
|
97
|
+
"${Y}"
|
|
97
98
|
]
|
|
98
99
|
}
|
|
99
|
-
`;return await
|
|
100
|
+
`;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}}async function F9($,Z=process.env){let J=E0(Z);await V9(J,{recursive:!0});let{path:Q,exists:z}=S8(J),Y=q9($);if(!z){let K=`{
|
|
100
101
|
"plugin": [
|
|
101
|
-
"${
|
|
102
|
+
"${Y}"
|
|
102
103
|
]
|
|
103
104
|
}
|
|
104
|
-
`;return await N1(Q,j,"utf8"),{configPath:Q,changed:!0,created:!0}}let{text:G}=v0(Q),{text:Y,changed:X}=_3(G,["plugin"],W,E2);if(X)await N1(Q,Y,"utf8");return{configPath:Q,changed:X,created:!1}}import{existsSync as x2}from"node:fs";import{readFile as p4,writeFile as TZ}from"node:fs/promises";import{join as c4}from"node:path";function g2($=process.env){let Z=c4(P0($),"settings.json");if(!x2(Z))return!1;try{let Q=JSON.parse(d4(Z))?.packages;if(!Array.isArray(Q))return!1;return Q.some((z)=>{let W=typeof z==="string"?z:typeof z==="object"&&z!==null?z.source:"";if(typeof W!=="string")return!1;return W===p0||W.startsWith(`${p0}@`)||W===`npm:${p0}`||W.startsWith(`npm:${p0}@`)})}catch{return!1}}function d4($){return x3("node:fs").readFileSync($,"utf8")}async function T2($=process.env){let Z=Y1($);if(!x2(Z))return!1;try{let J=await p4(Z,"utf8"),Q=JSON.parse(J);return Boolean(Q?.anthropic&&typeof Q.anthropic==="object")}catch{return!1}}async function h2($,Z=l,J=process.env){let Q=S2($),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}`}}async function u4($=process.env,Z=l){let J=await Z.run("opencode",["--version"],{env:$}),Q=J.exitCode===0,z=Q?J.stdout.trim()||null:null,W=q0($),{path:G,exists:Y}=S3(W),X=!1;if(Y){let{value:H}=v0(G);if(Array.isArray(H?.plugin))X=H.plugin.some((K)=>typeof K==="string"&&(K===k0||K.startsWith(`${k0}@`)))}return{kind:"opencode",installed:Q||Y||g3(W1($)),version:z,configPath:G,pluginInstalled:X}}async function l4($=process.env,Z=l){let J=await Z.run("pi",["--version"],{env:$}),Q=J.exitCode===0,z=null;if(Q){let j=J.stdout.trim()||J.stderr.trim();z=j.split(/\r?\n/).find((K)=>/^\d+\.\d+\.\d+/.test(K.trim()))?.trim()??j??null}let W=P0($),G=Q||g3(W),Y=g2($),X=await T2($);return{kind:"pi",installed:G,version:z,configPath:W,pluginInstalled:Y,hasLocalAuth:X}}async function i4($=process.env,Z=l){let J=await Z.run("ck",["--version"],{env:$}),Q=J.exitCode===0,z=Q?J.stdout.trim()||null:null,W=null,G=!1;try{if(W=J1(void 0,$),W&&g3(W)){let Y=await y2({connectionFile:W,handshakeTimeoutMs:2000});G=!0,Y.close()}}catch{G=!1}return{ckInstalled:Q,ckVersion:z,daemonRunning:G,connectionPath:W}}async function m2($=process.env,Z=l){let[J,Q,z]=await Promise.all([u4($,Z),l4($,Z),i4($,Z)]);return{opencode:J,pi:Q,claustrum:z}}async function p2($,Z){let J={...Z.env},Q=async()=>{if(X1(J),await I0(Z.fence),await z0($,J)!=="local")throw Error("Disconnect from the vault first.")};await Q();let z=Z.paths??await O0($,J),W=await Z.login?.($);if(W&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(W.accountIdentity))throw Error("Claude sign-in did not establish an account UUID");if(await Q(),await v2({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}),W){let G=f0({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,...W})}finally{G.close()}}}async function d2($){let Z=await O1("max");L1(Z.url,`Claude sign-in for ${$==="pi"?"Pi":"OpenCode"}`);let J=await f2({message:"Paste the Claude callback URL or authorization code:"});if(G0(J))throw Error("Claude sign-in cancelled");let Q=await I1(J,Z.verifier,Z.redirectUri,Z.state);if(Q.type!=="success")throw Error("Claude sign-in failed");let z=await c2(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 l2($=[],Z={}){let J=Z.env??process.env,Q=Z.runner??l,z=Z.fence??j3,W=Z.activate??C$,G=Z.migrateLocal??p2,Y={output:Z.output},X=$.includes("--yes")||$.includes("-y"),j=$.includes("--dry-run"),H=$.includes("--no-claustrum"),K=$.includes("--claustrum"),U=$.includes("--remove-pi-auth"),V=$.includes("--login"),q=V?Z.localLogin??d2:void 0;if(V&&K)return h.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",Y),1;O2("CortexKit Anthropic Auth Setup",Y);let B=I2(Y);B.start("Detecting installed environments…");let I=await(Z.detect??m2)(J,Q);B.stop("Environment detection complete.");let N=I.opencode.installed?`detected (${I.opencode.version??"version unknown"}, ${I.opencode.pluginInstalled?"plugin already configured":"plugin not configured"})`:"not found",A=I.pi.installed?`detected (${I.pi.version??"version unknown"}, ${I.pi.pluginInstalled?"extension already installed":"extension not installed"})`:"not found",w=I.claustrum.daemonRunning?`daemon running (${I.claustrum.ckVersion??"ck ready"})`:I.claustrum.ckInstalled?"ck installed, daemon not running":"not installed";if(h.info(`OpenCode: ${N}`,Y),h.info(`Pi: ${A}`,Y),h.info(`Claustrum: ${w}`,Y),!I.opencode.installed&&!I.pi.installed)return h.error("Neither OpenCode nor Pi was detected on this system.",Y),t("Install OpenCode (https://opencode.ai) or Pi (https://github.com/badlogic/pi-mono) first.",Y),1;let M=[];if(X){if(I.opencode.installed)M.push("opencode");if(I.pi.installed)M.push("pi")}else{let C=[];if(I.opencode.installed)C.push({value:"opencode",label:"OpenCode",hint:I.opencode.pluginInstalled?"already configured":"configure plugin + TUI sidebar"});if(I.pi.installed)C.push({value:"pi",label:"Pi",hint:I.pi.pluginInstalled?"already installed":"install provider extension"});let x=await P2({message:"Select integrations to configure:",options:C,initialValues:C.map((b)=>b.value),required:!0,...Y});if(G0(x))return t("Setup cancelled.",Y),0;M=x}if(M.length===0)return t("No integrations selected.",Y),0;let D=!1;if(I.claustrum.daemonRunning&&I.claustrum.ckInstalled&&!H){if(K)D=!0;else if(!X){let C=await E3({message:"Use Claude accounts from the Claustrum vault? Local account files stay unchanged and are not used while connected.",initialValue:!1,...Y});if(G0(C))return t("Setup cancelled.",Y),0;D=C}}if(q&&D)return h.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",Y),1;if(q||!D){for(let C of M)if(await z0(C,J)!=="local")return h.error("Disconnect from the vault first.",Y),1}let k=!1;if(M.includes("pi")&&I.pi.hasLocalAuth)if(X){if(!U)return h.error(D?"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.",Y),t("Setup aborted.",Y),1;k=!0}else{h.warn(D?"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.",Y);let C=await E3({message:D?"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,...Y});if(G0(C)||!C)return h.error("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.",Y),t("Setup aborted.",Y),1;k=!0}try{await I0(z)}catch(C){return h.error(await W0("setup-process-check",C,J),Y),t("Setup aborted — quit active hosts and rerun setup.",Y),1}let E=[];for(let C of M)E.push(await O0(C,J));if(await I$(E),j){if(h.info("[dry-run] Planned actions:",Y),h.info(` - Target integrations: ${M.join(", ")}`,Y),h.info(` - Claustrum custody: ${D?"enabled":"disabled"}`,Y),k)h.info(" - Pi local OAuth token will be removed",Y);return t("Dry run complete. No changes were made.",Y),0}let S=await u2(),m=async(C,x)=>{B.start(`Switching ${x} to Claustrum vault custody…`);try{let b=await W(C,{env:J,runner:Q,fence:z,removePiAnthropicAuth:C==="pi"&&k});return B.stop(b==="already-vault"?`${x} already uses Claustrum vault custody.`:`${x} now uses Claustrum vault custody.`),!0}catch(b){return B.stop(`${x} vault custody setup failed.`),h.error(await W0("setup-activation",b,J),Y),!1}};if(M.includes("opencode")){B.start("Configuring OpenCode plugin and TUI sidebar…");try{await w2(S,J),await _2(S,J),B.stop("OpenCode configuration updated.")}catch(C){return B.stop("OpenCode setup failed."),h.error(await W0("setup-opencode-config",C,J),Y),1}if(q||!D)await G("opencode",{env:J,fence:z,removePiAnthropicAuth:!1,login:q});if(D&&!await m("opencode","OpenCode"))return 1}if(M.includes("pi")){B.start("Installing Pi Anthropic extension…");try{let C=await h2(S,Q,J);if(!C.ok)return B.stop("Pi extension installation failed."),h.error(await m$("setup-pi-install",C,J),Y),1;B.stop("Pi Anthropic extension installed.")}catch(C){return B.stop("Pi setup failed."),h.error(await W0("setup-pi",C,J),Y),1}if(q||!D)await G("pi",{env:J,fence:z,removePiAnthropicAuth:k,login:q});if(D&&!await m("pi","Pi"))return 1}let T=[];if(M.includes("opencode"))T.push("• Start OpenCode normally (opencode).");if(M.includes("pi"))T.push("• Start Pi normally (pi).");if(D)T.push("• Manage accounts in Claustrum with: ck auth login --provider anthropic"),T.push(" Newly added accounts will be discovered automatically without restarting.");return L1(T.join(`
|
|
105
|
-
`),"Next Steps",
|
|
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),K0("Setup complete!",W),0}async function a0($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await A1(),J=d0({paths:Z,host:"opencode"});try{return await J.read(),await $(J)}finally{J.close()}}async function n1(){if(await N0("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function S9(){console.log(`Usage:
|
|
106
107
|
opencode-anthropic-auth setup [--yes] [--dry-run]
|
|
107
108
|
opencode-anthropic-auth login [label]
|
|
108
109
|
opencode-anthropic-auth api add [label]
|
|
@@ -111,9 +112,9 @@ ${Y}
|
|
|
111
112
|
|
|
112
113
|
Native credentials are managed by the offline setup migration.
|
|
113
114
|
Legacy import source:
|
|
114
|
-
${
|
|
115
|
+
${w9()}`)}function Y$($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function r1($){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}),Q=await J.text(),z;try{z=JSON.parse(Q)}catch{throw Error(`Cloudflare API returned ${J.status}: ${Q}`)}if(!J.ok||z.success===!1){let Y=z.errors?.map((G)=>G.message).filter(Boolean).join("; ");throw Error(Y||`Cloudflare API returned ${J.status}`)}return z.result}async function d8($,Z,J,Q){return r1({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:Q})}async function u8($){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([h9],{type:"application/javascript+module"}),"worker.js"),r1({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function l8($,Z,J,Q){await r1({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:Q})}async function i8($,Z,J){return r1({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function a8($={}){await a0((M)=>M.read());let Z=$.fetchImpl??fetch,J=$.prompt??o1,Q=$.warn??((M)=>console.warn(M)),z=Y$(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(z);let Y=Y$(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=g9();$.secrets?.push(X),console.log("Creating Cloudflare KV namespace...");let K=await d8(z,Y,W,Z);console.log("Uploading relay Worker..."),await u8({token:z,accountId:Y,scriptName:G,kvNamespaceId:K.id,relayToken:X,fetchImpl:Z}),await l8(z,Y,G,Z).catch(async(M)=>{Q(await B0("cli-relay-workers-dev",M,process.env,[z,X]))});let H=await i8(z,Y,Z),U=(H?.subdomain?`https://${G}.${H.subdomain}.workers.dev`:"")||Y$(await o1("Relay Worker URL: "),"Relay Worker URL");await a0((M)=>M.updateRelay({enabled:!0,url:U,token:X,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${U}`),console.log("Relay settings saved to the native account store.")}var s1=null;async function o1($){return s1??=p8({input:v8,output:c8}),(await s1.question($)).trim()}function n8(){s1?.close(),s1=null}async function s8($,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??o1,Q=Z.authorize??i1,z=Z.exchange??a1;await n1(),await a0(async(Y)=>{let G=await Y.read(),W=$?.trim()||await J("Fallback account label (optional): "),X=await Q("max");console.log(`
|
|
115
116
|
Open this URL in your browser and complete Claude sign-in:
|
|
116
117
|
`),console.log(`${X.url}
|
|
117
|
-
`);let
|
|
118
|
-
Saved native fallback account${
|
|
119
|
-
Saved API fallback route${Q?` "${Q}"`:""} (${z}).`)}async function
|
|
118
|
+
`);let K=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(K);let H=await z(K,X.verifier,X.redirectUri,X.state);if(H.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(H.access,H.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await n1();let j=W&&W!=="main"?W:crypto.randomUUID(),U=G.accounts.some((M)=>M.id===j&&M.source==="local");await Y.loginOAuth({routeId:j,replace:U,label:W||void 0,credential:{access:H.access,refresh:H.refresh,expires:H.expires}}),console.log(`
|
|
119
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function o8($,Z={}){await n1(),await a0((X)=>X.read());let J=Z.prompt??o1,Q=$?.trim()||await J("API fallback label (optional): "),z=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(!x9(z))throw Error("API fallback base URL must be an http(s) URL without embedded credentials");let Y=process.env.OPENCODE_ANTHROPIC_AUTH_API_KEY?.trim()||await J("API key: ");if(!Y.trim())throw Error("API key is required");Z.secrets?.push(Y.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 a0(async(X)=>{await n1();let K=await X.read(),H=Q&&Q!=="main"?Q:crypto.randomUUID(),j=K.accounts.find((U)=>U.id===H);if(j?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await X.addApi({routeId:H,replace:Boolean(j),label:Q||void 0,apiKey:Y.trim(),baseURL:z,authHeader:W})}),console.log(`
|
|
120
|
+
Saved API fallback route${Q?` "${Q}"`:""} (${z}).`)}async function r8(){await a0(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,Q]of Z.entries()){let z=Q.label||Q.id,Y=Q.enabled?"enabled":"disabled";if(Q.type==="api"){console.log(`${J+1}. ${z} (${Y}) — API route ${Q.baseURL}`);continue}let G=Q.quota?.five_hour?.remainingPercent,W=Q.quota?.seven_day?.remainingPercent,X=G===void 0&&W===void 0?"quota unknown":`5h ${G??"?"}%, 1w ${W??"?"}% remaining`;console.log(`${J+1}. ${z} (${Y}) — ${X}${Q.state?` — ${T9(Q)}`:""}`)}})}async function t8($){let[Z,J,Q]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){S9();return}if(Z==="setup"){$.stage="cli-setup";let z=await E9(process.argv.slice(3));if(z!==0)process.exitCode=z;return}if(Z==="login"){$.stage="cli-login",await s8(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await o8(Q,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await r8();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await a8({secrets:$.secrets});return}S9(),process.exitCode=1}if(j1.main==j1.module){let $={stage:"cli-command",secrets:[]};try{await t8($)}catch(Z){console.error(await B0($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{n8()}}export{E9 as runSetupCommand,a8 as relaySetup,s8 as login,o8 as addApiRoute};
|