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